flipcosmo 1.0.0__py3-none-any.whl → 1.2.1__py3-none-any.whl
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.
- docs/conf.py +154 -0
- flip/__init__.py +4 -11
- flip/covariance/__init__.py +7 -8
- flip/covariance/analytical/__init__.py +11 -0
- flip/covariance/{adamsblake17plane → analytical/adamsblake17}/coefficients.py +1 -1
- flip/covariance/{adamsblake17plane → analytical/adamsblake17}/fisher_terms.py +1 -1
- flip/covariance/{adamsblake17 → analytical/adamsblake17}/flip_terms.py +0 -1
- flip/covariance/{adamsblake17 → analytical/adamsblake17plane}/coefficients.py +1 -1
- flip/covariance/{adamsblake17 → analytical/adamsblake17plane}/fisher_terms.py +1 -1
- flip/covariance/{adamsblake17plane → analytical/adamsblake17plane}/flip_terms.py +0 -1
- flip/covariance/{adamsblake17plane → analytical/adamsblake17plane}/generator.py +103 -19
- flip/covariance/{adamsblake20 → analytical/adamsblake20}/coefficients.py +1 -1
- flip/covariance/{adamsblake20 → analytical/adamsblake20}/fisher_terms.py +1 -1
- flip/covariance/{adamsblake20 → analytical/adamsblake20}/flip_terms.py +0 -1
- flip/covariance/{carreres23 → analytical/carreres23}/coefficients.py +1 -4
- flip/covariance/{ravouxnoanchor25 → analytical/carreres23}/fisher_terms.py +1 -1
- flip/covariance/{carreres23 → analytical/carreres23}/flip_terms.py +0 -1
- flip/covariance/analytical/carreres23/generator.py +198 -0
- flip/covariance/analytical/genericzdep/__init__.py +5 -0
- flip/covariance/analytical/genericzdep/coefficients.py +53 -0
- flip/covariance/analytical/genericzdep/flip_terms.py +99 -0
- flip/covariance/{lai22 → analytical/lai22}/coefficients.py +2 -3
- flip/covariance/{lai22 → analytical/lai22}/fisher_terms.py +1 -1
- flip/covariance/{lai22 → analytical/lai22}/flip_terms.py +0 -1
- flip/covariance/{lai22 → analytical/lai22}/generator.py +263 -58
- flip/covariance/{lai22 → analytical/lai22}/symbolic.py +55 -19
- flip/covariance/{ravouxcarreres → analytical/ravouxcarreres}/coefficients.py +1 -1
- flip/covariance/{ravouxcarreres → analytical/ravouxcarreres}/fisher_terms.py +1 -1
- flip/covariance/{ravouxcarreres → analytical/ravouxcarreres}/flip_terms.py +0 -1
- flip/covariance/{ravouxnoanchor25 → analytical/ravouxnoanchor25}/coefficients.py +3 -2
- flip/covariance/{carreres23 → analytical/ravouxnoanchor25}/fisher_terms.py +1 -1
- flip/covariance/{ravouxnoanchor25 → analytical/ravouxnoanchor25}/flip_terms.py +0 -9
- flip/covariance/{rcrk24 → analytical/rcrk24}/coefficients.py +6 -6
- flip/covariance/{rcrk24 → analytical/rcrk24}/fisher_terms.py +7 -9
- flip/covariance/{rcrk24 → analytical/rcrk24}/flip_terms.py +0 -8
- flip/covariance/contraction.py +82 -40
- flip/covariance/cov_utils.py +89 -81
- flip/covariance/covariance.py +172 -141
- flip/covariance/emulators/__init__.py +1 -1
- flip/covariance/emulators/generator.py +73 -3
- flip/covariance/emulators/gpmatrix.py +40 -1
- flip/covariance/emulators/nnmatrix.py +57 -1
- flip/covariance/emulators/skgpmatrix.py +125 -0
- flip/covariance/fisher.py +307 -0
- flip/{fit_utils.py → covariance/fit_utils.py} +185 -10
- flip/{fitter.py → covariance/fitter.py} +151 -125
- flip/covariance/generator.py +82 -106
- flip/{likelihood.py → covariance/likelihood.py} +286 -64
- flip/{plot_utils.py → covariance/plot_utils.py} +79 -4
- flip/covariance/symbolic.py +89 -44
- flip/data/__init__.py +1 -1
- flip/data/data_density.parquet +0 -0
- flip/data/data_velocity.parquet +0 -0
- flip/data/{grid_window_m.parquet → data_window_density.parquet} +0 -0
- flip/{gridding.py → data/gridding.py} +125 -130
- flip/data/load_data_test.py +102 -0
- flip/data/power_spectrum_mm.txt +2 -2
- flip/data/power_spectrum_mt.txt +2 -2
- flip/data/power_spectrum_tt.txt +2 -2
- flip/data/test_covariance_reference_values.json +145 -0
- flip/data/test_e2e_reference_values.json +14 -0
- flip/data_vector/basic.py +118 -101
- flip/data_vector/cosmo_utils.py +18 -0
- flip/data_vector/galaxypv_vectors.py +58 -94
- flip/data_vector/snia_vectors.py +60 -3
- flip/data_vector/vector_utils.py +47 -1
- flip/power_spectra/class_engine.py +36 -1
- flip/power_spectra/cosmoprimo_engine.py +37 -2
- flip/power_spectra/generator.py +47 -25
- flip/power_spectra/models.py +30 -31
- flip/power_spectra/pyccl_engine.py +36 -1
- flip/simulation/__init__.py +0 -0
- flip/utils.py +62 -91
- flipcosmo-1.2.1.dist-info/METADATA +78 -0
- flipcosmo-1.2.1.dist-info/RECORD +109 -0
- {flipcosmo-1.0.0.dist-info → flipcosmo-1.2.1.dist-info}/WHEEL +1 -1
- flipcosmo-1.2.1.dist-info/top_level.txt +7 -0
- scripts/flip_compute_correlation_model.py +70 -0
- scripts/flip_compute_power_spectra.py +50 -0
- scripts/flip_fisher_forecast_velocity.py +70 -0
- scripts/flip_fisher_rcrk24.py +164 -0
- scripts/flip_launch_minuit_density_fit.py +91 -0
- scripts/flip_launch_minuit_full_fit.py +117 -0
- scripts/flip_launch_minuit_velocity_fit.py +78 -0
- scripts/flip_launch_minuit_velocity_fit_full.py +107 -0
- scripts/flip_launch_minuit_velocity_fit_interpolation.py +93 -0
- test/refresh_reference_values.py +43 -0
- test/test_covariance_assembly.py +102 -0
- test/test_covariance_reference_values.py +125 -0
- test/test_covariance_utils.py +34 -0
- test/test_e2e_density.py +50 -0
- test/test_e2e_joint.py +65 -0
- test/test_e2e_velocity.py +53 -0
- test/test_likelihood_inversions.py +31 -0
- flip/covariance/carreres23/generator.py +0 -132
- flip/data/density_data.parquet +0 -0
- flip/data/velocity_data.parquet +0 -0
- flip/fisher.py +0 -190
- flipcosmo-1.0.0.dist-info/METADATA +0 -32
- flipcosmo-1.0.0.dist-info/RECORD +0 -82
- flipcosmo-1.0.0.dist-info/top_level.txt +0 -1
- /flip/{config.py → _config.py} +0 -0
- /flip/covariance/{adamsblake17 → analytical/adamsblake17}/__init__.py +0 -0
- /flip/covariance/{adamsblake17plane → analytical/adamsblake17plane}/__init__.py +0 -0
- /flip/covariance/{adamsblake20 → analytical/adamsblake20}/__init__.py +0 -0
- /flip/covariance/{carreres23 → analytical/carreres23}/__init__.py +0 -0
- /flip/covariance/{lai22 → analytical/lai22}/__init__.py +0 -0
- /flip/covariance/{lai22 → analytical/lai22}/h_terms.py +0 -0
- /flip/covariance/{ravouxcarreres → analytical/ravouxcarreres}/__init__.py +0 -0
- /flip/covariance/{ravouxcarreres → analytical/ravouxcarreres}/flip_terms_lmax.py +0 -0
- /flip/covariance/{ravouxnoanchor25 → analytical/ravouxnoanchor25}/__init__.py +0 -0
- /flip/covariance/{rcrk24 → analytical/rcrk24}/__init__.py +0 -0
- {flipcosmo-1.0.0.dist-info → flipcosmo-1.2.1.dist-info}/licenses/LICENSE +0 -0
|
@@ -2,8 +2,6 @@ import importlib
|
|
|
2
2
|
|
|
3
3
|
import numpy as np
|
|
4
4
|
|
|
5
|
-
import flip.covariance.emulators.gpmatrix as gpmatrix
|
|
6
|
-
import flip.covariance.emulators.nnmatrix as nnmatrix
|
|
7
5
|
from flip.covariance import cov_utils
|
|
8
6
|
from flip.utils import create_log
|
|
9
7
|
|
|
@@ -12,6 +10,7 @@ log = create_log()
|
|
|
12
10
|
_avail_emulator_models = [
|
|
13
11
|
"gpmatrix",
|
|
14
12
|
"nnmatrix",
|
|
13
|
+
"skgpmatrix",
|
|
15
14
|
]
|
|
16
15
|
|
|
17
16
|
|
|
@@ -24,6 +23,23 @@ def compute_cov(
|
|
|
24
23
|
test_emulator=False,
|
|
25
24
|
**kwargs,
|
|
26
25
|
):
|
|
26
|
+
"""Train an emulator for a given covariance type and return evaluators.
|
|
27
|
+
|
|
28
|
+
Args:
|
|
29
|
+
emulator_model_name: Backend name, one of ``gpmatrix``, ``nnmatrix``, ``skgpmatrix``.
|
|
30
|
+
covariance_list: List of covariance objects with precomputed matrices.
|
|
31
|
+
parameter_values: Array ``(n_samples, n_params)`` training inputs.
|
|
32
|
+
emulator_parameter_names: Names of parameters to pass at evaluation time.
|
|
33
|
+
covariance_type: One of ``"gg"``, ``"vv"``, ``"gv"`` indicating block type.
|
|
34
|
+
test_emulator: If True, runs a quick evaluation vs. training data and logs errors.
|
|
35
|
+
**kwargs: Extra keyword arguments forwarded to backend ``train``.
|
|
36
|
+
|
|
37
|
+
Returns:
|
|
38
|
+
List of callables, one per covariance term, taking a parameter dict and returning a matrix.
|
|
39
|
+
|
|
40
|
+
Raises:
|
|
41
|
+
ValueError: If list lengths mismatch or model name is invalid.
|
|
42
|
+
"""
|
|
27
43
|
if len(covariance_list) != len(parameter_values):
|
|
28
44
|
raise ValueError(
|
|
29
45
|
"covariance_list and parameter_values must have the same length."
|
|
@@ -38,7 +54,7 @@ def compute_cov(
|
|
|
38
54
|
f"flip.covariance.emulators.{emulator_model_name}"
|
|
39
55
|
)
|
|
40
56
|
|
|
41
|
-
emulator_type = emulator_module._emulator_type
|
|
57
|
+
# emulator_type = emulator_module._emulator_type
|
|
42
58
|
# Only implemented for matrix emulators, so far.
|
|
43
59
|
|
|
44
60
|
square_covariance, emulator_output_variance, emulator_output_non_diagonal = (
|
|
@@ -86,6 +102,19 @@ def prepare_covariance_matrices(
|
|
|
86
102
|
covariance_list,
|
|
87
103
|
covariance_type,
|
|
88
104
|
):
|
|
105
|
+
"""Extract and stack covariance training targets for emulator backends.
|
|
106
|
+
|
|
107
|
+
Converts each covariance object into arrays for diagonal and non-diagonal
|
|
108
|
+
parts depending on the covariance type.
|
|
109
|
+
|
|
110
|
+
Args:
|
|
111
|
+
covariance_list: List of covariance objects.
|
|
112
|
+
covariance_type: Block type ``("gg"|"vv"|"gv")``.
|
|
113
|
+
|
|
114
|
+
Returns:
|
|
115
|
+
Tuple ``(square_covariance, output_variance, output_non_diagonal)`` where
|
|
116
|
+
arrays have shapes compatible with backend trainers.
|
|
117
|
+
"""
|
|
89
118
|
if covariance_type[0] == covariance_type[1]:
|
|
90
119
|
square_covariance = True
|
|
91
120
|
else:
|
|
@@ -132,6 +161,21 @@ def return_evaluation_functions(
|
|
|
132
161
|
covariance_type,
|
|
133
162
|
**kwargs,
|
|
134
163
|
):
|
|
164
|
+
"""Wrap backend models into per-term evaluation functions.
|
|
165
|
+
|
|
166
|
+
Each returned function accepts a parameter dict mapping names to values and
|
|
167
|
+
returns either a square matrix (gg/vv) or a flattened vector (gv).
|
|
168
|
+
|
|
169
|
+
Args:
|
|
170
|
+
models: Tuple of backend-trained models and evaluation dictionaries.
|
|
171
|
+
emulator_module: Module providing ``evaluate(model, x, dict)`` function.
|
|
172
|
+
emulator_parameter_names: Names used to extract parameter order from dict.
|
|
173
|
+
covariance_type: Block type ``("gg"|"vv"|"gv")``.
|
|
174
|
+
**kwargs: Extra keyword arguments (unused).
|
|
175
|
+
|
|
176
|
+
Returns:
|
|
177
|
+
List of evaluation callables for each covariance term.
|
|
178
|
+
"""
|
|
135
179
|
|
|
136
180
|
if covariance_type[0] == covariance_type[1]:
|
|
137
181
|
square_covariance = True
|
|
@@ -222,6 +266,19 @@ def test_training(
|
|
|
222
266
|
verbose=True,
|
|
223
267
|
**kwargs,
|
|
224
268
|
):
|
|
269
|
+
"""Compute emulator errors against training covariances for sanity checks.
|
|
270
|
+
|
|
271
|
+
Args:
|
|
272
|
+
evaluation_functions: List of term evaluators returned by ``return_evaluation_functions``.
|
|
273
|
+
covariance_list: List of covariance objects (ground truth).
|
|
274
|
+
parameter_values_dict: List of parameter dicts matching training inputs.
|
|
275
|
+
covariance_type: Block type ``("gg"|"vv"|"gv")``.
|
|
276
|
+
verbose: If True, logs per-term maximal relative errors.
|
|
277
|
+
**kwargs: Extra keyword arguments (unused).
|
|
278
|
+
|
|
279
|
+
Returns:
|
|
280
|
+
Nested list of errors per sample and term: ``[ [err_diag, rel_err_diag, err_all, rel_err_all], ... ]``.
|
|
281
|
+
"""
|
|
225
282
|
if covariance_type[0] == covariance_type[1]:
|
|
226
283
|
square_covariance = True
|
|
227
284
|
else:
|
|
@@ -281,6 +338,19 @@ def generate_covariance(
|
|
|
281
338
|
emulator_parameter_names,
|
|
282
339
|
**kwargs,
|
|
283
340
|
):
|
|
341
|
+
"""Generate emulator evaluators for requested covariance blocks.
|
|
342
|
+
|
|
343
|
+
Args:
|
|
344
|
+
emulator_model_name: Backend name.
|
|
345
|
+
model_kind: One of ``"density"``, ``"velocity"``, ``"full"``, ``"density_velocity"``.
|
|
346
|
+
covariance_list: List of covariance objects for training.
|
|
347
|
+
parameter_values: Array ``(n_samples, n_params)`` training inputs.
|
|
348
|
+
emulator_parameter_names: Parameter names used at evaluation.
|
|
349
|
+
**kwargs: Forwarded to backend trainers.
|
|
350
|
+
|
|
351
|
+
Returns:
|
|
352
|
+
Dict with keys among ``{"gg","vv","gv"}`` mapping to lists of evaluator functions.
|
|
353
|
+
"""
|
|
284
354
|
|
|
285
355
|
emulator_covariance_dict = {}
|
|
286
356
|
|
|
@@ -8,7 +8,7 @@ try:
|
|
|
8
8
|
import GPy
|
|
9
9
|
|
|
10
10
|
gpy_installed = True
|
|
11
|
-
except:
|
|
11
|
+
except ImportError:
|
|
12
12
|
gpy_installed = False
|
|
13
13
|
log.add(
|
|
14
14
|
"Install GPy to use the gpmatrix emulator",
|
|
@@ -38,6 +38,35 @@ def train(
|
|
|
38
38
|
num_restarts_non_diagonal=None,
|
|
39
39
|
**kwargs,
|
|
40
40
|
):
|
|
41
|
+
"""Train Gaussian Process emulators for covariance matrices.
|
|
42
|
+
|
|
43
|
+
Trains one GP per covariance term. For square covariances (gg or vv), it
|
|
44
|
+
trains both a GP for the diagonal element (variance) and one for the
|
|
45
|
+
non-diagonal elements. For rectangular covariances (gv), only the
|
|
46
|
+
non-diagonal GP is trained.
|
|
47
|
+
|
|
48
|
+
Args:
|
|
49
|
+
square_covariance: Whether the covariance is square (gg or vv) or not (gv).
|
|
50
|
+
output_variance: Array of shape ``(n_terms, n_samples)`` containing diagonal values per sample. Ignored if not square.
|
|
51
|
+
output_non_diagonal: Array of shape ``(n_terms, n_samples, n_nd)`` containing flattened non-diagonal values per sample.
|
|
52
|
+
parameter_values: Array of shape ``(n_samples, n_params)`` with emulator input parameters.
|
|
53
|
+
kernel_variance: Optional GPy kernel to use for variance models. Defaults to ``Exponential + Poly`` if GPy is available.
|
|
54
|
+
kernel_non_diagonal: Optional GPy kernel to use for non-diagonal models. Defaults to ``Exponential + Poly`` if GPy is available.
|
|
55
|
+
verbose: If True, prints optimization messages.
|
|
56
|
+
num_restarts_variance: Optional number of optimizer restarts for variance GPs.
|
|
57
|
+
num_restarts_non_diagonal: Optional number of optimizer restarts for non-diagonal GPs.
|
|
58
|
+
**kwargs: Extra keyword arguments (unused).
|
|
59
|
+
|
|
60
|
+
Returns:
|
|
61
|
+
Tuple containing:
|
|
62
|
+
- ``gp_models_variance``: List of variance GP models or ``None``.
|
|
63
|
+
- ``gp_models_non_diagonal``: List of non-diagonal GP models.
|
|
64
|
+
- ``gp_evaluation_dictionary_variance``: Per-term evaluation dictionaries or ``None``.
|
|
65
|
+
- ``gp_evaluation_dictionary_non_diagonal``: Per-term evaluation dictionaries.
|
|
66
|
+
|
|
67
|
+
Raises:
|
|
68
|
+
ImportError: If GPy is not installed when training is requested.
|
|
69
|
+
"""
|
|
41
70
|
|
|
42
71
|
if square_covariance:
|
|
43
72
|
if kernel_variance is None:
|
|
@@ -91,5 +120,15 @@ def evaluate(
|
|
|
91
120
|
evaluation_value,
|
|
92
121
|
evaluation_dictionary,
|
|
93
122
|
):
|
|
123
|
+
"""Evaluate a trained GP model at given parameter values.
|
|
124
|
+
|
|
125
|
+
Args:
|
|
126
|
+
model: Trained GPy GPRegression model.
|
|
127
|
+
evaluation_value: Array of shape ``(1, n_params)`` with input parameters.
|
|
128
|
+
evaluation_dictionary: Placeholder for API consistency (unused for GPy).
|
|
129
|
+
|
|
130
|
+
Returns:
|
|
131
|
+
Tuple ``(mean, std)`` as returned by ``GPy.models.GPRegression.predict``.
|
|
132
|
+
"""
|
|
94
133
|
output = model.predict(evaluation_value)
|
|
95
134
|
return output
|
|
@@ -9,7 +9,7 @@ try:
|
|
|
9
9
|
|
|
10
10
|
torch_install = True
|
|
11
11
|
|
|
12
|
-
except:
|
|
12
|
+
except ImportError:
|
|
13
13
|
torch_install = False
|
|
14
14
|
log.add(
|
|
15
15
|
"Install pytorch to use the nnmatrix emulator",
|
|
@@ -36,6 +36,15 @@ class RegressionNet(default_regression_object):
|
|
|
36
36
|
output_dimension=1,
|
|
37
37
|
activation_function=default_activation_function,
|
|
38
38
|
):
|
|
39
|
+
"""Simple fully connected regression network.
|
|
40
|
+
|
|
41
|
+
Args:
|
|
42
|
+
input_dimension: Number of input features.
|
|
43
|
+
dimension_hidden_layers: Width of hidden layers.
|
|
44
|
+
number_hidden_layers: Number of hidden layers.
|
|
45
|
+
output_dimension: Number of output targets.
|
|
46
|
+
activation_function: Torch activation class to use.
|
|
47
|
+
"""
|
|
39
48
|
super().__init__()
|
|
40
49
|
layers = []
|
|
41
50
|
|
|
@@ -52,6 +61,7 @@ class RegressionNet(default_regression_object):
|
|
|
52
61
|
self.model = torch.nn.Sequential(*layers)
|
|
53
62
|
|
|
54
63
|
def forward(self, x):
|
|
64
|
+
"""Forward pass returning network output."""
|
|
55
65
|
return self.model(x)
|
|
56
66
|
|
|
57
67
|
|
|
@@ -65,6 +75,18 @@ def train_torch_model(
|
|
|
65
75
|
verbose,
|
|
66
76
|
model_name,
|
|
67
77
|
):
|
|
78
|
+
"""Train a torch model on normalized data.
|
|
79
|
+
|
|
80
|
+
Args:
|
|
81
|
+
number_epochs: Number of training epochs.
|
|
82
|
+
model: Torch model to train.
|
|
83
|
+
normalized_input: Normalized input array ``(n_samples, n_features)``.
|
|
84
|
+
normalized_output: Normalized target array ``(n_samples, n_targets)``.
|
|
85
|
+
optimizer: Torch optimizer instance.
|
|
86
|
+
loss_function: Torch loss function.
|
|
87
|
+
verbose: If True, logs periodic losses.
|
|
88
|
+
model_name: Label used in logging.
|
|
89
|
+
"""
|
|
68
90
|
normalized_input = torch.tensor(normalized_input, dtype=torch.float32)
|
|
69
91
|
normalized_output = torch.tensor(normalized_output, dtype=torch.float32)
|
|
70
92
|
for epoch in range(1, number_epochs + 1):
|
|
@@ -92,7 +114,31 @@ def train(
|
|
|
92
114
|
activation_function=default_activation_function,
|
|
93
115
|
loss_function=default_loss_function,
|
|
94
116
|
tolerance_optimizer=1e-3,
|
|
117
|
+
**kwargs,
|
|
95
118
|
):
|
|
119
|
+
"""Train neural network emulators for covariance matrices.
|
|
120
|
+
|
|
121
|
+
Normalizes inputs and outputs; trains separate nets per covariance term.
|
|
122
|
+
For square covariances (gg/vv) also trains a variance net.
|
|
123
|
+
|
|
124
|
+
Args:
|
|
125
|
+
square_covariance: Whether the covariance is square (gg/vv) or rectangular (gv).
|
|
126
|
+
output_variance: Array ``(n_terms, n_samples)`` diagonal entries; ignored if not square.
|
|
127
|
+
output_non_diagonal: Array ``(n_terms, n_samples, n_nd)`` flattened non-diagonals.
|
|
128
|
+
parameter_values: Array ``(n_samples, n_params)`` emulator inputs.
|
|
129
|
+
verbose: If True, prints training progress.
|
|
130
|
+
dimension_hidden_layers: Hidden layer width.
|
|
131
|
+
number_hidden_layers: Hidden layer count.
|
|
132
|
+
number_epochs: Epochs to train.
|
|
133
|
+
activation_function: Torch activation class.
|
|
134
|
+
loss_function: Torch loss function.
|
|
135
|
+
tolerance_optimizer: Learning rate for Adam optimizer.
|
|
136
|
+
**kwargs: Extra keyword arguments (unused).
|
|
137
|
+
|
|
138
|
+
Returns:
|
|
139
|
+
Tuple of lists/dicts: ``(nn_models_variance, nn_models_non_diagonal,
|
|
140
|
+
nn_evaluation_dictionary_variance, nn_evaluation_dictionary_non_diagonal)``.
|
|
141
|
+
"""
|
|
96
142
|
|
|
97
143
|
parameter_values_mean, parameter_values_std = (
|
|
98
144
|
parameter_values.mean(axis=0),
|
|
@@ -202,6 +248,16 @@ def evaluate(
|
|
|
202
248
|
evaluation_value,
|
|
203
249
|
evaluation_dictionary,
|
|
204
250
|
):
|
|
251
|
+
"""Evaluate a trained NN emulator, denormalizing output.
|
|
252
|
+
|
|
253
|
+
Args:
|
|
254
|
+
model: Trained torch model.
|
|
255
|
+
evaluation_value: Array ``(1, n_params)`` input values.
|
|
256
|
+
evaluation_dictionary: Dict with normalization stats (input_mean/std, output_mean/std).
|
|
257
|
+
|
|
258
|
+
Returns:
|
|
259
|
+
Tuple ``(output, None)`` where output is the denormalized numpy array.
|
|
260
|
+
"""
|
|
205
261
|
|
|
206
262
|
normalized_evaluation_value = (
|
|
207
263
|
evaluation_value - evaluation_dictionary["input_mean"]
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
|
|
3
|
+
from flip.utils import create_log
|
|
4
|
+
|
|
5
|
+
log = create_log()
|
|
6
|
+
|
|
7
|
+
try:
|
|
8
|
+
from sklearn.gaussian_process import GaussianProcessRegressor
|
|
9
|
+
from sklearn.gaussian_process.kernels import RBF, ConstantKernel
|
|
10
|
+
|
|
11
|
+
sklearngp_installed = True
|
|
12
|
+
|
|
13
|
+
except ImportError:
|
|
14
|
+
sklearngp_installed = False
|
|
15
|
+
log.add(
|
|
16
|
+
"Install scikit-learn to use the sklearnmatrix emulator",
|
|
17
|
+
level="warning",
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
_emulator_type = "matrix"
|
|
22
|
+
|
|
23
|
+
if sklearngp_installed:
|
|
24
|
+
default_kernel_variance = RBF(length_scale=1.0) + ConstantKernel(constant_value=1.0)
|
|
25
|
+
default_kernel_non_diagonal = RBF(length_scale=1.0) + ConstantKernel(
|
|
26
|
+
constant_value=1.0
|
|
27
|
+
)
|
|
28
|
+
else:
|
|
29
|
+
default_kernel_variance = None
|
|
30
|
+
default_kernel_non_diagonal = None
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def train(
|
|
34
|
+
square_covariance,
|
|
35
|
+
output_variance,
|
|
36
|
+
output_non_diagonal,
|
|
37
|
+
parameter_values,
|
|
38
|
+
kernel_variance=None,
|
|
39
|
+
kernel_non_diagonal=None,
|
|
40
|
+
num_restarts_variance=0,
|
|
41
|
+
num_restarts_non_diagonal=0,
|
|
42
|
+
**kwargs,
|
|
43
|
+
):
|
|
44
|
+
"""Train scikit-learn GP emulators for covariance matrices.
|
|
45
|
+
|
|
46
|
+
Args:
|
|
47
|
+
square_covariance: Whether covariance is square (gg/vv) or rectangular (gv).
|
|
48
|
+
output_variance: Array ``(n_terms, n_samples)`` of diagonal entries; ignored if not square.
|
|
49
|
+
output_non_diagonal: Array ``(n_terms, n_samples, n_nd)`` of flattened non-diagonals.
|
|
50
|
+
parameter_values: Array ``(n_samples, n_params)`` emulator inputs.
|
|
51
|
+
kernel_variance: Kernel for variance GP; defaults to ``RBF + Constant``.
|
|
52
|
+
kernel_non_diagonal: Kernel for non-diagonal GP; defaults to ``RBF + Constant``.
|
|
53
|
+
num_restarts_variance: Optimizer restarts for variance GP.
|
|
54
|
+
num_restarts_non_diagonal: Optimizer restarts for non-diagonal GP.
|
|
55
|
+
**kwargs: Extra keyword arguments (unused).
|
|
56
|
+
|
|
57
|
+
Returns:
|
|
58
|
+
Tuple of models and evaluation dictionaries analogous to other emulator backends.
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
if square_covariance:
|
|
62
|
+
if kernel_variance is None:
|
|
63
|
+
kernel_variance = default_kernel_variance
|
|
64
|
+
gp_models_variance = []
|
|
65
|
+
gp_evaluation_dictionary_variance = [None for j in range(len(output_variance))]
|
|
66
|
+
else:
|
|
67
|
+
gp_models_variance = None
|
|
68
|
+
gp_evaluation_dictionary_variance = None
|
|
69
|
+
if kernel_non_diagonal is None:
|
|
70
|
+
kernel_non_diagonal = default_kernel_non_diagonal
|
|
71
|
+
|
|
72
|
+
gp_models_non_diagonal = []
|
|
73
|
+
gp_evaluation_dictionary_non_diagonal = [
|
|
74
|
+
None for j in range(len(output_non_diagonal))
|
|
75
|
+
]
|
|
76
|
+
|
|
77
|
+
for j in range(len(output_non_diagonal)):
|
|
78
|
+
|
|
79
|
+
if square_covariance:
|
|
80
|
+
|
|
81
|
+
model_variance = GaussianProcessRegressor(
|
|
82
|
+
kernel=kernel_variance,
|
|
83
|
+
n_restarts_optimizer=num_restarts_variance,
|
|
84
|
+
)
|
|
85
|
+
model_variance.fit(
|
|
86
|
+
parameter_values,
|
|
87
|
+
output_variance[j][:, np.newaxis],
|
|
88
|
+
)
|
|
89
|
+
gp_models_variance.append(model_variance)
|
|
90
|
+
|
|
91
|
+
model_non_diagonal = GaussianProcessRegressor(
|
|
92
|
+
kernel=kernel_non_diagonal,
|
|
93
|
+
n_restarts_optimizer=num_restarts_non_diagonal,
|
|
94
|
+
)
|
|
95
|
+
model_non_diagonal.fit(
|
|
96
|
+
parameter_values,
|
|
97
|
+
output_non_diagonal[j],
|
|
98
|
+
)
|
|
99
|
+
gp_models_non_diagonal.append(model_non_diagonal)
|
|
100
|
+
|
|
101
|
+
return (
|
|
102
|
+
gp_models_variance,
|
|
103
|
+
gp_models_non_diagonal,
|
|
104
|
+
gp_evaluation_dictionary_variance,
|
|
105
|
+
gp_evaluation_dictionary_non_diagonal,
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def evaluate(
|
|
110
|
+
model,
|
|
111
|
+
evaluation_value,
|
|
112
|
+
evaluation_dictionary,
|
|
113
|
+
):
|
|
114
|
+
"""Evaluate a scikit-learn GP model.
|
|
115
|
+
|
|
116
|
+
Args:
|
|
117
|
+
model: Trained ``GaussianProcessRegressor``.
|
|
118
|
+
evaluation_value: Array ``(1, n_params)`` input values.
|
|
119
|
+
evaluation_dictionary: Placeholder for API consistency (unused).
|
|
120
|
+
|
|
121
|
+
Returns:
|
|
122
|
+
Tuple ``(mean, std)`` from ``GaussianProcessRegressor.predict``.
|
|
123
|
+
"""
|
|
124
|
+
output = model.predict(evaluation_value, return_std=True)
|
|
125
|
+
return output
|