Skip to content

Commit ac429c9

Browse files
committed
planck:clipy: finished rework
1 parent 3467791 commit ac429c9

File tree

2 files changed

+48
-61
lines changed

2 files changed

+48
-61
lines changed

cobaya/likelihoods/base_classes/planck_clik.py

Lines changed: 44 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
from cobaya.install import download_file, download_github_release, pip_install
1818
from cobaya.likelihood import Likelihood
1919
from cobaya.log import LoggedError, get_logger
20-
from cobaya.tools import VersionCheckError, are_different_params_lists, create_banner
20+
from cobaya.tools import VersionCheckError, are_different_params_lists
2121

2222
pla_url_prefix = r"https://pla.esac.esa.int/pla-sl/data-action?COSMOLOGY.COSMOLOGY_OID="
2323

@@ -42,7 +42,7 @@ def initialize(self):
4242
self.packages_path
4343
)
4444
# Load clipy instead of clik
45-
clik = load_clipy(
45+
clipy = load_clipy(
4646
path=self.path,
4747
install_path=install_path,
4848
logger=self.log,
@@ -58,6 +58,8 @@ def initialize(self):
5858
self.log,
5959
f"{excpt}. To install a new version, {msg_to_install} with `--upgrade`.",
6060
) from excpt
61+
# Disable JAX to avoid dependency issues
62+
os.environ["CLIPY_NOJAX"] = "1"
6163
# Loading the likelihood data
6264
data_path = get_data_path(self.__class__.get_qualified_class_name())
6365
if not os.path.isabs(self.clik_file):
@@ -67,51 +69,46 @@ def initialize(self):
6769
os.path.join(self.path or self.packages_path, "data", data_path),
6870
)
6971
self.clik_file = os.path.join(self.path_data, self.clik_file)
70-
# clipy handles both lensing and non-lensing likelihoods with single constructor
7172
try:
72-
# Disable JAX to avoid dependency issues
73-
os.environ["CLIPY_NOJAX"] = "1"
74-
self.clik = clik.clik(self.clik_file)
75-
except Exception as excpt:
73+
self.commands = None
74+
75+
self.clik_likelihood = clipy.clik(self.clik_file, **(self.commands or {}))
76+
except clipy.clik_emul_error as excpt:
7677
# Is it that the file was not found?
7778
if not os.path.exists(self.clik_file):
7879
raise ComponentNotInstalledError(
7980
self.log,
80-
"The .clik file was not found where specified in the "
81-
"'clik_file' field of the settings of this likelihood. "
82-
"Maybe the 'path' given is not correct? The full path where"
83-
" the .clik file was searched for is '%s'",
84-
self.clik_file,
81+
"The .clik file was not found where specified in the 'clik_file' "
82+
"field of the settings of this likelihood. Install this likelihood "
83+
f"with 'cobaya-install {self.get_qualified_class_name()}'. If this "
84+
"error persists, maybe the 'path' given is not correct? The full path"
85+
" where the .clik file was searched for is '{self.clik_file}'",
8586
) from excpt
8687
# Else: unknown clipy error
87-
self.log.error(
88-
"An unexpected error occurred in clipy (possibly related to "
89-
"multiple simultaneous initialization, or simultaneous "
90-
"initialization of incompatible likelihoods; e.g. polarised "
91-
"vs non-polarised 'lite' likelihoods. See error info below:"
92-
)
93-
raise
94-
self.l_maxs = self.clik.get_lmax()
95-
# calculate requirements here so class can also be separately instantiated
96-
requested_cls = ["tt", "ee", "bb", "te", "tb", "eb"]
97-
# clipy automatically handles lensing detection, but we need to check the lmax values
98-
has_cl = [lmax != -1 for lmax in self.l_maxs]
99-
# Check if this is a lensing likelihood by examining the structure
100-
if len(self.l_maxs) > 6 and self.l_maxs[0] != -1:
101-
# First element is pp for lensing likelihoods
102-
self.lensing = True
103-
requested_cls = ["pp"] + requested_cls
104-
else:
105-
self.lensing = False
106-
# For non-lensing, use get_has_cl if available
107-
if hasattr(self.clik, "get_has_cl"):
108-
has_cl = self.clik.get_has_cl()
109-
self.requested_cls = [cl for cl, i in zip(requested_cls, has_cl) if int(i)]
110-
self.l_maxs_cls = [lmax for lmax, i in zip(self.l_maxs, has_cl) if int(i)]
111-
self.expected_params = list(self.clik.extra_parameter_names)
88+
raise LoggedError(
89+
self.log,
90+
f"An unexpected error occurred in clipy: {excpt}",
91+
) from excpt
92+
except Exception as excpt: # unknown clippy error
93+
raise LoggedError(
94+
self.log,
95+
f"An unmanaged error occurred in clipy: {excpt}. Please report it as a "
96+
"GitHub issue in the Cobaya repo.",
97+
) from excpt
98+
lmaxs = self.clik_likelihood.lmax
99+
cls_sorted = ["tt", "ee", "bb", "te", "tb", "eb"]
100+
if len(lmaxs) > 6: # lensing likelihood!
101+
cls_sorted = ["pp"] + cls_sorted
102+
self.requested_cls_lmax = {
103+
cl: lmax for cl, lmax in zip(cls_sorted, lmaxs) if lmax != -1
104+
}
105+
self.expected_params = list(self.clik_likelihood.extra_parameter_names)
112106
# Placeholder for vector passed to clipy
113-
length = len(self.l_maxs) if self.lensing else len(has_cl)
114-
self.vector = np.zeros(np.sum(self.l_maxs) + length + len(self.expected_params))
107+
self.vector = np.zeros(
108+
sum(list(self.requested_cls_lmax.values()))
109+
+ len(self.requested_cls_lmax) # account for ell=0
110+
+ len(self.expected_params)
111+
)
115112

