-
Notifications
You must be signed in to change notification settings - Fork 0
/
other_simple_likelihood.py
329 lines (283 loc) · 12.9 KB
/
other_simple_likelihood.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
from cobaya.likelihood import Likelihood
import numpy as np
import matplotlib.pyplot as plt
import pickle
class exactXX(Likelihood):
"""Class to define the template for an exact likelihood encoding one single field, here named X."""
def initialize(self):
"""Initialize the likelihood.
Prepare any computation, importing any necessary code, files, etc. Note
that this function is run only once at the very beginning of the routine. e.g.
here you load a cl_file containing the fiducial values of the power spectra
according to some fiducial cosmology you want to probe. Furthermore, you import
the CLs of the noise you are considering and you check for basic consistencies.
In this example, I precomputed the fiducial power spectra (coming as a dict),
but you may want to produce them on the fly using a CAMB inifile, or whatever
you want.
Returns
-------
None
"""
# Loading files
_cl_file = "path/to/cls.pkl"
_nl_file = "path/to/noise.pkl"
with open(_cl_file, "rb") as pickle_file:
self.fiduCLS = pickle.load(pickle_file)
with open(_nl_file, "rb") as pickle_file:
self.noiseCLS = pickle.load(pickle_file)
# Initialize useful quantities
self.debug = True
self.lmin = 2
self.lmax = 300
self.fsky = 0.5
# Probably at this point you may want to check what fields are contained in the fiducial
# dictionaries, the syntax of the keywords, or whether the lmin is 0, or 2. In case
# something is not consistent you may want to add some extra lines to make them so.
if self.debug:
print(f"Keys of fiducial CLs ---> {self.fiduCLS.keys()}")
print(f"Keys of noise CLs ---> {self.noiseCLS.keys()}")
# For a field contained in the fiducial (here XX):
_field = "xx"
print("\nPrinting the first few values to check that it starts from 0...")
print(f"Fiducial CLs for {_field.upper()} ---> {self.fiduCLS[_field][0:5]}")
print(f"Noise CLs for {_field.upper()} ---> {self.noiseCLS[_field][0:5]}")
# Now we pass the fiducial spectra to the rest of the class
self.data = (
self.fiduCLS["xx"][self.lmin : self.lmax + 1]
+ self.noiseCLS["xx"][self.lmin : self.lmax + 1]
)
def get_requirements(self):
"""Define requirements of the likelihood, specifying quantities calculated by a theory code are needed.
Returns
-------
dict: dict with requirements
return dictionary
"""
requirements = {}
requirements["Cl"] = {"xx": self.lmax}
if self.debug:
requirements[
"CAMBdata"
] = None # This allows to get the complete product of the CAMB run
return requirements
def logp(self):
"""Compute the likelihood for each step of the chain. Note that this function has to return log-likelihood.
Returns
-------
float: log-likelihood
"""
# You may want to check whether every parameter has been set as desided, thus you can print
# the parameters set in CAMB. This also allows you to do some extra computation with the CAMB
# results if needed.
if self.debug:
_CAMBdata = self.provider.get_CAMBdata()
_pars = _CAMBdata.Params
print(_pars)
# Retrieve CLs for the step
_cobaCLs = self.provider.get_Cl(ell_factor=True)
# Also here you may want to check what fields are contained in the fiducial
# dictionaries, the syntax of the keywords, or whether the lmin is 0, or 2. In case
# something is not consistent you may want to add some extra lines to make them so.
if self.debug:
print(f"Keys of Cobaya CLs ---> {_cobaCLs.keys()}")
# For a field contained in the fiducial (here YY):
_field = "xx"
print("\nPrinting the first few values to check that it starts from 0...")
print(f"Cobaya CLs for {_field.upper()} ---> {_cobaCLs[_field][0:5]}")
_coba = (
_cobaCLs["xx"][self.lmin : self.lmax + 1]
+ self.noiseCLS["xx"][self.lmin : self.lmax + 1]
)
# At this point, you may want to check whether everything is consistent in terms of
# normalizations, overall values, etc... Therefore here you can plot the considered field
# and you can compare the fiducial and the cobaya spectra (+ noise eventually)
if self.debug:
_ell = np.arange(0, self.lmax + 1, 1)
_field = "xx"
plt.loglog(
_ell[2 - self.lmin :],
self.fiduCLS[_field][2 - self.lmin :],
label="Fiducial CLs",
)
plt.loglog(
_ell[2 - self.lmin :],
_cobaCLs[_field][2 - self.lmin :],
label="Cobaya CLs",
)
plt.loglog(
_ell[2 - self.lmin :],
self.noiseCLS[_field][2 - self.lmin :],
label="Noise CLs",
)
plt.xlim(2, None)
plt.legend()
plt.show()
# Since this function is called for every step, you want to kill it if you produce
# this plot
exit()
# Now you want to compute the log-likelihood. This may be done in many different ways.
# Here you can compute the log-likelihood using an exact likelihood. Note that this
# example uses only one field. Thus for more complex likelihoods this may become more
# involved
_ell = np.arange(self.lmin, self.lmax + 1, 1)
M = self.data / _coba
logp_ℓ = -0.5 * (2 * _ell + 1) * self.fsky * (M - np.log(np.abs(M)) - 1)
return np.sum(logp_ℓ)
class exactYYYKKK(Likelihood):
"""Class to define the template for an exact likelihood encoding two fields, here named here Y and K."""
def initialize(self):
"""Initialize the likelihood.
Prepare any computation, importing any necessary code, files, etc. Note
that this function is run only once at the very beginning of the routine. e.g.
here you load a cl_file containing the fiducial values of the power spectra
according to some fiducial cosmology you want to probe. Furthermore, you import
the CLs of the noise you are considering and you check for basic consistencies.
In this example, I precomputed the fiducial power spectra (coming as a dict),
but you may want to produce them on the fly using a CAMB inifile, or whatever
you want.
Returns
-------
None
"""
# Loading files
_cl_file = "path/to/cls.pkl"
_nl_file = "path/to/noise.pkl"
with open(_cl_file, "rb") as pickle_file:
self.fiduCLS = pickle.load(pickle_file)
with open(_nl_file, "rb") as pickle_file:
self.noiseCLS = pickle.load(pickle_file)
# Initialize useful quantities
self.debug = True
self.lmin = 2
self.lmaxYY = 500
self.lmaxKK = 300
self.lmax = np.max(self.lmaxYY, self.lmaxKK)
self.fsky = 0.5
# Probably at this point you may want to check what fields are contained in the fiducial
# dictionaries, the syntax of the keywords, or whether the lmin is 0, or 2. In case
# something is not consistent you may want to add some extra lines to make them so.
if self.debug:
print(f"Keys of fiducial CLs ---> {self.fiduCLS.keys}")
print(f"Keys of noise CLs ---> {self.noiseCLS.keys}")
# For a field contained in the fiducial (here YY):
_field = "yy"
print("\nPrinting the first few values to check that it starts from 0...")
print(f"Fiducial CLs for {_field.upper} ---> {self.fiduCLS[_field][0:5]}")
print(f"Noise CLs for {_field.upper} ---> {self.noiseCLS[_field][0:5]}")
# Now we pass the fiducial spectra to the rest of the class
self.fiduCOV = np.array(
[
[self.fiduCLS["yy"], self.fiduCLS["yk"]],
[self.fiduCLS["yk"], self.fiduCLS["kk"]],
],
)
self.noiseCOV = np.array(
[
[self.noiseCLS["yy"], self.noiseCLS["yk"]],
[self.noiseCLS["yk"], self.noiseCLS["kk"]],
],
)
self.data = (
self.fiduCOV[:, :, self.lmin : self.lmax + 1]
+ self.noiseCOV[:, :, self.lmin : self.lmax + 1]
)
def get_requirements(self):
"""Define requirements of the likelihood, specifying quantities calculated by a theory code are needed.
Returns
-------
dict: dict with requirements
return dictionary
"""
requirements = {}
requirements["Cl"] = {"yy": self.lmax, "kk": self.lmax, "yk": self.lmax}
if self.debug:
requirements[
"CAMBdata"
] = None # This allows to get the complete product of the CAMB run
return requirements
def logp(self):
"""Compute the likelihood for each step of the chain. Note that this function has to return log-likelihood.
Returns
-------
float: log-likelihood
"""
# You may want to check whether every parameter has been set as desided, thus you can print
# the parameters set in CAMB. This also allows you to do some extra computation with the CAMB
# results if needed.
if self.debug:
_CAMBdata = self.provider.get_CAMBdata()
_pars = _CAMBdata.Params
print(_pars)
# Retrieve CLs for the step
self.cobaCLs = self.provider.get_Cl(ell_factor=True)
# Also here you may want to check what fields are contained in the fiducial
# dictionaries, the syntax of the keywords, or whether the lmin is 0, or 2. In case
# something is not consistent you may want to add some extra lines to make them so.
if self.debug:
print(f"Keys of Cobaya CLs ---> {self.cobaCLs.keys()}")
# For a field contained in the fiducial (here YY):
_field = "yy"
print("\nPrinting the first few values to check that it starts from 0...")
print(f"Cobaya CLs for {_field.upper()} ---> {self.cobaCLs[_field][0:5]}")
self.cobaCOV = np.array(
[
[self.cobaCLS["yy"], self.cobaCLS["yk"]],
[self.cobaCLS["yk"], self.cobaCLS["kk"]],
],
)
self.coba = (
self.cobaCOV[:, :, self.lmin : self.lmax + 1]
+ self.noiseCOV[:, :, self.lmin : self.lmax + 1]
)
# At this point, you may want to check whether everything is consistent in terms of
# normalizations, overall values, etc... Therefore here you can plot the considered field
# and you can compare the fiducial and the cobaya spectra (+ noise eventually)
if self.debug:
_ell = np.arange(0, self.lmax + 1, 1)
_field = "yy"
plt.loglog(
_ell[2 - self.lmin :],
self.fiduCLS[_field][2 - self.lmin :],
label="Fiducial CLs",
)
plt.loglog(
_ell[2 - self.lmin :],
self.cobaCLs[_field][2 - self.lmin :],
label="Cobaya CLs",
)
plt.loglog(
_ell[2 - self.lmin :],
self.noiseCLS[_field][2 - self.lmin :],
label="Noise CLs",
)
plt.legend()
plt.show()
# Since this function is called for every step, you want to kill it if you produce
# this plot
exit()
# Now you want to compute the log-likelihood. This may be done in many different ways.
# Here you can compute the log-likelihood using an exact likelihood. Note that this
# example uses only one field. Thus for more complex likelihoods this may become more
# involved
_ell = np.arange(self.lmin, self.lmax + 1, 1)
logp_ℓ = np.zeros(_ell.shape)
for i in range(0, self.lmax + 1 - self.lmin):
if i <= self.lmaxKK:
M = self.data[:, :, i] @ np.linalg.inv(self.coba[:, :, i])
_norm = len(self.data[0, :, i])
logp_ℓ[i] = (
-0.5
* (2 * _ell[i] + 1)
* self.fsky
* (np.trace(M) - np.linalg.slogdet(M)[1] - _norm)
)
else:
M = self.data[0, 0, i] / self.coba[0, 0, i]
_norm = 1
logp_ℓ[i] = (
-0.5
* (2 * _ell[i] + 1)
* self.fsky
* (M - np.log(np.abs(M)) - _norm)
)
return np.sum(logp_ℓ)