Bayesian Sampler Examples

Examples of running each sampler avaiable in 3ML.

Before, that, let’s discuss setting up configuration default sampler with default parameters. We can set in our configuration a default algorithm and default setup parameters for the samplers. This can ease fitting when we are doing exploratory data analysis.

With any of the samplers, you can pass keywords to access their setups. Read each pacakges documentation for more details.

[1]:
from threeML import *
from threeML.plugins.XYLike import XYLike

import numpy as np
import dynesty
from jupyterthemes import jtplot

%matplotlib inline
jtplot.style(context="talk", fscale=1, ticks=True, grid=False)
silence_warnings()
set_threeML_style()
22:01:47 WARNING   The naima package is not available. Models that depend on it will not be         functions.py:48
                  available                                                                                        
         WARNING   The GSL library or the pygsl wrapper cannot be loaded. Models that depend on it  functions.py:69
                  will not be available.                                                                           
22:01:48 WARNING   The ebltable package is not available. Models that depend on it will not be     absorption.py:33
                  available                                                                                        
[2]:
threeML_config.bayesian.default_sampler
[2]:
<Sampler.emcee: 'emcee'>
[3]:
threeML_config.bayesian.emcee_setup
[3]:
{'n_burnin': None, 'n_iterations': 500, 'n_walkers': 50, 'seed': 5123}

If you simply run bayes_analysis.sample() the default sampler and its default parameters will be used.

Let’s make some data to fit.

[4]:
sin = Sin(K=1, f=0.1)
sin.phi.fix = True
sin.K.prior = Log_uniform_prior(lower_bound=0.5, upper_bound=1.5)
sin.f.prior = Uniform_prior(lower_bound=0, upper_bound=0.5)

model = Model(PointSource("demo", 0, 0, spectral_shape=sin))

x = np.linspace(-2 * np.pi, 4 * np.pi, 20)
yerr = np.random.uniform(0.01, 0.2, 20)


xyl = XYLike.from_function("demo", sin, x, yerr)
xyl.plot()

bayes_analysis = BayesianAnalysis(model, DataList(xyl))
22:01:49 INFO      Using Gaussian statistic (equivalent to chi^2) with the provided errors.            XYLike.py:93
22:01:50 INFO      Using Gaussian statistic (equivalent to chi^2) with the provided errors.            XYLike.py:93
../_images/notebooks_sampler_docs_5_2.png

emcee

[5]:
bayes_analysis.set_sampler("emcee")
bayes_analysis.sampler.setup(n_walkers=20, n_iterations=500)
bayes_analysis.sample()

xyl.plot()
bayes_analysis.results.corner_plot()
         INFO      sampler set to emcee                                                    bayesian_analysis.py:202
22:01:53 INFO      Mean acceptance fraction: 0.7218                                            emcee_sampler.py:157
22:01:54 INFO      fit restored to maximum of posterior                                         sampler_base.py:178
         INFO      fit restored to maximum of posterior                                         sampler_base.py:178
Maximum a posteriori probability (MAP) point:

result unit
parameter
demo.spectrum.main.Sin.K 1.013 -0.015 +0.017 1 / (cm2 keV s)
demo.spectrum.main.Sin.f (1.005 +/- 0.005) x 10^-1 rad / keV
Values of -log(posterior) at the minimum:

-log(posterior)
demo -6.762638
total -6.762638
Values of statistical measures:

statistical measures
AIC 18.231158
BIC 19.516740
DIC 17.308502
PDIC 1.885384
[5]:
../_images/notebooks_sampler_docs_7_12.png
../_images/notebooks_sampler_docs_7_13.png
../_images/notebooks_sampler_docs_7_14.png

multinest

[6]:
bayes_analysis.set_sampler("multinest")
bayes_analysis.sampler.setup(n_live_points=400, resume=False, auto_clean=True)
bayes_analysis.sample()

xyl.plot()
bayes_analysis.results.corner_plot()
22:01:55 INFO      sampler set to multinest                                                bayesian_analysis.py:202
 *****************************************************
 MultiNest v3.10
 Copyright Farhan Feroz & Mike Hobson
 Release Jul 2015

 no. of live points =  400
 dimensionality =    2
 *****************************************************
 ln(ev)=  -15.960051662356523      +/-  0.14355960779352378
  analysing data from chains/fit-.txt
 Total Likelihood Evaluations:         6168
 Sampling finished. Exiting MultiNest