116113
def initialize_with_params(self):
117114
# Check that the parameters are the right ones
@@ -129,45 +126,35 @@ def initialize_with_params(self):
129126

130127
def get_requirements(self):
131128
# State requisites to the theory code
132-
return {"Cl": dict(zip(self.requested_cls, self.l_maxs_cls))}
129+
return {"Cl": self.requested_cls_lmax}
133130

134131
def logp(self, **params_values):
135-
# get Cl's from the theory code
132+
# Get Cl's from the theory code
136133
cl = self.provider.get_Cl(units="FIRASmuK2")
137134
return self.log_likelihood(cl, **params_values)
138135

139136
def log_likelihood(self, cl, **params_values):
140-
# fill with Cl's
137+
# Fill with Cl's
141138
self.vector[: -len(self.expected_params)] = np.concatenate(
142139
[
143-
(
144-
cl[spectrum][: 1 + lmax]
145-
if spectrum not in ["tb", "eb"]
146-
else np.zeros(1 + lmax)
147-
)
148-
for spectrum, lmax in zip(self.requested_cls, self.l_maxs_cls)
140+
cl[spec][: 1 + lmax] if spec not in ["tb", "eb"] else np.zeros(1 + lmax)
141+
for spec, lmax in self.requested_cls_lmax.items()
149142
]
150143
)
151144
# check for nan's: may produce issues in clipy
152145
# dot product is apparently the fastest way in threading-enabled numpy
153146
if np.isnan(np.dot(self.vector, self.vector)):
154147
return -np.inf
155-
# fill with likelihood parameters
148+
# Fill with likelihood parameters
156149
self.vector[-len(self.expected_params) :] = [
157150
params_values[p] for p in self.expected_params
158151
]
159-
# clipy returns a scalar, not an array like clik
160-
loglike = self.clik(self.vector)
161-
# Convert to Python float
162-
loglike = float(loglike)
152+
loglike = self.clik_likelihood(self.vector)
163153
# "zero" of clipy, and sometimes nan's returned
164-
if np.allclose(loglike, -1e30) or np.isnan(loglike):
154+
if loglike <= -1e30 or np.isnan(loglike):
165155
loglike = -np.inf
166156
return loglike
167157

168-
def close(self):
169-
del self.clik # Clean up clipy object
170-
171158
@classmethod
172159
def get_code_path(cls, path):
173160
return os.path.realpath(os.path.join(path, "code", common_path))

tests/test_cosmo_planck_2018.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@
4141
def test_planck_2018_t_camb(packages_path, skip_not_installed, clik=False):
4242
best_fit = deepcopy(params_lowl_highTT_lensing)
4343
best_fit.pop("H0")
44-
info_likelihood = lik_info_lowl_highTT_lensing
44+
info_likelihood = lik_info_lowl_highTT_lensing.copy()
4545
chi2 = chi2_lowl_highTT_lensing.copy()
4646
if clik:
4747
info_likelihood["planck_2018_lowl.TT_clik"] = info_likelihood.pop(
@@ -320,7 +320,7 @@ def test_planck_2018_p_CamSpec2021_camb(packages_path, skip_not_installed):
320320

321321
def test_planck_2018_lcmbmarged_camb(packages_path, skip_not_installed):
322322
best_fit = params_lensing_cmbmarged
323-
info_likelihood = lik_info_lensing_cmbmarged
323+
info_likelihood = lik_info_lensing_cmbmarged.copy()
324324
info_theory = {"camb": {"extra_args": planck_precision["camb"]}}
325325
best_fit_derived = {}
326326
body_of_test(
@@ -341,7 +341,7 @@ def test_planck_2018_t_classy(packages_path, skip_not_installed):
341341
best_fit = deepcopy(params_lowl_highTT_lensing)
342342
best_fit.pop("theta_MC_100")
343343
best_fit = params_lowl_highTT_lensing
344-
info_likelihood = lik_info_lowl_highTT_lensing
344+
info_likelihood = lik_info_lowl_highTT_lensing.copy()
345345
info_theory = {"classy": {"extra_args": planck_precision["classy"]}}
346346
best_fit_derived = deepcopy(derived_lowl_highTT_lensing)
347347
for p in classy_unknown:
@@ -362,7 +362,7 @@ def test_planck_2018_t_classy(packages_path, skip_not_installed):
362362
def test_planck_2018_p_classy(packages_path, skip_not_installed):
363363
best_fit = deepcopy(params_lowTE_highTTTEEE_lensingcmblikes)
364364
best_fit.pop("theta_MC_100")
365-
info_likelihood = lik_info_lowTE_highTTTEEE_lensingcmblikes
365+
info_likelihood = lik_info_lowTE_highTTTEEE_lensingcmblikes.copy()
366366
info_theory = {"classy": {"extra_args": planck_precision["classy"]}}
367367
best_fit_derived = deepcopy(derived_lowTE_highTTTEEE_lensingcmblikes)
368368
for p in classy_unknown:

0 commit comments

Comments
 (0)