emantis 1.2.0__tar.gz → 1.2.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. {emantis-1.2.0 → emantis-1.2.1}/PKG-INFO +3 -3
  2. {emantis-1.2.0 → emantis-1.2.1}/README.rst +1 -1
  3. {emantis-1.2.0 → emantis-1.2.1}/pyproject.toml +3 -2
  4. {emantis-1.2.0 → emantis-1.2.1}/src/emantis/__init__.py +2 -1
  5. {emantis-1.2.0 → emantis-1.2.1}/src/emantis/_cli.py +0 -1
  6. {emantis-1.2.0 → emantis-1.2.1}/src/emantis/_gp_emulation.py +35 -29
  7. {emantis-1.2.0 → emantis-1.2.1}/src/emantis/_read_data.py +0 -8
  8. {emantis-1.2.0 → emantis-1.2.1}/src/emantis/_transformers.py +12 -13
  9. {emantis-1.2.0 → emantis-1.2.1}/src/emantis/_utils_inputs.py +0 -2
  10. {emantis-1.2.0 → emantis-1.2.1}/src/emantis/halo_mass_function.py +1 -3
  11. {emantis-1.2.0 → emantis-1.2.1}/src/emantis/matter_power_spectrum.py +24 -5
  12. {emantis-1.2.0 → emantis-1.2.1}/src/emantis/powerspectrum_matter.py +0 -3
  13. {emantis-1.2.0 → emantis-1.2.1}/tests/test_halo_mass_function.py +0 -6
  14. {emantis-1.2.0 → emantis-1.2.1}/tests/test_matter_power_spectrum.py +42 -54
  15. {emantis-1.2.0 → emantis-1.2.1}/COPYING +0 -0
  16. {emantis-1.2.0 → emantis-1.2.1}/src/emantis/_types.py +0 -0
  17. {emantis-1.2.0 → emantis-1.2.1}/src/emantis/_utils.py +0 -0
  18. {emantis-1.2.0 → emantis-1.2.1}/src/emantis/data/cosmo_params_fR_emu_v1.txt +0 -0
  19. {emantis-1.2.0 → emantis-1.2.1}/src/emantis/data/cosmo_params_fR_emu_v1_config.toml +0 -0
  20. {emantis-1.2.0 → emantis-1.2.1}/src/emantis/data/cosmo_params_fR_emu_v2.txt +0 -0
  21. {emantis-1.2.0 → emantis-1.2.1}/src/emantis/data/cosmo_params_fR_emu_v2_config.toml +0 -0
  22. {emantis-1.2.0 → emantis-1.2.1}/src/emantis/data/cosmo_params_wCDM_emu_v2.txt +0 -0
  23. {emantis-1.2.0 → emantis-1.2.1}/src/emantis/data/cosmo_params_wCDM_emu_v2_config.toml +0 -0
  24. {emantis-1.2.0 → emantis-1.2.1}/src/emantis/data/fofr_matter_power_boost/cosmo_params.txt +0 -0
  25. {emantis-1.2.0 → emantis-1.2.1}/src/emantis/data/fofr_matter_power_boost/kbins.h5 +0 -0
  26. {emantis-1.2.0 → emantis-1.2.1}/src/emantis/data/fofr_matter_power_boost/power_boosts_train.h5 +0 -0
  27. {emantis-1.2.0 → emantis-1.2.1}/src/emantis/data/halo_mass_function/halo_mass_function_fR_emu_v2_data.h5 +0 -0
  28. {emantis-1.2.0 → emantis-1.2.1}/src/emantis/data/halo_mass_function/halo_mass_function_fR_emu_v2_emulation_config.toml +0 -0
  29. {emantis-1.2.0 → emantis-1.2.1}/src/emantis/data/halo_mass_function/halo_mass_function_wCDM_emu_v2_data.h5 +0 -0
  30. {emantis-1.2.0 → emantis-1.2.1}/src/emantis/data/halo_mass_function/halo_mass_function_wCDM_emu_v2_emulation_config.toml +0 -0
  31. {emantis-1.2.0 → emantis-1.2.1}/src/emantis/data/matter_power_spectrum_nl_boost/matter_power_spectrum_nl_boost_wCDM_emu_v2_data.h5 +0 -0
  32. {emantis-1.2.0 → emantis-1.2.1}/src/emantis/data/matter_power_spectrum_nl_boost/matter_power_spectrum_nl_boost_wCDM_emu_v2_emulation_config.toml +0 -0
  33. {emantis-1.2.0 → emantis-1.2.1}/src/emantis/data/matter_power_spectrum_nl_mg_boost/matter_power_spectrum_nl_mg_boost_fR_emu_v1_data.h5 +0 -0
  34. {emantis-1.2.0 → emantis-1.2.1}/src/emantis/data/matter_power_spectrum_nl_mg_boost/matter_power_spectrum_nl_mg_boost_fR_emu_v1_emulation_config.toml +0 -0
  35. {emantis-1.2.0 → emantis-1.2.1}/src/emantis/data/matter_power_spectrum_nl_mg_boost/matter_power_spectrum_nl_mg_boost_fR_emu_v2_data.h5 +0 -0
  36. {emantis-1.2.0 → emantis-1.2.1}/src/emantis/data/matter_power_spectrum_nl_mg_boost/matter_power_spectrum_nl_mg_boost_fR_emu_v2_emulation_config.toml +0 -0
  37. {emantis-1.2.0 → emantis-1.2.1}/src/emantis/data/sigma8/cosmo_params_LCDM.txt +0 -0
  38. {emantis-1.2.0 → emantis-1.2.1}/src/emantis/data/sigma8/cosmo_params_LCDM_config.toml +0 -0
  39. {emantis-1.2.0 → emantis-1.2.1}/src/emantis/data/sigma8/cosmo_params_wCDM.txt +0 -0
  40. {emantis-1.2.0 → emantis-1.2.1}/src/emantis/data/sigma8/cosmo_params_wCDM_config.toml +0 -0
  41. {emantis-1.2.0 → emantis-1.2.1}/src/emantis/data/sigma8/sigma8_LCDM_data.txt +0 -0
  42. {emantis-1.2.0 → emantis-1.2.1}/src/emantis/data/sigma8/sigma8_LCDM_emulation_config.toml +0 -0
  43. {emantis-1.2.0 → emantis-1.2.1}/src/emantis/data/sigma8/sigma8_wCDM_data.txt +0 -0
  44. {emantis-1.2.0 → emantis-1.2.1}/src/emantis/data/sigma8/sigma8_wCDM_emulation_config.toml +0 -0
  45. {emantis-1.2.0 → emantis-1.2.1}/src/emantis/exceptions.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: emantis
