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()
18:42:53 WARNING   The naima package is not available. Models that depend on it will not be         functions.py:48
                  available                                                                                        
18:42:54 WARNING   The GSL library or the pygsl wrapper cannot be loaded. Models that depend on it  functions.py:69
                  will not be available.                                                                           
         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))
18:42:55 INFO      Using Gaussian statistic (equivalent to chi^2) with the provided errors.            XYLike.py:93
18:42:56 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
18:42:59 INFO      Mean acceptance fraction: 0.7161                                            emcee_sampler.py:157
18:43:00 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 (9.83 -0.19 +0.20) x 10^-1 1 / (cm2 keV s)
demo.spectrum.main.Sin.f (9.94 +/- 0.05) x 10^-2 rad / keV
Values of -log(posterior) at the minimum:

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

statistical measures
AIC 15.451751
BIC 16.737334
DIC 14.871668
PDIC 2.062935
[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()
         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
 *****************************************************
  analysing data from chains/fit-.txt ln(ev)=  -14.612982646727215      +/-  0.14299798749126899
 Total Likelihood Evaluations:         5226
 Sampling finished. Exiting MultiNest

18:43: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 (9.82 -0.22 +0.21) x 10^-1 1 / (cm2 keV s)
demo.spectrum.main.Sin.f (9.95 +/- 0.05) x 10^-2 rad / keV
Values of -log(posterior) at the minimum:

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

statistical measures
AIC 15.453212
BIC 16.738794
DIC 15.049305
PDIC 2.149384
log(Z) -6.346338
         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()
18:43:02 INFO      sampler set to dynesty_nested                                           bayesian_analysis.py:202
3979it [00:04, 897.13it/s, +400 | bound: 8 | nc: 1 | ncall: 19098 | eff(%): 23.420 | loglstar:   -inf < -5.392 <    inf | logz: -14.288 +/-  0.140 | dlogz:  0.001 >  0.409]
18:43:07 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 (9.82 -0.19 +0.20) x 10^-1 1 / (cm2 keV s)
demo.spectrum.main.Sin.f (9.94 +/- 0.05) x 10^-2 rad / keV
Values of -log(posterior) at the minimum:

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

statistical measures
AIC 15.452760
BIC 16.738342
DIC 14.675127
PDIC 1.964338
log(Z) -6.205398
[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()
         INFO      sampler set to dynesty_dynamic                                          bayesian_analysis.py:202
7166it [00:07, 1918.33it/s, batch: 0 | bound: 12 | nc: 1 | ncall: 25887 | eff(%): 27.507 | loglstar:   -inf < -5.393 <    inf | logz: -14.430 +/-  0.127 | dlogz:  0.003 >  0.010]
WARNING DeprecationWarning: This an old stopping function that will be removed in future releases

8341it [00:08, 1528.13it/s, batch: 1 | bound: 3 | nc: 2 | ncall: 27484 | eff(%): 30.099 | loglstar: -7.267 < -5.573 < -5.835 | logz: -14.427 +/-  0.130 | stop:  1.422]
WARNING DeprecationWarning: This an old stopping function that will be removed in future releases

9022it [00:09, 1050.32it/s, batch: 2 | bound: 2 | nc: 1 | ncall: 28232 | eff(%): 31.777 | loglstar: -7.791 < -5.931 < -7.267 | logz: -14.424 +/-  0.106 | stop:  1.133]
WARNING DeprecationWarning: This an old stopping function that will be removed in future releases

9275it [00:10, 607.38it/s, batch: 3 | bound: 2 | nc: 1 | ncall: 28511 | eff(%): 31.996 | loglstar: -8.216 < -7.550 < -7.784 | logz: -14.411 +/-  0.099 | stop:  1.015]
WARNING DeprecationWarning: This an old stopping function that will be removed in future releases

9738it [00:10, 885.48it/s, batch: 3 | bound: 2 | nc: 1 | ncall: 28988 | eff(%): 33.593 | loglstar: -8.216 < -5.410 < -7.784 | logz: -14.411 +/-  0.099 | stop:  0.894]
18:43:19 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 (9.82 -0.20 +0.19) x 10^-1 1 / (cm2 keV s)
demo.spectrum.main.Sin.f (9.94 +/- 0.05) x 10^-2 rad / keV
Values of -log(posterior) at the minimum:

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

statistical measures
AIC 15.451885
BIC 16.737468
DIC 14.653284
PDIC 1.953641
log(Z) -6.250917
[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()
         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:09<00:00, 66.64it/s]
18:43:29 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: 28
Scale Factor: 1.572088
Mean Integrated Autocorrelation Time: 2.98
Effective Sample Size: 4197.65
Number of Log Probability Evaluations: 64355
Effective Samples per Log Probability Evaluation: 0.065227
None
Maximum a posteriori probability (MAP) point:

result unit
parameter
demo.spectrum.main.Sin.K (9.82 -0.19 +0.20) x 10^-1 1 / (cm2 keV s)
demo.spectrum.main.Sin.f (9.94 +/- 0.05) x 10^-2 rad / keV
Values of -log(posterior) at the minimum:

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

statistical measures
AIC 15.451512
BIC 16.737094
DIC 14.693727
PDIC 1.973932
[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()
18:43:30 INFO      sampler set to ultranest                                                bayesian_analysis.py:202
[ultranest] Sampling 400 live points from prior ...
[ultranest] Explored until L=-5
[ultranest] Likelihood function evaluations: 7923
[ultranest]   logZ = -14.54 +- 0.103
[ultranest] Effective samples strategy satisfied (ESS = 977.3, need >400)
[ultranest] Posterior uncertainty strategy is satisfied (KL: 0.45+-0.06 nat, need <0.50 nat)
[ultranest] Evidency uncertainty strategy is satisfied (dlogz=0.42, need <0.5)
[ultranest]   logZ error budget: single: 0.14 bs:0.10 tail:0.41 total:0.42 required:<0.50
[ultranest] done iterating.
18:43:38 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 (9.81 -0.18 +0.21) x 10^-1 1 / (cm2 keV s)
demo.spectrum.main.Sin.f (9.94 +/- 0.05) x 10^-2 rad / keV
Values of -log(posterior) at the minimum:

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

statistical measures
AIC 15.457655
BIC 16.743237
DIC 14.871057
PDIC 2.062487
log(Z) -6.317673
[10]:
../_images/notebooks_sampler_docs_16_12.png
../_images/notebooks_sampler_docs_16_13.png
../_images/notebooks_sampler_docs_16_14.png