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()
19:51:16 WARNING   The naima package is not available. Models that depend on it will not be         functions.py:50
                  available                                                                                        
         WARNING   The GSL library or the pygsl wrapper cannot be loaded. Models that depend on it  functions.py:71
                  will not be available.                                                                           
         WARNING   The ebltable package is not available. Models that depend on it will not be     absorption.py:36
                  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))
19:51:18 INFO      Using Gaussian statistic (equivalent to chi^2) with the provided errors.            XYLike.py:89
19:51:19 INFO      Using Gaussian statistic (equivalent to chi^2) with the provided errors.            XYLike.py:89
../_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:197
19:51:23 INFO      Mean acceptance fraction: 0.6519                                            emcee_sampler.py:157
19:51:24 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.010 -0.023 +0.020 1 / (cm2 keV s)
demo.spectrum.main.Sin.f (1.0025 -0.0022 +0.0016) x 10^-1 rad / keV
Values of -log(posterior) at the minimum:

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

statistical measures
AIC 11.048438
BIC 12.334021
DIC 149.652575
PDIC -15.959611
[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()
19:51:26 INFO      sampler set to multinest                                                bayesian_analysis.py:197
 *****************************************************
 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)=  -13.082599077406002      +/-  0.14950389179649995
 Total Likelihood Evaluations:         7153
 Sampling finished. Exiting MultiNest

19:51:27 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.010 -0.019 +0.021 1 / (cm2 keV s)
demo.spectrum.main.Sin.f (1.0025 +/- 0.0017) x 10^-1 rad / keV
Values of -log(posterior) at the minimum:

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

statistical measures
AIC 11.048768
BIC 12.334350
DIC 10.357805
PDIC 2.007589
log(Z) -5.681701
         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()
19:51:28 INFO      sampler set to dynesty_nested                                           bayesian_analysis.py:197
4587it [00:11, 404.53it/s, +400 | bound: 9 | nc: 1 | ncall: 20710 | eff(%): 24.554 | loglstar:   -inf < -3.161 <    inf | logz: -13.576 +/-  0.153 | dlogz:  0.001 >  0.409]
19:51:40 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.010 -0.019 +0.021 1 / (cm2 keV s)
demo.spectrum.main.Sin.f (1.0026 +/- 0.0018) x 10^-1 rad / keV
Values of -log(posterior) at the minimum:

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

statistical measures
AIC 11.049461
BIC 12.335043
DIC 10.343681
PDIC 2.000033
log(Z) -5.895883
[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()
19:51:41 INFO      sampler set to dynesty_dynamic                                          bayesian_analysis.py:197
7855it [00:16, 1213.93it/s, batch: 0 | bound: 14 | nc: 1 | ncall: 27492 | eff(%): 28.497 | loglstar:   -inf < -3.162 <    inf | logz: -13.389 +/-  0.136 | dlogz:  0.001 >  0.010]
WARNING DeprecationWarning: This an old stopping function that will be removed in future releases

9074it [00:19, 1277.24it/s, batch: 1 | bound: 3 | nc: 1 | ncall: 29214 | eff(%): 31.035 | loglstar: -4.935 < -3.183 < -3.628 | logz: -13.387 +/-  0.140 | stop:  1.476]
WARNING DeprecationWarning: This an old stopping function that will be removed in future releases

9725it [00:20, 692.95it/s, batch: 2 | bound: 2 | nc: 2 | ncall: 29916 | eff(%): 32.499 | loglstar: -5.431 < -3.202 < -4.934 | logz: -13.397 +/-  0.115 | stop:  1.059]
WARNING DeprecationWarning: This an old stopping function that will be removed in future releases

9733it [00:21, 459.21it/s, batch: 2 | bound: 2 | nc: 1 | ncall: 29924 | eff(%): 32.526 | loglstar: -5.431 < -3.165 < -4.934 | logz: -13.397 +/-  0.115 | stop:  0.961]
19:52:03 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.011 +/- 0.020 1 / (cm2 keV s)
demo.spectrum.main.Sin.f (1.0025 -0.0017 +0.0018) x 10^-1 rad / keV
Values of -log(posterior) at the minimum:

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

statistical measures
AIC 11.048182
BIC 12.333764
DIC 10.351666
PDIC 2.004460
log(Z) -5.819696
[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()
19:52:04 INFO      sampler set to zeus                                                     bayesian_analysis.py:197
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:20<00:00, 31.08it/s]
19:52:25 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: 20
Scale Factor: 0.747577
Mean Integrated Autocorrelation Time: 259.21
Effective Sample Size: 48.22
Number of Log Probability Evaluations: 77336
Effective Samples per Log Probability Evaluation: 0.000624
None
Maximum a posteriori probability (MAP) point:

result unit
parameter
demo.spectrum.main.Sin.K 1.011 -0.024 +0.019 1 / (cm2 keV s)
demo.spectrum.main.Sin.f (1.0025 -0.0021 +0.0017) x 10^-1 rad / keV
Values of -log(posterior) at the minimum:

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

statistical measures
AIC 11.048045
BIC 12.333627
DIC 115.593121
PDIC -5.099908
[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()
         INFO      sampler set to ultranest                                                bayesian_analysis.py:197
[ultranest] Sampling 400 live points from prior ...
[ultranest] Explored until L=-3
[ultranest] Likelihood function evaluations: 13926
[ultranest]   logZ = -13.46 +- 0.1041
[ultranest] Effective samples strategy satisfied (ESS = 964.6, need >400)
[ultranest] Posterior uncertainty strategy is satisfied (KL: 0.46+-0.09 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.10 tail:0.40 total:0.42 required:<0.50
[ultranest] done iterating.
19:52: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 1.011 -0.020 +0.019 1 / (cm2 keV s)
demo.spectrum.main.Sin.f (1.0026 -0.0019 +0.0016) x 10^-1 rad / keV
Values of -log(posterior) at the minimum:

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

statistical measures
AIC 11.052666
BIC 12.338248
DIC 10.151683
PDIC 1.904531
log(Z) -5.847234
[10]:
../_images/notebooks_sampler_docs_16_12.png
../_images/notebooks_sampler_docs_16_13.png
../_images/notebooks_sampler_docs_16_14.png