3
- Version: 1.2.0
3
+ Version: 1.2.1
4
4
  Summary: A cosmological emulator for non-linear large-scale structure formation studies in alternative dark energy and gravity theories.
5
5
  Keywords: cosmology,emulator,large-scale structure,dark energy,modified gravity
6
6
  Author-Email: =?utf-8?q?I=C3=B1igo_S=C3=A1ez_Casares?= <inigo.saez-casares@obspm.fr>
@@ -12,7 +12,7 @@ Classifier: Intended Audience :: Science/Research
12
12
  Classifier: Topic :: Scientific/Engineering :: Physics
13
13
  Project-URL: repository, https://gitlab.obspm.fr/e-mantis/e-mantis.git
14
14
  Project-URL: documentation, https://e-mantis.pages.obspm.fr/e-mantis/index.html
15
- Requires-Python: <4.0,>=3.10
15
+ Requires-Python: <3.14,>=3.10
16
16
  Requires-Dist: h5py<4.0,>=3.8
17
17
  Requires-Dist: scikit-learn<2,>=1
18
18
  Requires-Dist: numpy<3.0,>=1.24
@@ -94,7 +94,7 @@ You can also retrain them manually using the CLI utility.
94
94
  Documentation and usage
95
95
  -----------------------
96
96
 
97
- The up-to-date documentation for this project (with code examples and a detailed API) is available `here <https://e-mantis.pages.obspm.fr/e-mantis/index.html>`_.
97
+ The up-to-date documentation for this project (with code examples and a detailed API) is available `here <https://e-mantis.pages.obspm.fr/e-mantis>`_.
98
98
 
99
99
  Licence
100
100
  -------
@@ -71,7 +71,7 @@ You can also retrain them manually using the CLI utility.
71
71
  Documentation and usage
72
72
  -----------------------
73
73
 
74
- The up-to-date documentation for this project (with code examples and a detailed API) is available `here <https://e-mantis.pages.obspm.fr/e-mantis/index.html>`_.
74
+ The up-to-date documentation for this project (with code examples and a detailed API) is available `here <https://e-mantis.pages.obspm.fr/e-mantis>`_.
75
75
 
76
76
  Licence
77
77
  -------
@@ -2,7 +2,7 @@
2
2
  authors = [
3
3
  { name = "Iñigo Sáez Casares", email = "inigo.saez-casares@obspm.fr" },
4
4
  ]