22:01:56 INFO      fit restored to maximum of posterior                                         sampler_base.py:178
         INFO      fit restored to maximum of posterior                                         sampler_base.py:178
Maximum a posteriori probability (MAP) point:

result unit
parameter
demo.spectrum.main.Sin.K 1.013 -0.017 +0.015 1 / (cm2 keV s)
demo.spectrum.main.Sin.f (1.004 +/- 0.005) x 10^-1 rad / keV
Values of -log(posterior) at the minimum:

-log(posterior)
demo -6.762828
total -6.762828
Values of statistical measures:

statistical measures
AIC 18.231538
BIC 19.517120
DIC 17.477867
PDIC 1.976215
log(Z) -6.931362
         INFO      deleting the chain directory chains                                     multinest_sampler.py:255
[6]:
../_images/notebooks_sampler_docs_9_11.png
../_images/notebooks_sampler_docs_9_12.png
../_images/notebooks_sampler_docs_9_13.png

dynesty

[7]:
bayes_analysis.set_sampler("dynesty_nested")
bayes_analysis.sampler.setup(n_live_points=400)
bayes_analysis.sample()

xyl.plot()
bayes_analysis.results.corner_plot()
         INFO      sampler set to dynesty_nested                                           bayesian_analysis.py:202
4243it [00:04, 888.77it/s, +400 | bound: 8 | nc: 1 | ncall: 19785 | eff(%): 23.952 | loglstar:   -inf < -6.750 <    inf | logz: -16.308 +/-  0.146 | dlogz:  0.001 >  0.409]
22:02:01 INFO      fit restored to maximum of posterior                                         sampler_base.py:178
         INFO      fit restored to maximum of posterior                                         sampler_base.py:178
Maximum a posteriori probability (MAP) point:

result unit
parameter
demo.spectrum.main.Sin.K 1.013 -0.017 +0.015 1 / (cm2 keV s)
demo.spectrum.main.Sin.f (1.005 +/- 0.005) x 10^-1 rad / keV
Values of -log(posterior) at the minimum:

-log(posterior)
demo -6.763276
total -6.763276
Values of statistical measures:

statistical measures
AIC 18.232434
BIC 19.518016
DIC 17.488523
PDIC 1.981774
log(Z) -7.082663
[7]:
../_images/notebooks_sampler_docs_11_10.png
../_images/notebooks_sampler_docs_11_11.png
../_images/notebooks_sampler_docs_11_12.png
[8]:
bayes_analysis.set_sampler("dynesty_dynamic")
bayes_analysis.sampler.setup(
    stop_function=dynesty.utils.old_stopping_function, n_effective=None
)
bayes_analysis.sample()

xyl.plot()
bayes_analysis.results.corner_plot()
22:02:02 INFO      sampler set to dynesty_dynamic                                          bayesian_analysis.py:202
7289it [00:07, 1877.45it/s, batch: 0 | bound: 12 | nc: 1 | ncall: 26603 | eff(%): 27.216 | loglstar:   -inf < -6.754 <    inf | logz: -16.064 +/-  0.129 | dlogz:  0.004 >  0.010]
WARNING DeprecationWarning: This an old stopping function that will be removed in future releases

8038it [00:09, 916.76it/s, batch: 1 | bound: 3 | nc: 1 | ncall: 27702 | eff(%): 28.486 | loglstar: -8.573 < -7.297 < -7.291 | logz: -16.061 +/-  0.133 | stop:  1.439]
WARNING DeprecationWarning: This an old stopping function that will be removed in future releases

8864it [00:10, 919.54it/s, batch: 2 | bound: 2 | nc: 1 | ncall: 28588 | eff(%): 30.663 | loglstar: -9.097 < -7.839 < -8.573 | logz: -16.052 +/-  0.109 | stop:  1.130]
WARNING DeprecationWarning: This an old stopping function that will be removed in future releases

9159it [00:10, 851.68it/s, batch: 2 | bound: 2 | nc: 1 | ncall: 28908 | eff(%): 31.683 | loglstar: -9.097 < -6.753 < -8.573 | logz: -16.052 +/-  0.109 | stop:  0.938]
22:02:13 INFO      fit restored to maximum of posterior                                         sampler_base.py:178
         INFO      fit restored to maximum of posterior                                         sampler_base.py:178
Maximum a posteriori probability (MAP) point:

