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()
05:15:25 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.                                                                           
         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))
05:15:27 INFO      Using Gaussian statistic (equivalent to chi^2) with the provided errors.            XYLike.py:93
05:15:28 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
05:15:31 INFO      Mean acceptance fraction: 0.7034999999999999                                emcee_sampler.py:157
         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.017 +0.015 1 / (cm2 keV s)
demo.spectrum.main.Sin.f (10.00 -0.035 +0.04) x 10^-2 rad / keV
Values of -log(posterior) at the minimum:

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

statistical measures
AIC 18.368852
BIC 19.654435
DIC 17.847605
PDIC 2.088062
[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()
05:15:32 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)=  -16.574413947909981      +/-  0.14780047452922601
 Total Likelihood Evaluations:         5895
 Sampling finished. Exiting MultiNest

05:15:33 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.017 +0.015 1 / (cm2 keV s)
demo.spectrum.main.Sin.f (10.00 +/- 0.04) x 10^-2 rad / keV
Values of -log(posterior) at the minimum:

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

statistical measures
AIC 18.373010
BIC 19.658592
DIC 17.793983
PDIC 2.064988
log(Z) -7.198177
         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
4229it [00:04, 960.52it/s, +400 | bound: 9 | nc: 1 | ncall: 19355 | eff(%): 24.421 | loglstar:   -inf < -6.822 <    inf | logz: -16.342 +/-  0.146 | dlogz:  0.001 >  0.409]
05:15: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.010 -0.015 +0.014 1 / (cm2 keV s)
demo.spectrum.main.Sin.f (10.00 +/- 0.04) x 10^-2 rad / keV
Values of -log(posterior) at the minimum:

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

statistical measures
AIC 18.370865
BIC 19.656447
DIC 17.627936
PDIC 1.981979
log(Z) -7.097053
[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()
05:15:39 INFO      sampler set to dynesty_dynamic                                          bayesian_analysis.py:202
7347it [00:07, 1434.18it/s, batch: 0 | bound: 13 | nc: 1 | ncall: 27301 | eff(%): 26.559 | loglstar:   -inf < -6.829 <    inf | logz: -16.621 +/-  0.133 | dlogz:  0.007 >  0.010]
WARNING DeprecationWarning: This an old stopping function that will be removed in future releases

8614it [00:08, 1539.79it/s, batch: 1 | bound: 3 | nc: 1 | ncall: 28992 | eff(%): 29.490 | loglstar: -8.545 < -6.993 < -7.275 | logz: -16.614 +/-  0.137 | stop:  1.391]
WARNING DeprecationWarning: This an old stopping function that will be removed in future releases

9299it [00:09, 1074.66it/s, batch: 2 | bound: 2 | nc: 1 | ncall: 29737 | eff(%): 31.109 | loglstar: -9.042 < -7.252 < -8.543 | logz: -16.602 +/-  0.112 | stop:  1.054]
WARNING DeprecationWarning: This an old stopping function that will be removed in future releases

9551it [00:10, 631.33it/s, batch: 3 | bound: 2 | nc: 1 | ncall: 30022 | eff(%): 31.322 | loglstar: -9.435 < -8.804 < -9.035 | logz: -16.601 +/-  0.104 | stop:  1.069]
WARNING DeprecationWarning: This an old stopping function that will be removed in future releases

10006it [00:11, 902.01it/s, batch: 3 | bound: 2 | nc: 1 | ncall: 30493 | eff(%): 32.814 | loglstar: -9.435 < -6.823 < -9.035 | logz: -16.601 +/-  0.104 | stop:  0.808]
05:15:50 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.014 1 / (cm2 keV s)
demo.spectrum.main.Sin.f (10.00 +/- 0.04) x 10^-2 rad / keV
Values of -log(posterior) at the minimum:

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

statistical measures
AIC 18.368745
BIC 19.654327
DIC 17.453666
PDIC 1.895196
log(Z) -7.207368
[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()
05:15:51 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:08<00:00, 73.48it/s]
05:16:00 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.405118
Mean Integrated Autocorrelation Time: 2.9
Effective Sample Size: 4313.65
Number of Log Probability Evaluations: 64983
Effective Samples per Log Probability Evaluation: 0.066381
None
Maximum a posteriori probability (MAP) point:

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

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

statistical measures
AIC 18.368914
BIC 19.654496
DIC 17.711939
PDIC 2.023822
[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()
05:16:01 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: 7647
[ultranest]   logZ = -16.71 +- 0.107
[ultranest] Effective samples strategy satisfied (ESS = 984.9, need >400)
[ultranest] Posterior uncertainty strategy is satisfied (KL: 0.46+-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.11 tail:0.41 total:0.42 required:<0.50
[ultranest] done iterating.
05:16:08 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.009 -0.014 +0.015 1 / (cm2 keV s)
demo.spectrum.main.Sin.f (10.00 +/- 0.04) x 10^-2 rad / keV
Values of -log(posterior) at the minimum:

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

statistical measures
AIC 18.383735
BIC 19.669317
DIC 17.704202
PDIC 2.019729
log(Z) -7.258329
[10]:
../_images/notebooks_sampler_docs_16_12.png
../_images/notebooks_sampler_docs_16_13.png
../_images/notebooks_sampler_docs_16_14.png