5
- requires-python = "<4.0,>=3.10"
5
+ requires-python = "<3.14,>=3.10"
6
6
  dependencies = [
7
7
  "h5py <4.0,>=3.8",
8
8
  "scikit-learn <2,>=1",
@@ -12,7 +12,7 @@ dependencies = [
12
12
  "joblib <2.0.0,>=1.3.2",
13
13
  ]
14
14
  name = "emantis"
15
- version = "1.2.0"
15
+ version = "1.2.1"
16
16
  description = "A cosmological emulator for non-linear large-scale structure formation studies in alternative dark energy and gravity theories."
17
17
  readme = "README.rst"
18
18
  classifiers = [
@@ -72,6 +72,7 @@ dev = [
72
72
  "pytest>=8.4.1",
73
73
  "pytest-cov>=6",
74
74
  "pytest-pydocstyle>=2.4.0",
75
+ "pre-commit>=4.5.0",
75
76
  ]
76
77
  docs = [
77
78
  "sphinx",
@@ -1,6 +1,7 @@
1
1
  import logging
2
+ from .powerspectrum_matter import FofrBoost
2
3
 
3
4
  # Capture warnings by the logging system.
4
5
  logging.captureWarnings(True)
5
6
 
6
- from .powerspectrum_matter import FofrBoost
7
+ __all__ = ["FofrBoost", "matter_power_spectrum", "halo_mass_function"]
@@ -47,7 +47,6 @@ n_jobs = min(joblib.cpu_count(), n_jobs_max)
47
47
  # - type of emulators to train
48
48
  # Use typer package, see: https://packaging.python.org/en/latest/guides/creating-command-line-tools/
49
49
  def train_all_emulators():
50
-
51
50
  print(f"Will train all emulators using {n_jobs} processes.\n")
52
51
 
53
52
  print("----- Train matter_power_spectrum emulators -----\n")
@@ -237,7 +237,6 @@ class BaseEmulator:
237
237
 
238
238
  # Check each parameter range if necessary.
239
239
  if self.params_range is not None:
240
-
241
240
  # Loop over all parameters.
242
241
  for i, param_name in enumerate(self.params_range):
243
242
  _utils_inputs.check_emulation_range(
@@ -325,7 +324,6 @@ class BaseEmulator:
325
324
 
326
325
  # Loop over input parameters.
327
326
  for param_name in input_params_dict:
328
-
329
327
  _utils_inputs.check_emulation_range(
330
328
  input_params_dict[param_name],
331
329
  self.params_range[param_name]["min_value"],
@@ -413,17 +411,18 @@ class GaussianProcessEmulator1D(BaseEmulator):
413
411
 
414
412
  self._params = params
415
413
 
416
- # For "binned" data, apply a transformation if requested.
417
- # TODO: needs some care. 1/ accessing real raw data is useful. 2/ propagation to data_std.
414
+ # TODO: solve this compatibility problem.
418
415
  if self._config_emu.data.data_type == "binned":
419
- self._data = _utils.simple_transform(
420
- data, self._config_emu.data.binned.y_transform
421
- )
422
- # Leave other type of data as is.
423
- else:
424
- self._data = data
416
+ if self._config_emu.data.binned.y_transform == "log10":
417
+ if data_std is not None:
418
+ raise ValueError(
419
+ "Input log10 transformation (`y_transform`) is not compatible with input data_std."
420
+ )
421
+
422
+ self._data = data
425
423
 
426
424
  self._data_bins = data_bins
425
+
427
426
  if self._config_emu.data.data_type == "bspline" and self._data_bins is None:
428
427
  raise ValueError(
429
428
  "For data of type `bspline` you must provide a value for `data_bins`."
@@ -753,6 +752,7 @@ class GaussianProcessEmulator1D(BaseEmulator):
753
752
  self,
754
753
  n_splits: int = 5,
755
754
  shuffle: bool = True,
755
+ target_std: npt.NDArray | None = None,
756
756
  n_jobs: int | None = None,
757
757
  **kwargs_joblib,
758
758
  ) -> list[float]:
@@ -799,10 +799,7 @@ class GaussianProcessEmulator1D(BaseEmulator):
799
799
 
800
800
  # Compute validation scores for each fold.
801
801
  scores = Parallel(n_jobs=n_jobs, **kwargs_joblib)(
802
- delayed(self.validation_score)(
803
- models[0],
804
- models[1],
805
- )
802
+ delayed(self.validation_score)(models[0], models[1], target_std)
806
803
  for models in kfold_iterator
807
804
  )
808
805
 
@@ -941,6 +938,7 @@ class GaussianProcessEmulator1D(BaseEmulator):
941
938
  self,
942
939
  train_models: npt.NDArray,
943
940
  val_models: npt.NDArray,
941
+ target_std: npt.NDArray | None = None,
944
942
  ) -> float:
945
943
  """Compute a mean squared error validation score.
946
944
 
@@ -978,10 +976,19 @@ class GaussianProcessEmulator1D(BaseEmulator):
978
976
  data_train = self._data[train_models]
979
977
  scaler = preprocessing.StandardScaler().fit(data_train)
980
978
 
979
+ data_val = scaler.transform(data_val)
980
+ pred_val = scaler.transform(pred_val)
981
+
982
+ if target_std is not None:
983
+ target_std /= scaler.scale_
984
+
985
+ data_val /= target_std
986
+ pred_val /= target_std
987
+
981
988
  # Compute mean squared error score.
982
989
  score = mean_squared_error(
983
- scaler.transform(data_val),
984
- scaler.transform(pred_val),
990
+ data_val,
991
+ pred_val,
985
992
  multioutput="uniform_average",
986
993
  )
987
994
 
@@ -1069,7 +1076,6 @@ class GaussianProcessEmulator1D(BaseEmulator):
1069
1076
  bins = self._data_bins
1070
1077
 
1071
1078
  elif self._config_emu.data.data_type == "bspline":
1072
-
1073
1079
  assert self._data_bins is not None
1074
1080
 
1075
1081
  bins = _utils.inverse_simple_transform(
@@ -1089,7 +1095,6 @@ class GaussianProcessEmulator1D(BaseEmulator):
1089
1095
  data: npt.NDArray,
1090
1096
  data_std: npt.NDArray | None = None,
1091
1097
  ) -> GaussianProcessRegressor:
1092
-
1093
1098
  if self._ignore_training_warnings:
1094
1099
  # Ignore warnings during training.
1095
1100
  warnings.simplefilter("ignore")
@@ -1127,22 +1132,30 @@ class GaussianProcessEmulator1D(BaseEmulator):
1127
1132
  data_std: npt.NDArray | None = None,
1128
1133
  n_jobs: int | None = None,
1129
1134
  ) -> None:
1130
-
1131
1135
  # Fit parameter scaler.
1132
1136
  self._params_scaler.fit(params)
1133
1137
 
1134
1138
  # Scale parameters.
1135
1139
  params_scaled = self._params_scaler.transform(params)
1136
1140
 
1141
+ # For "binned" data, apply a transformation if requested.
1142
+ if self._config_emu.data.data_type == "binned":
1143
+ data = _utils.simple_transform(
1144
+ data, self._config_emu.data.binned.y_transform
1145
+ )
1146
+
1137
1147
  # Fit PCA and transform data.
1138
1148
  if self._config_emu.pca.do_pca:
1139
1149
  # Fit PCA.
1140
1150
  self._pca_transformer.fit(data)
1141
1151
 
1142
- # Transform data and data_std if required.
1143
- # WARNING: data_std must be done BEFORE.
1152
+ # Transform data_std if required.
1153
+ # WARNING: data_std must be done BEFORE data.
1144
1154
  if data_std is not None:
1145
1155
  data_std = self._pca_transformer.propagate_std(data, data_std)
1156
+
1157
+ # Transform data.
1158
+ # WARNING: data_std must be done BEFORE data.
1146
1159
  data = self._pca_transformer.transform(data)
1147
1160
 
1148
1161
  # Init. and fit GPR.
@@ -1201,7 +1214,7 @@ class GaussianProcessEmulator1D(BaseEmulator):
1201
1214
  self.train(n_jobs=n_jobs)
1202
1215
 
1203
1216
  # If the emulator is present but something went wrong in retrieving it.
1204
- except:
1217
+ except Exception:
1205
1218
  with as_file(RESOURCES / "data/emulator_storage") as myfile:
1206
1219
  # TODO: this conversion with as_posix() is required only for python < 3.11.
1207
1220
  # Remove it if support for python 3.10 is dropped.
@@ -1357,7 +1370,6 @@ class GaussianProcessEmulator1D(BaseEmulator):
1357
1370
  """
1358
1371
  # Inverse PCA.
1359
1372
  if self._config_emu.pca.do_pca:
1360
-
1361
1373
  # Get array shape (..., M).
1362
1374
  pred_gp_shape = list(pred_gp.shape)
1363
1375
 
@@ -1375,7 +1387,6 @@ class GaussianProcessEmulator1D(BaseEmulator):
1375
1387
 
1376
1388
  # Deal with binned emulation data.
1377
1389
  if self._config_emu.data.data_type == "binned":
1378
-
1379
1390
  # Return at the default emulator bins.
1380
1391
  if x is None:
1381
1392
  # Inverse transform predictions.
@@ -1421,7 +1432,6 @@ class GaussianProcessEmulator1D(BaseEmulator):
1421
1432
 
1422
1433
  # Get final prediction from emulated BSpline coefficients.
1423
1434
  elif self._config_emu.data.data_type == "bspline":
1424
-
1425
1435
  if x is None:
1426
1436
  raise ValueError(
1427
1437
  "For data type `bspline` you must provide bin values `x`."
@@ -1459,7 +1469,6 @@ class GaussianProcessEmulator1D(BaseEmulator):
1459
1469
  return_std=False,
1460
1470
  return_gp=False,
1461
1471
  ):
1462
-
1463
1472
  if excluded_models is None:
1464
1473
  excluded_models = []
1465
1474
 
@@ -1691,7 +1700,6 @@ class GaussianProcessEmulator1Dx1D(BaseEmulator):
1691
1700
  """
1692
1701
  # If the variable is the data bin.
1693
1702
  if parameter == self._config_emu.config_gpe_1D.data.variable_name:
1694
-
1695
1703
  # If the range is not node dependent, return the range of the first node.
1696
1704
  if self._config_emu.config_node.constant_data1D_range:
1697
1705
  return self._bin_range(self._data_nodes[0])
@@ -1950,7 +1958,6 @@ class GaussianProcessEmulator1Dx1D(BaseEmulator):
1950
1958
  pred_low: float | npt.NDArray,
1951
1959
  pred_up: float | npt.NDArray,
1952
1960
  ) -> float | npt.NDArray:
1953
-
1954
1961
  # Get node interpolation config.
1955
1962
  interp_node_x_type = self._config_emu.config_node.x_interp_type
1956
1963
  interp_node_y_type = self._config_emu.config_node.y_interp_type
@@ -1975,7 +1982,6 @@ class GaussianProcessEmulator1Dx1D(BaseEmulator):
1975
1982
  return pred_interp
1976
1983
 
1977
1984
  def _bin_range(self, node_var) -> tuple[float, float]:
1978
-
1979
1985
  # Check node range.
1980
1986
  node_var_min, node_var_max = self._node_var_range
1981
1987
  _utils_inputs.check_emulation_range(
@@ -35,7 +35,6 @@ RESOURCES = files("emantis")
35
35
 
36
36
 
37
37
  def read_emulation_config_from_file(filepath: str) -> dict:
38
-
39
38
  # Read emulation data config.
40
39
  with as_file(RESOURCES / f"data/{filepath}") as mytoml:
41
40
  with open(mytoml, "rb") as f:
@@ -45,7 +44,6 @@ def read_emulation_config_from_file(filepath: str) -> dict:
45
44
 
46
45
 
47
46
  def read_emulation_config(observable: str, model: str, sim_version: int) -> dict:
48
-
49
47
  # Emulation config file name.
50
48
  filepath = (
51
49
  f"{observable}/{observable}_{model}_emu_v{sim_version}_emulation_config.toml"
@@ -57,7 +55,6 @@ def read_emulation_config(observable: str, model: str, sim_version: int) -> dict
57
55
 
58
56
 
59
57
  def read_cosmo_params_from_file(filepath: str) -> npt.NDArray:
60
-
61
58
  # Read values of the cosmological parameters.
62
59
  with as_file(RESOURCES / f"data/{filepath}") as mytxt:
63
60
  cosmo_params = np.genfromtxt(mytxt, skip_header=1)
@@ -66,7 +63,6 @@ def read_cosmo_params_from_file(filepath: str) -> npt.NDArray:
66
63
 
67
64
 
68
65
  def read_cosmo_params(model: str, sim_version: int) -> npt.NDArray:
69
-
70
66
  # File with cosmological parameters values.
71
67
  filepath = f"cosmo_params_{model}_emu_v{sim_version}.txt"
72
68
  # Read parameters.
@@ -76,7 +72,6 @@ def read_cosmo_params(model: str, sim_version: int) -> npt.NDArray:
76
72
 
77
73
 
78
74
  def read_cosmo_params_range_from_file(filepath: str) -> dict:
79
-
80
75
  # Read emulation range in terms of cosmological parameters.
81
76
  with as_file(RESOURCES / f"data/{filepath}") as mytoml:
82
77
  with open(mytoml, "rb") as f:
@@ -87,7 +82,6 @@ def read_cosmo_params_range_from_file(filepath: str) -> dict:
87
82
 
88
83
 
89
84
  def read_cosmo_params_range(model: str, sim_version: int) -> dict:
90
-
91
85
  # File with range of cosmological parameters.
92
86
  filepath = f"cosmo_params_{model}_emu_v{sim_version}_config.toml"
93
87
  # Read ranges.
@@ -121,7 +115,6 @@ def read_data_bspline(
121
115
  dict[float, int],
122
116
  dict[float, npt.NDArray] | None,
123
117
  ]:
124
-
125
118
  if prefix is None:
126
119
  prefix = ""
127
120
 
@@ -175,7 +168,6 @@ def read_data_binned(
175
168
  dict[float, npt.NDArray],
176
169
  dict[float, npt.NDArray] | None,
177
170
  ]:
178
-
179
171
  if prefix is None:
180
172
  prefix = ""
181
173
 
@@ -55,7 +55,6 @@ class PCATransformer:
55
55
  random_seed: int | None = None,
56
56
  **pca_extra_args,
57
57
  ) -> None:
58
-
59
58
  # Number of PCA components to keep.
60
59
  self.n_components = pca_components
61
60
 
@@ -80,12 +79,12 @@ class PCATransformer:
80
79
  # Random seed.
81
80
  self.random_seed = random_seed
82
81
 
83
- def fit(self, data):
82
+ def fit(self, data) -> None:
84
83
  """Fit the PCA transformer.
85
84
 
86
85
  Parameters
87
86
  ----------
88
- data : array of shape(n_samples, n_features)
87
+ data : array of shape (n_samples, n_features)
89
88
  The data array, where `n_samples` is the number of samples and `n_features` is the number of features.
90
89
  """
91
90
  # Fit the data scalers.
@@ -108,12 +107,12 @@ class PCATransformer:
108
107
 
109
108
  Parameters
110
109
  ----------
111
- data : array of shape(n_samples, n_features)
110
+ data : array of shape (n_samples, n_features)
112
111
  The data array, where `n_samples` is the number of samples and `n_features` is the number of features.
113
112
 
114
113
  Returns
115
114
  -------
116
- data_transformed : array of shape(n_samples, n_components)
115
+ data_transformed : array of shape (n_samples, n_components)
117
116
  The transformed data array, where `n_samples` is the number of samples and `n_components` is the number of PCA components.
118
117
  """
119
118
  # Transform data (scaling + PCA).
@@ -129,12 +128,12 @@ class PCATransformer:
129
128
 
130
129
  Parameters
131
130
  ----------
132
- data_transformed : array of shape(n_samples, n_components)
131
+ data_transformed : array of shape (n_samples, n_components)
133
132
  A data array in the transformed space, where `n_samples` is the number of samples and `n_components` is the number of PCA components.
134
133
 
135
134
  Returns
136
135
  -------
137
- data_original : array of shape(n_samples, n_features)
136
+ data_original : array of shape (n_samples, n_features)
138
137
  The original data array, which would be transformed into `data_transformed`, where `n_samples` is the number of samples and `n_features` is the number of features.
139
138
  """
140
139
  # Inverse transform data (inverse PCA + inverse scaling).
@@ -153,14 +152,14 @@ class PCATransformer:
153
152
 
154
153
  Parameters
155
154
  ----------
156
- data : array of shape(n_samples, n_features)
155
+ data : array of shape (n_samples, n_features)
157
156
  The data array, where `n_samples` is the number of samples and `n_features` is the number of features.
158
- data_std : array of shape(n_samples, n_features)
157
+ data_std : array of shape (n_samples, n_features)
159
158
  The data standard deviation array, where `n_samples` is the number of samples and `n_features` is the number of features.
160
159
 
161
160
  Returns
162
161
  -------
163
- data_transformed : array of shape(n_samples, n_components)
162
+ data_transformed : array of shape (n_samples, n_components)
164
163
  The transformed data standard deviation array, where `n_samples` is the number of samples and `n_components` is the number of PCA components.
165
164
  """
166
165
  # TODO Optimize: make analytical or vectorize.
@@ -193,14 +192,14 @@ class PCATransformer:
193
192
 
194
193
  Parameters
195
194
  ----------
196
- data_transformed : array of shape(n_samples, n_components)
195
+ data_transformed : array of shape (n_samples, n_components)
197
196
  A data array in the transformed space, where `n_samples` is the number of samples and `n_components` is the number of PCA components.
198
- data_transformed_std : array of shape(n_samples, n_components)
197
+ data_transformed_std : array of shape (n_samples, n_components)
199
198
  The standard deviation array of the data in the transformed space, where `n_samples` is the number of samples and `n_components` is the number of PCA components.
200
199
 
201
200
  Returns
202
201
  -------
203
- data_original_std : array of shape(n_samples, n_features), optional (default=None)
202
+ data_original_std : array of shape (n_samples, n_features), optional (default=None)
204
203
  The standard deviation of the original data array, which would be transformed into `data_transformed`, where `n_samples` is the number of samples and `n_features` is the number of features.
205
204
  """
206
205
  # TODO Optimize: make analytical or vectorize.
@@ -107,7 +107,6 @@ def format_input_to_1d_array(
107
107
  def convert_cosmo_params_from_As_to_sigma8(
108
108
  cosmo_params: dict, sigma8_emulator, sigma8_name: str
109
109
  ) -> dict:
110
-
111
110
  # If A_s not present do nothing.
112
111
  if "A_s" not in cosmo_params:
113
112
  return cosmo_params
@@ -122,7 +121,6 @@ def convert_cosmo_params_from_As_to_sigma8(
122
121
 
123
122
  # Loop over input parameter names.
124
123
  for param in cosmo_params:
125
-
126
124
  # If sigma8 is also present raise an exception.
127
125
  if "sigma8" in param:
128
126
  raise ValueError(
@@ -82,7 +82,6 @@ class HMFEmulator(GaussianProcessEmulator1Dx1D):
82
82
  verbose: bool = True,
83
83
  use_persistent_storage: bool = True,
84
84
  ) -> None:
85
-
86
85
  # Check model.
87
86
  if model not in _HMF_MODELS:
88
87
  raise ValueError(f"`model` must be one of: {_HMF_MODELS}.")
@@ -178,7 +177,7 @@ class HMFEmulator(GaussianProcessEmulator1Dx1D):
178
177
  mass_def_string = f"deltac_{delta_c:g}"
179
178
 
180
179
  else:
181
- raise ValueError(f"Incorrect mass definition (`mass_def`).")
180
+ raise ValueError("Incorrect mass definition (`mass_def`).")
182
181
 
183
182
  return mass_def_string
184
183
 
@@ -236,7 +235,6 @@ class HMFEmulator(GaussianProcessEmulator1Dx1D):
236
235
  """
237
236
  # Check if A_s in present in the input cosmological parameters.
238
237
  if "A_s" in cosmo_params:
239
-
240
238
  # Needs to be changed if multiple parameters with sigma8 in the name are present.
241
239
  sigma8_name = [param for param in self.params_range if "sigma8" in param][0]
242
240
  cosmo_params = convert_cosmo_params_from_As_to_sigma8(
@@ -70,7 +70,6 @@ class Sigma8Emulator(GaussianProcessEmulator1D):
70
70
  verbose: bool = True,
71
71
  use_persistent_storage: bool = True,
72
72
  ) -> None:
73
-
74
73
  # Check model.
75
74
  if model not in _SIGMA8_MODELS:
76
75
  raise ValueError(f"`model` must be one of: {_SIGMA8_MODELS}.")
@@ -168,7 +167,6 @@ class NonLinearBoostEmulator(GaussianProcessEmulator1Dx1D):
168
167
  verbose: bool = True,
169
168
  use_persistent_storage: bool = True,
170
169
  ) -> None:
171
-
172
170
  # Check model.
173
171
  if model not in _NL_BOOST_MODELS:
174
172
  raise ValueError(f"`model` must be one of: {_NL_BOOST_MODELS}.")
@@ -266,7 +264,6 @@ class NonLinearBoostEmulator(GaussianProcessEmulator1Dx1D):
266
264
  """
267
265
  # Check if A_s in present in the input cosmological parameters.
268
266
  if "A_s" in cosmo_params:
269
-
270
267
  # Needs to be changed if multiple parameters with sigma8 in the name are present.
271
268
  sigma8_name = [param for param in self.params_range if "sigma8" in param][0]
272
269
  cosmo_params = convert_cosmo_params_from_As_to_sigma8(
@@ -340,7 +337,6 @@ class NonLinearMGBoostEmulator(GaussianProcessEmulator1Dx1D):
340
337
  verbose: bool = True,
341
338
  use_persistent_storage: bool = True,
342
339
  ) -> None:
343
-
344
340
  # Check model.
345
341
  if model not in _NL_MG_BOOST_MODELS:
346
342
  raise ValueError(f"`model` must be one of: {_NL_MG_BOOST_MODELS}.")
@@ -408,6 +404,7 @@ class NonLinearMGBoostEmulator(GaussianProcessEmulator1Dx1D):
408
404
  k: float | list[float] | npt.NDArray | None = None,
409
405
  squeeze: bool = True,
410
406
  extrapolate_k_low: bool = True,
407
+ extrapolate_cosmo: bool = False,
411
408
  ) -> npt.NDArray:
412
409
  """Predict the non-linear modified gravity matter power spectrum boost.
413
410
 
@@ -437,6 +434,10 @@ class NonLinearMGBoostEmulator(GaussianProcessEmulator1Dx1D):
437
434
  Extrapolation to low wavenumber values.
438
435
  If True, the emulator will extrapolate its predictions for wavenumber values below the minimum emulation range.
439
436
  This is extrapolation should be safe to use.
437
+ extrapolate_cosmo : bool, optinal (default=False)
438
+ Extrapolation in terms of cosmological parameters.
439
+ If True, do a constant extrapolation of the boost for cosmological parameters outside of the emulation range.
440
+ Only for standard parameters, there is no extrapolation for the modified gravity parameters.
440
441
 
441
442
  Returns
442
443
  -------
@@ -450,13 +451,31 @@ class NonLinearMGBoostEmulator(GaussianProcessEmulator1Dx1D):
450
451
  """
451
452
  # Check if A_s in present in the input cosmological parameters.
452
453
  if "A_s" in cosmo_params:
453
-
454
454
  # Needs to be changed if multiple parameters with sigma8 in the name are present.
455
+ # TODO: check that this works for v1 emulator. Probably it does not.
455
456
  sigma8_name = [param for param in self.params_range if "sigma8" in param][0]
456
457
  cosmo_params = convert_cosmo_params_from_As_to_sigma8(
457
458
  cosmo_params, self._sigma8_emulator, sigma8_name
458
459
  )
459
460
 
461
+ # Constant extrapolation in cosmological parameters.
462
+ if extrapolate_cosmo:
463
+ # Check input parameter names.
464
+ if cosmo_params.keys() != self.params_range.keys():
465
+ raise KeyError(
466
+ f"Incorrect input parameter names. You must provide values for (and only for): {list(self.params_range.keys())}."
467
+ )
468
+ for param in self.params_range:
469
+ # TODO: this assumes f(R) gravity.
470
+ # Do not extrapolate logfR0.
471
+ if param == "logfR0":
472
+ continue
473
+ cosmo_params[param] = np.clip(
474
+ cosmo_params[param],
475
+ a_min=self.params_range[param]["min_value"],
476
+ a_max=self.params_range[param]["max_value"],
477
+ )
478
+
460
479
  # TODO: the extrapolation and clipping to low k assumes f(R) model.
461
480
  # Needs to be modified for future extension to other models.
462
481
  return np.clip(
@@ -641,9 +641,6 @@ class FofrBoost:
641
641
 
642
642
  # Predict the power spectrum boost using the trained GPR instance.
643
643
 
644
- # Number of samples to predict.
645
- nmodels = cosmo_params.shape[0]
646
-
647
644
  # Predict the PCA coefficients
648
645
  boost_pred_reduced = self._emu_aexp_node[aexp]["GPR"].predict(cosmo_params)
649
646
 
@@ -19,9 +19,7 @@ _HMF_MASS_DEF = [f"b{elt}" for elt in _FOF_B_VALUES] + [
19
19
  @pytest.mark.parametrize("model", _HMF_MODELS)
20
20
  @pytest.mark.parametrize("mass_def", _HMF_MASS_DEF)
21
21
  class TestHMFEmulator:
22
-
23
22
  def test_train(self, model, mass_def):
24
-
25
23
  # Init. emulator.
26
24
  emu = HMFEmulator(model=model, mass_def=mass_def, n_jobs=n_jobs)
27
25
 
@@ -40,7 +38,6 @@ class TestHMFEmulator:
40
38
  )
41
39
 
42
40
  def test_predict(self, model, mass_def):
43
-
44
41
  # Init. emulator.
45
42
  emu = HMFEmulator(model=model, mass_def=mass_def, n_jobs=n_jobs)
46
43
 
@@ -51,7 +48,6 @@ class TestHMFEmulator:
51
48
 
52
49
  # Loop over scale factor nodes.
53
50
  for aexp in emu.aexp_nodes:
54
-
55
51
  cosmo_params = emu._emulator_nodes[aexp]._params
56
52
  cosmo_params_dict = {
57
53
  param: cosmo_params[:, i]
@@ -97,7 +93,6 @@ class TestHMFEmulator:
97
93
 
98
94
  # Loop over scale factor nodes.
99
95
  for aexp in emu.aexp_nodes:
100
-
101
96
  cosmo_params = emu._emulator_nodes[aexp]._params
102
97
  cosmo_params_dict = {
103
98
  param: cosmo_params[:, i]
@@ -146,7 +141,6 @@ class TestHMFEmulator:
146
141
 
147
142
  # Loop over scale factor nodes.
148
143
  for aexp in emu.aexp_nodes:
149
-
150
144
  cosmo_params = emu._emulator_nodes[aexp]._params
151
145
  cosmo_params_dict = {
152
146
  param: cosmo_params[:, i]
@@ -15,9 +15,50 @@ n_jobs_max = 6
15
15
  n_jobs = min(joblib.cpu_count(), n_jobs_max)
16
16
 
17
17
 
18
+ @pytest.mark.parametrize("model", _SIGMA8_MODELS)
19
+ class TestSigma8Emulator:
20
+ def test_train(self, model):
21
+ # Init. emulator.
22
+ emu = Sigma8Emulator(model=model)
23
+
24
+ emu.train()
25
+
26
+ # Check that instance has a trained emulator.
27
+ assert bool(emu._gp_regressor_list)
28
+ # Check consistency in the number of GP outputs.
29
+ assert emu._gp_n_outputs == len(emu._gp_regressor_list)
30
+
31
+ def test_predict(self, model):
32
+ # Init. emulator.
33
+ emu = Sigma8Emulator(model=model)
34
+
35
+ # Check that params range dict is present.
36
+ assert emu.params_range is not None
37
+
38
+ emu.load_train_emulator()
39
+
40
+ cosmo_params = emu._params
41
+ cosmo_params_dict = {
42
+ param: cosmo_params[:, i] for i, param in enumerate(emu.params_range.keys())
43
+ }
44
+
45
+ data = emu._data
46
+
47
+ pred = emu.predict_sigma8(cosmo_params_dict)
48
+
49
+ # Check pred array shape.
50
+ assert pred.shape == (data.shape[0],)
51
+
52
+ # Check that mean absolute relative difference
53
+ # between emulator and training data is smaller than 0.01%
54
+ abs_rel_diff = np.abs((pred - data[:, 0]) / data[:, 0])
55
+ mean_abs_rel_diff = np.mean(abs_rel_diff)
56
+
57
+ assert mean_abs_rel_diff < 1e-3
58
+
59
+
18
60
  @pytest.mark.parametrize("model", _NL_MG_BOOST_MODELS)
19
61
  class TestNonLinearMGBoostEmulator:
20
-
21
62
  def test_train(self, model):
22
63
  """Test the training."""
23
64
 
@@ -54,7 +95,6 @@ class TestNonLinearMGBoostEmulator:
54
95
 
55
96
  # Loop over scale factor nodes.
56
97
  for aexp in emu.aexp_nodes:
57
-
58
98
  cosmo_params = emu._emulator_nodes[aexp]._params
59
99
  cosmo_params_dict = {
60
100
  param: cosmo_params[:, i]
@@ -85,7 +125,6 @@ class TestNonLinearMGBoostEmulator:
85
125
 
86
126
  # Loop over scale factor nodes.
87
127
  for aexp in emu.aexp_nodes:
88
-
89
128
  cosmo_params = emu._emulator_nodes[aexp]._params
90
129
  cosmo_params_dict = {
91
130
  param: cosmo_params[:, i]
@@ -111,7 +150,6 @@ class TestNonLinearMGBoostEmulator:
111
150
  assert mean_abs_rel_diff < 1e-6
112
151
 
113
152
  def test_emulation_range_exception(self, model):
114
-
115
153
  # Init. emulator.
116
154
  emu = NonLinearMGBoostEmulator(model=model, n_jobs=n_jobs)
117
155
 
@@ -138,9 +176,7 @@ class TestNonLinearMGBoostEmulator:
138
176
 
139
177
 
140
178
  class TestNonLinearFofrBoostEmulators:
141
-
142
179
  def test_new_interface_v1_vs_v2(self):
143
-
144
180
  # Init. emulator.
145
181
  emu_v1 = NonLinearMGBoostEmulator(model="fR_v1", n_jobs=n_jobs)
146
182
  emu_v2 = NonLinearMGBoostEmulator(model="fR", n_jobs=n_jobs)
@@ -181,7 +217,6 @@ class TestNonLinearFofrBoostEmulators:
181
217
 
182
218
  # Loop over scale factor values.
183
219
  for aexp in aexp_list:
184
-
185
220
  pred_v1 = emu_v1.predict_boost(cosmo_params_v1, aexp)
186
221
  pred_v2 = emu_v2.predict_boost(cosmo_params_v2, aexp)
187
222
 
@@ -202,7 +237,6 @@ class TestNonLinearFofrBoostEmulators:
202
237
  assert mean_abs_rel_diff < 1e-2
203
238
 
204
239
  def test_v1_new_vs_old_interface(self):
205
-
206
240
  # Init. emulator.
207
241
  emu = NonLinearMGBoostEmulator(model="fR_v1", n_jobs=n_jobs)
208
242
 
@@ -237,7 +271,6 @@ class TestNonLinearFofrBoostEmulators:
237
271
 
238
272
  # Loop over scale factor values.
239
273
  for aexp in aexp_list:
240
-
241
274
  pred = emu.predict_boost(cosmo_params, aexp)
242
275
  pred_old = emu_old.predict_boost(
243
276
  omega_m=cosmo_params["Omega_m"],
@@ -267,48 +300,3 @@ class TestNonLinearFofrBoostEmulators:
267
300
  mean_abs_rel_diff = np.mean(abs_rel_diff)
268
301
 
269
302
  assert mean_abs_rel_diff < 5e-3
270
-
271
-
272
- @pytest.mark.parametrize("model", _SIGMA8_MODELS)
273
- class TestSigma8Emulator:
274
-
275
- def test_train(self, model):
276
-
277
- # Init. emulator.
278
- emu = Sigma8Emulator(model=model)
279
-
280
- emu.train()
281
-
282
- # Check that instance has a trained emulator.
283
- assert bool(emu._gp_regressor_list)
284
- # Check consistency in the number of GP outputs.
285
- assert emu._gp_n_outputs == len(emu._gp_regressor_list)
286
-
287
- def test_predict(self, model):
288
-
289
- # Init. emulator.
290
- emu = Sigma8Emulator(model=model)
291
-
292
- # Check that params range dict is present.
293
- assert emu.params_range is not None
294
-
295
- emu.load_train_emulator()
296
-
297
- cosmo_params = emu._params
298
- cosmo_params_dict = {
299
- param: cosmo_params[:, i] for i, param in enumerate(emu.params_range.keys())
300
- }
301
-
302
- data = emu._data
303
-
304
- pred = emu.predict_sigma8(cosmo_params_dict)
305
-
306
- # Check pred array shape.
307
- assert pred.shape == (data.shape[0],)
308
-
309
- # Check that mean absolute relative difference
310
- # between emulator and training data is smaller than 0.01%
311
- abs_rel_diff = np.abs((pred - data[:, 0]) / data[:, 0])
312
- mean_abs_rel_diff = np.mean(abs_rel_diff)
313
-
314
- assert mean_abs_rel_diff < 1e-3
File without changes
File without changes
File without changes