result unit
parameter
demo.spectrum.main.Sin.K 1.013 +/- 0.016 1 / (cm2 keV s)
demo.spectrum.main.Sin.f (1.005 +/- 0.005) x 10^-1 rad / keV
Values of -log(posterior) at the minimum:

-log(posterior)
demo -6.762426
total -6.762426
Values of statistical measures:

statistical measures
AIC 18.230734
BIC 19.516316
DIC 17.443250
PDIC 1.958775
log(Z) -6.965615
[8]:
../_images/notebooks_sampler_docs_12_10.png
../_images/notebooks_sampler_docs_12_11.png
../_images/notebooks_sampler_docs_12_12.png

zeus

[9]:
bayes_analysis.set_sampler("zeus")
bayes_analysis.sampler.setup(n_walkers=20, n_iterations=500)
bayes_analysis.sample()

xyl.plot()
bayes_analysis.results.corner_plot()
22:02:14 INFO      sampler set to zeus                                                     bayesian_analysis.py:202
WARNING:root:The sampler class has been deprecated. Please use the new EnsembleSampler class.
The run method has been deprecated and it will be removed. Please use the new run_mcmc method.
Initialising ensemble of 20 walkers...
Sampling progress : 100%|██████████| 625/625 [00:10<00:00, 57.10it/s]
22:02:26 INFO      fit restored to maximum of posterior                                         sampler_base.py:178
         INFO      fit restored to maximum of posterior                                         sampler_base.py:178
Summary
-------
Number of Generations: 625
Number of Parameters: 2
Number of Walkers: 20
Number of Tuning Generations: 19
Scale Factor: 1.063141
Mean Integrated Autocorrelation Time: 3.22
Effective Sample Size: 3887.79
Number of Log Probability Evaluations: 65764
Effective Samples per Log Probability Evaluation: 0.059117
None
Maximum a posteriori probability (MAP) point:

result unit
parameter
demo.spectrum.main.Sin.K 1.013 +/- 0.016 1 / (cm2 keV s)
demo.spectrum.main.Sin.f (1.005 +/- 0.005) x 10^-1 rad / keV
Values of -log(posterior) at the minimum:

-log(posterior)
demo -6.762503
total -6.762503
Values of statistical measures:

statistical measures
AIC 18.230888
BIC 19.516470
DIC 17.537700
PDIC 2.006148
[9]:
../_images/notebooks_sampler_docs_14_12.png
../_images/notebooks_sampler_docs_14_13.png
../_images/notebooks_sampler_docs_14_14.png

ultranest

[10]:
bayes_analysis.set_sampler("ultranest")
bayes_analysis.sampler.setup(
    min_num_live_points=400, frac_remain=0.5, use_mlfriends=False
)
bayes_analysis.sample()

xyl.plot()
bayes_analysis.results.corner_plot()
22:02:27 INFO      sampler set to ultranest                                                bayesian_analysis.py:202
[ultranest] Sampling 400 live points from prior ...
[ultranest] Explored until L=-7
[ultranest] Likelihood function evaluations: 6481
[ultranest]   logZ = -16.2 +- 0.1157
[ultranest] Effective samples strategy satisfied (ESS = 969.3, need >400)
[ultranest] Posterior uncertainty strategy is satisfied (KL: 0.47+-0.07 nat, need <0.50 nat)
[ultranest] Evidency uncertainty strategy is satisfied (dlogz=0.42, need <0.5)
[ultranest]   logZ error budget: single: 0.15 bs:0.12 tail:0.41 total:0.42 required:<0.50
[ultranest] done iterating.
22:02:35 INFO      fit restored to maximum of posterior                                         sampler_base.py:178
         INFO      fit restored to maximum of posterior                                         sampler_base.py:178
Maximum a posteriori probability (MAP) point:

result unit
parameter
demo.spectrum.main.Sin.K 1.012 +/- 0.017 1 / (cm2 keV s)
demo.spectrum.main.Sin.f (1.005 +/- 0.005) x 10^-1 rad / keV
Values of -log(posterior) at the minimum:

-log(posterior)
demo -6.763056
total -6.763056
Values of statistical measures:

statistical measures
AIC 18.231994
BIC 19.517576
DIC 17.515318
PDIC 1.994916
log(Z) -7.032023
[10]:
../_images/notebooks_sampler_docs_16_12.png
../_images/notebooks_sampler_docs_16_13.png
../_images/notebooks_sampler_docs_16_14.png