-
Notifications
You must be signed in to change notification settings - Fork 28
/
run_pypolychord.py
77 lines (58 loc) · 2.05 KB
/
run_pypolychord.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
from numpy import pi, log
import pypolychord
from pypolychord.settings import PolyChordSettings
from pypolychord.priors import UniformPrior
try:
from mpi4py import MPI
except ImportError:
pass
#| Define a four-dimensional spherical gaussian likelihood,
#| width sigma=0.1, centered on the 0 with one derived parameter.
#| The derived parameter is the squared radius
nDims = 4
nDerived = 1
sigma = 0.1
def likelihood(theta):
""" Simple Gaussian Likelihood"""
nDims = len(theta)
r2 = sum(theta**2)
logL = -log(2*pi*sigma*sigma)*nDims/2.0
logL += -r2/2/sigma/sigma
return logL, [r2]
#| Define a box uniform prior from -1 to 1
def prior(hypercube):
""" Uniform prior from [-1,1]^D. """
return UniformPrior(-1, 1)(hypercube)
#| Optional dumper function giving run-time read access to
#| the live points, dead points, weights and evidences
def dumper(live, dead, logweights, logZ, logZerr):
print("Last dead point:", dead[-1])
#| Initialise the settings
settings = PolyChordSettings(nDims, nDerived)
settings.file_root = 'gaussian'
settings.nlive = 200
settings.do_clustering = True
settings.read_resume = False
#| Run PolyChord
output = pypolychord.run_polychord(likelihood, nDims, nDerived, settings, prior, dumper)
#| Create a paramnames file
paramnames = [('p%i' % i, r'\theta_%i' % i) for i in range(nDims)]
paramnames += [('r*', 'r')]
output.make_paramnames_files(paramnames)
#| Make an anesthetic plot (could also use getdist)
try:
import anesthetic as ac
samples = ac.read_chains(settings.base_dir + '/' + settings.file_root)
fig, axes = ac.make_2d_axes(['p0', 'p1', 'p2', 'p3', 'r'])
samples.plot_2d(axes)
fig.savefig('posterior.pdf')
except ImportError:
try:
import getdist.plots
posterior = output.posterior
g = getdist.plots.getSubplotPlotter()
g.triangle_plot(posterior, filled=True)
g.export('posterior.pdf')
except ImportError:
print("Install matplotlib and getdist for plotting examples")
print("Install anesthetic or getdist for plotting examples")