multimodalsrm 0.1.0__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.
- multimodalsrm/__init__.py +58 -0
- multimodalsrm/_observation_preparation.py +338 -0
- multimodalsrm/_parallel.py +74 -0
- multimodalsrm/_version.py +3 -0
- multimodalsrm/alignment.py +261 -0
- multimodalsrm/bayesian/__init__.py +24 -0
- multimodalsrm/bayesian/_archive.py +255 -0
- multimodalsrm/bayesian/_backend.py +92 -0
- multimodalsrm/bayesian/baselines.py +97 -0
- multimodalsrm/bayesian/blocks.py +100 -0
- multimodalsrm/bayesian/calibration.py +284 -0
- multimodalsrm/bayesian/calibration_archive.py +70 -0
- multimodalsrm/bayesian/calibration_problem.py +52 -0
- multimodalsrm/bayesian/covariance_pairs.py +47 -0
- multimodalsrm/bayesian/diagnostics.py +243 -0
- multimodalsrm/bayesian/execution.py +37 -0
- multimodalsrm/bayesian/factorization.py +107 -0
- multimodalsrm/bayesian/fitting.py +810 -0
- multimodalsrm/bayesian/gp_hyperparameters.py +51 -0
- multimodalsrm/bayesian/grouped.py +105 -0
- multimodalsrm/bayesian/grouped_score.py +42 -0
- multimodalsrm/bayesian/identity.py +25 -0
- multimodalsrm/bayesian/map_conditioning.py +237 -0
- multimodalsrm/bayesian/map_parallel.py +56 -0
- multimodalsrm/bayesian/model.py +951 -0
- multimodalsrm/bayesian/multifactor.py +117 -0
- multimodalsrm/bayesian/multifactor_cholesky.py +85 -0
- multimodalsrm/bayesian/multifactor_score.py +49 -0
- multimodalsrm/bayesian/noise_profile.py +287 -0
- multimodalsrm/bayesian/observation_adapter.py +12 -0
- multimodalsrm/bayesian/orientation_diagnostics.py +268 -0
- multimodalsrm/bayesian/orientation_persistence.py +186 -0
- multimodalsrm/bayesian/orthogonal.py +217 -0
- multimodalsrm/bayesian/persistence.py +412 -0
- multimodalsrm/bayesian/polishing.py +295 -0
- multimodalsrm/bayesian/posterior_coordinates.py +36 -0
- multimodalsrm/bayesian/posterior_participants.py +118 -0
- multimodalsrm/bayesian/posterior_persistence.py +573 -0
- multimodalsrm/bayesian/posterior_updates.py +499 -0
- multimodalsrm/bayesian/prediction.py +380 -0
- multimodalsrm/bayesian/priors.py +135 -0
- multimodalsrm/bayesian/problem.py +470 -0
- multimodalsrm/bayesian/quality.py +251 -0
- multimodalsrm/bayesian/reference.py +94 -0
- multimodalsrm/bayesian/refinement_coordinates.py +59 -0
- multimodalsrm/bayesian/response_quadrature.py +243 -0
- multimodalsrm/bayesian/response_scope.py +57 -0
- multimodalsrm/bayesian/results.py +144 -0
- multimodalsrm/bayesian/spectral.py +194 -0
- multimodalsrm/bayesian/state_space.py +354 -0
- multimodalsrm/bayesian/state_space_bach.py +172 -0
- multimodalsrm/bayesian/state_space_compact.py +329 -0
- multimodalsrm/bayesian/state_space_delays.py +124 -0
- multimodalsrm/bayesian/state_space_gaussian.py +172 -0
- multimodalsrm/bayesian/state_space_gaussian_rational.py +195 -0
- multimodalsrm/bayesian/state_space_parameters.py +411 -0
- multimodalsrm/bayesian/state_space_rational.py +177 -0
- multimodalsrm/bayesian/state_space_responses.py +267 -0
- multimodalsrm/bayesian/temporal_noise.py +192 -0
- multimodalsrm/bayesian/timing.py +30 -0
- multimodalsrm/bayesian/trajectories.py +177 -0
- multimodalsrm/bayesian/transform.py +199 -0
- multimodalsrm/bayesian/updated_posterior_persistence.py +95 -0
- multimodalsrm/bayesian/warmup_checkpoint.py +190 -0
- multimodalsrm/bayesian/workflow.py +270 -0
- multimodalsrm/calibration.py +380 -0
- multimodalsrm/data.py +84 -0
- multimodalsrm/estimator.py +617 -0
- multimodalsrm/grouping.py +33 -0
- multimodalsrm/inference.py +298 -0
- multimodalsrm/initialization.py +77 -0
- multimodalsrm/inspection.py +167 -0
- multimodalsrm/kernel_optimization.py +316 -0
- multimodalsrm/kernels.py +485 -0
- multimodalsrm/objective.py +437 -0
- multimodalsrm/operators.py +181 -0
- multimodalsrm/optimization.py +348 -0
- multimodalsrm/posterior_results.py +29 -0
- multimodalsrm/results.py +33 -0
- multimodalsrm/selection.py +574 -0
- multimodalsrm/validation.py +258 -0
- multimodalsrm-0.1.0.dist-info/METADATA +128 -0
- multimodalsrm-0.1.0.dist-info/RECORD +86 -0
- multimodalsrm-0.1.0.dist-info/WHEEL +5 -0
- multimodalsrm-0.1.0.dist-info/licenses/LICENSE +21 -0
- multimodalsrm-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""Native-time shared response models for multimodal observations."""
|
|
2
|
+
|
|
3
|
+
from ._version import __version__
|
|
4
|
+
from .alignment import temporal_isc, time_segment_matching
|
|
5
|
+
from .data import TimeSeries
|
|
6
|
+
from .estimator import MultimodalSRM
|
|
7
|
+
from .inspection import KernelEstimate
|
|
8
|
+
from .kernels import (
|
|
9
|
+
BachSCR,
|
|
10
|
+
DoubleGamma,
|
|
11
|
+
Gamma,
|
|
12
|
+
Gaussian,
|
|
13
|
+
Identity,
|
|
14
|
+
KernelPrior,
|
|
15
|
+
Normal,
|
|
16
|
+
Response,
|
|
17
|
+
SampledKernel,
|
|
18
|
+
)
|
|
19
|
+
from .posterior_results import PosteriorSeriesResult
|
|
20
|
+
from .results import SeriesResult
|
|
21
|
+
from .selection import (
|
|
22
|
+
ModelComparisonResult,
|
|
23
|
+
ModelSelectionResult,
|
|
24
|
+
NestedCrossValidationResult,
|
|
25
|
+
compare_models,
|
|
26
|
+
nested_cross_validate,
|
|
27
|
+
select_model,
|
|
28
|
+
)
|
|
29
|
+
from .validation import CrossValidationResult, LeaveOneRunOut, cross_validate
|
|
30
|
+
|
|
31
|
+
__all__ = [
|
|
32
|
+
"__version__",
|
|
33
|
+
"TimeSeries",
|
|
34
|
+
"temporal_isc",
|
|
35
|
+
"time_segment_matching",
|
|
36
|
+
"Identity",
|
|
37
|
+
"Gaussian",
|
|
38
|
+
"Gamma",
|
|
39
|
+
"DoubleGamma",
|
|
40
|
+
"BachSCR",
|
|
41
|
+
"SampledKernel",
|
|
42
|
+
"Response",
|
|
43
|
+
"Normal",
|
|
44
|
+
"KernelPrior",
|
|
45
|
+
"SeriesResult",
|
|
46
|
+
"PosteriorSeriesResult",
|
|
47
|
+
"MultimodalSRM",
|
|
48
|
+
"KernelEstimate",
|
|
49
|
+
"LeaveOneRunOut",
|
|
50
|
+
"cross_validate",
|
|
51
|
+
"CrossValidationResult",
|
|
52
|
+
"compare_models",
|
|
53
|
+
"select_model",
|
|
54
|
+
"nested_cross_validate",
|
|
55
|
+
"ModelComparisonResult",
|
|
56
|
+
"ModelSelectionResult",
|
|
57
|
+
"NestedCrossValidationResult",
|
|
58
|
+
]
|
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
"""Estimator-independent validation, fixed support and native data preparation.
|
|
2
|
+
|
|
3
|
+
These internal helpers contain no fitting, covariance or inference backend.
|
|
4
|
+
The reference estimators and Bayesian adapter share the same preparation rules;
|
|
5
|
+
configuration metadata is retained for compatibility with existing consumers.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import copy
|
|
9
|
+
from collections.abc import Mapping
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
|
|
12
|
+
import numpy as np
|
|
13
|
+
from sklearn.base import BaseEstimator
|
|
14
|
+
|
|
15
|
+
from .data import normalize_data
|
|
16
|
+
from .kernels import DoubleGamma, Gaussian, Identity, Response
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass
|
|
20
|
+
class NativeBlock:
|
|
21
|
+
subject: object
|
|
22
|
+
run: object
|
|
23
|
+
modality: object
|
|
24
|
+
times: np.ndarray
|
|
25
|
+
values: np.ndarray
|
|
26
|
+
mask: np.ndarray
|
|
27
|
+
valid: np.ndarray
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass
|
|
31
|
+
class ObservationSystem:
|
|
32
|
+
times: np.ndarray
|
|
33
|
+
keys: list
|
|
34
|
+
values: np.ndarray
|
|
35
|
+
|
|
36
|
+
def rows(self, loadings):
|
|
37
|
+
return np.array([loadings[s][m][f] for s, m, f in self.keys])
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class ObservationPreparation(BaseEstimator):
|
|
41
|
+
"""Common options, response validation and support-eligible preprocessing."""
|
|
42
|
+
|
|
43
|
+
def __init__(
|
|
44
|
+
self,
|
|
45
|
+
features=3,
|
|
46
|
+
*,
|
|
47
|
+
latent_dt,
|
|
48
|
+
responses=None,
|
|
49
|
+
length_scale=3.0,
|
|
50
|
+
learn_length_scale=False,
|
|
51
|
+
length_scale_bounds=(0.2, 30.0),
|
|
52
|
+
noise_variance=0.1,
|
|
53
|
+
learn_noise=True,
|
|
54
|
+
noise_bounds=(1e-5, 10.0),
|
|
55
|
+
loading_ridge=1e-3,
|
|
56
|
+
max_iter=100,
|
|
57
|
+
tol=1e-6,
|
|
58
|
+
n_init=3,
|
|
59
|
+
random_state=None,
|
|
60
|
+
standardize=True,
|
|
61
|
+
max_latent_size=1500,
|
|
62
|
+
):
|
|
63
|
+
self.features = features
|
|
64
|
+
self.latent_dt = latent_dt
|
|
65
|
+
self.responses = responses
|
|
66
|
+
self.length_scale = length_scale
|
|
67
|
+
self.learn_length_scale = learn_length_scale
|
|
68
|
+
self.length_scale_bounds = length_scale_bounds
|
|
69
|
+
self.noise_variance = noise_variance
|
|
70
|
+
self.learn_noise = learn_noise
|
|
71
|
+
self.noise_bounds = noise_bounds
|
|
72
|
+
self.loading_ridge = loading_ridge
|
|
73
|
+
self.max_iter = max_iter
|
|
74
|
+
self.tol = tol
|
|
75
|
+
self.n_init = n_init
|
|
76
|
+
self.random_state = random_state
|
|
77
|
+
self.standardize = standardize
|
|
78
|
+
self.max_latent_size = max_latent_size
|
|
79
|
+
|
|
80
|
+
def _validate(self, data):
|
|
81
|
+
for name in ("features", "max_iter", "n_init", "max_latent_size"):
|
|
82
|
+
value = getattr(self, name)
|
|
83
|
+
if (
|
|
84
|
+
isinstance(value, (bool, np.bool_))
|
|
85
|
+
or not isinstance(value, (int, np.integer))
|
|
86
|
+
or value < 1
|
|
87
|
+
):
|
|
88
|
+
raise ValueError(f"{name} must be a positive integer")
|
|
89
|
+
for name in ("latent_dt", "length_scale", "noise_variance", "tol"):
|
|
90
|
+
value = getattr(self, name)
|
|
91
|
+
if not np.isscalar(value) or not np.isfinite(value) or value <= 0:
|
|
92
|
+
raise ValueError(f"{name} must be positive finite")
|
|
93
|
+
if not np.isfinite(self.loading_ridge) or self.loading_ridge < 0:
|
|
94
|
+
raise ValueError("loading_ridge must be nonnegative finite")
|
|
95
|
+
for name in ("learn_noise", "learn_length_scale", "standardize"):
|
|
96
|
+
if not isinstance(getattr(self, name), (bool, np.bool_)):
|
|
97
|
+
raise ValueError(f"{name} must be Boolean")
|
|
98
|
+
for name, initial, active in (
|
|
99
|
+
("noise_bounds", self.noise_variance, self.learn_noise),
|
|
100
|
+
("length_scale_bounds", self.length_scale, self.learn_length_scale),
|
|
101
|
+
):
|
|
102
|
+
bounds = np.asarray(getattr(self, name), float)
|
|
103
|
+
if (
|
|
104
|
+
bounds.shape != (2,)
|
|
105
|
+
or not np.isfinite(bounds).all()
|
|
106
|
+
or not 0 < bounds[0] < bounds[1]
|
|
107
|
+
):
|
|
108
|
+
raise ValueError(f"{name} must be two increasing positive finite bounds")
|
|
109
|
+
if active and not bounds[0] <= initial <= bounds[1]:
|
|
110
|
+
raise ValueError(f"initial value lies outside {name}")
|
|
111
|
+
self.subjects_ = list(data)
|
|
112
|
+
self.modalities_ = list(
|
|
113
|
+
dict.fromkeys(m for runs in data.values() for mods in runs.values() for m in mods)
|
|
114
|
+
)
|
|
115
|
+
if self.responses is not None and not isinstance(self.responses, Mapping):
|
|
116
|
+
raise ValueError("responses must map modality names to Response objects")
|
|
117
|
+
supplied = self.responses or {}
|
|
118
|
+
if not set(supplied) <= set(self.modalities_):
|
|
119
|
+
raise ValueError("responses contain unobserved modalities")
|
|
120
|
+
self.responses_ = {
|
|
121
|
+
m: copy.deepcopy(
|
|
122
|
+
supplied.get(m, Response(Identity(), pooling="shared", estimate=False))
|
|
123
|
+
)
|
|
124
|
+
for m in self.modalities_
|
|
125
|
+
}
|
|
126
|
+
for response in self.responses_.values():
|
|
127
|
+
if not isinstance(response, Response) or response.pooling != "shared":
|
|
128
|
+
raise ValueError("ProbabilisticMultimodalSRM requires Response(pooling='shared')")
|
|
129
|
+
kernel = response.initial_kernel()
|
|
130
|
+
if isinstance(kernel, DoubleGamma):
|
|
131
|
+
bounds = response.parameter_bounds()
|
|
132
|
+
extremes = {
|
|
133
|
+
p: bounds[p] if p in response.free_parameters else (v, v)
|
|
134
|
+
for p, v in kernel.parameters.items()
|
|
135
|
+
}
|
|
136
|
+
peak_max = extremes["peak_shape"][1] * extremes["peak_scale"][1]
|
|
137
|
+
undershoot_min = extremes["undershoot_shape"][0] * extremes["undershoot_scale"][0]
|
|
138
|
+
if peak_max >= undershoot_min:
|
|
139
|
+
raise ValueError(
|
|
140
|
+
"DoubleGamma bounds must preserve peak/undershoot mean ordering throughout the parameter box; narrow bounds or use Response.lag_only(..., pooling='shared')"
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
def _support(self, times, modality, domain):
|
|
144
|
+
lo, hi = self.responses_[modality].support_envelope()
|
|
145
|
+
a, b = domain
|
|
146
|
+
tolerance = 1e-10 * max(1.0, abs(a), abs(b))
|
|
147
|
+
return (
|
|
148
|
+
(times >= a - tolerance)
|
|
149
|
+
& (times <= b + tolerance)
|
|
150
|
+
& (times - hi >= a - tolerance)
|
|
151
|
+
& (times - lo <= b + tolerance)
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
def _prepare(self, data):
|
|
155
|
+
data = normalize_data(data)
|
|
156
|
+
self._validate(data)
|
|
157
|
+
self.grids_, self.domains_ = self._grids(data)
|
|
158
|
+
# Learn preprocessing only from entries eligible for the fixed envelope.
|
|
159
|
+
self.preprocessing_ = {}
|
|
160
|
+
for s, runs in data.items():
|
|
161
|
+
self.preprocessing_[s] = {}
|
|
162
|
+
for m in dict.fromkeys(m for mods in runs.values() for m in mods):
|
|
163
|
+
series = [(r, mods[m]) for r, mods in runs.items() if m in mods]
|
|
164
|
+
values = np.concatenate([ts.values for _, ts in series])
|
|
165
|
+
mask = np.concatenate(
|
|
166
|
+
[
|
|
167
|
+
ts.mask & self._support(ts.times, m, self.domains_[r])[:, None]
|
|
168
|
+
for r, ts in series
|
|
169
|
+
]
|
|
170
|
+
)
|
|
171
|
+
count = mask.sum(axis=0)
|
|
172
|
+
if np.any(count == 0):
|
|
173
|
+
raise ValueError(f"no support-eligible observations for a feature of {s}/{m}")
|
|
174
|
+
mean = np.where(mask, values, 0).sum(axis=0) / count
|
|
175
|
+
scale = np.sqrt(np.where(mask, (values - mean) ** 2, 0).sum(axis=0) / count)
|
|
176
|
+
constant = scale <= np.finfo(float).eps
|
|
177
|
+
scale[constant] = 1.0
|
|
178
|
+
if not self.standardize:
|
|
179
|
+
mean, scale = np.zeros_like(mean), np.ones_like(scale)
|
|
180
|
+
self.preprocessing_[s][m] = dict(mean=mean, scale=scale, constant_features=constant)
|
|
181
|
+
self._training_data = data
|
|
182
|
+
self.configuration_ = dict(
|
|
183
|
+
likelihood="independent_gaussian_observations",
|
|
184
|
+
noise_units="preprocessed_variance",
|
|
185
|
+
latent_prior="unit_variance_independent_matern32_factors",
|
|
186
|
+
approximation="GP_on_grid_with_piecewise_linear_convolution",
|
|
187
|
+
uncertainty="conditional_on_fitted_parameters",
|
|
188
|
+
latent_pooling="shared",
|
|
189
|
+
kernel_pooling="shared",
|
|
190
|
+
objective="negative_marginal_log_likelihood_plus_parameter_penalties",
|
|
191
|
+
prior_jitter=1e-8,
|
|
192
|
+
latent_dt=self.latent_dt,
|
|
193
|
+
mean="jointly_fitted_unpenalized_offsets_in_preprocessed_units",
|
|
194
|
+
restart_selection="minimum_finite_training_objective",
|
|
195
|
+
response_metadata={m: r.metadata for m, r in self.responses_.items()},
|
|
196
|
+
timing="relative unless independently anchored; fixed priors do not establish identification",
|
|
197
|
+
)
|
|
198
|
+
return data
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
class NativeObservationPreparation(ObservationPreparation):
|
|
202
|
+
"""Prepare observation-space systems without choosing an inference backend."""
|
|
203
|
+
|
|
204
|
+
def __init__(
|
|
205
|
+
self,
|
|
206
|
+
features=3,
|
|
207
|
+
*,
|
|
208
|
+
latent_dt,
|
|
209
|
+
responses=None,
|
|
210
|
+
length_scale=3.0,
|
|
211
|
+
learn_length_scale=False,
|
|
212
|
+
length_scale_bounds=(0.2, 30.0),
|
|
213
|
+
noise_variance=0.1,
|
|
214
|
+
learn_noise=True,
|
|
215
|
+
noise_bounds=(1e-5, 10.0),
|
|
216
|
+
loading_ridge=1e-3,
|
|
217
|
+
max_iter=100,
|
|
218
|
+
tol=1e-6,
|
|
219
|
+
n_init=3,
|
|
220
|
+
random_state=None,
|
|
221
|
+
standardize=True,
|
|
222
|
+
max_latent_size=1500,
|
|
223
|
+
covariance_tolerance=1e-7,
|
|
224
|
+
max_observations=800,
|
|
225
|
+
maxcor=100,
|
|
226
|
+
gradient_tolerance=1e-5,
|
|
227
|
+
):
|
|
228
|
+
super().__init__(
|
|
229
|
+
features,
|
|
230
|
+
latent_dt=latent_dt,
|
|
231
|
+
responses=responses,
|
|
232
|
+
length_scale=length_scale,
|
|
233
|
+
learn_length_scale=learn_length_scale,
|
|
234
|
+
length_scale_bounds=length_scale_bounds,
|
|
235
|
+
noise_variance=noise_variance,
|
|
236
|
+
learn_noise=learn_noise,
|
|
237
|
+
noise_bounds=noise_bounds,
|
|
238
|
+
loading_ridge=loading_ridge,
|
|
239
|
+
max_iter=max_iter,
|
|
240
|
+
tol=tol,
|
|
241
|
+
n_init=n_init,
|
|
242
|
+
random_state=random_state,
|
|
243
|
+
standardize=standardize,
|
|
244
|
+
max_latent_size=max_latent_size,
|
|
245
|
+
)
|
|
246
|
+
self.covariance_tolerance = covariance_tolerance
|
|
247
|
+
self.max_observations = max_observations
|
|
248
|
+
self.maxcor = maxcor
|
|
249
|
+
self.gradient_tolerance = gradient_tolerance
|
|
250
|
+
|
|
251
|
+
def _validate(self, data):
|
|
252
|
+
super()._validate(data)
|
|
253
|
+
for m, kernel in getattr(self, "_known_kernels", {}).items():
|
|
254
|
+
if m in self.responses_ and m not in (self.responses or {}):
|
|
255
|
+
self.responses_[m] = Response(kernel, pooling="shared", estimate=False)
|
|
256
|
+
if self.learn_length_scale:
|
|
257
|
+
raise ValueError("learn_length_scale is unsupported by the continuous reference")
|
|
258
|
+
for name in ("max_observations", "maxcor"):
|
|
259
|
+
value = getattr(self, name)
|
|
260
|
+
if (
|
|
261
|
+
isinstance(value, (bool, np.bool_))
|
|
262
|
+
or not isinstance(value, (int, np.integer))
|
|
263
|
+
or value < 1
|
|
264
|
+
):
|
|
265
|
+
raise ValueError(f"{name} must be a positive integer")
|
|
266
|
+
for name in ("covariance_tolerance", "gradient_tolerance"):
|
|
267
|
+
value = getattr(self, name)
|
|
268
|
+
if not np.isscalar(value) or not np.isfinite(value) or value <= 0:
|
|
269
|
+
raise ValueError(f"{name} must be positive finite")
|
|
270
|
+
for response in self.responses_.values():
|
|
271
|
+
if type(response.initial_kernel()) not in getattr(
|
|
272
|
+
self, "_response_types", (Identity, Gaussian)
|
|
273
|
+
):
|
|
274
|
+
raise ValueError(
|
|
275
|
+
"continuous reference supports only Identity and Gaussian responses"
|
|
276
|
+
)
|
|
277
|
+
|
|
278
|
+
def _grids(self, data):
|
|
279
|
+
# Native unions are safe bookkeeping, not GP discretization.
|
|
280
|
+
times = {}
|
|
281
|
+
for runs in data.values():
|
|
282
|
+
for r, mods in runs.items():
|
|
283
|
+
for ts in mods.values():
|
|
284
|
+
times.setdefault(r, []).append(ts.times[ts.mask.any(axis=1)])
|
|
285
|
+
grids = {r: np.unique(np.concatenate(t)) for r, t in times.items()}
|
|
286
|
+
domains = {r: (t[0], t[-1]) for r, t in grids.items()}
|
|
287
|
+
if any(b <= a for a, b in domains.values()):
|
|
288
|
+
raise ValueError("each run requires positive observed duration")
|
|
289
|
+
return grids, domains
|
|
290
|
+
|
|
291
|
+
def _prepare(self, data):
|
|
292
|
+
result = super()._prepare(data)
|
|
293
|
+
self.configuration_.update(
|
|
294
|
+
approximation="continuous_response_covariance",
|
|
295
|
+
prior_jitter=0.0,
|
|
296
|
+
covariance_tolerance=self.covariance_tolerance,
|
|
297
|
+
max_observations=self.max_observations,
|
|
298
|
+
uncertainty="conditional_on_parameters",
|
|
299
|
+
)
|
|
300
|
+
self._systems(result, self.domains_) # Guard before initialization or covariance.
|
|
301
|
+
return result
|
|
302
|
+
|
|
303
|
+
def _systems(self, data, domains):
|
|
304
|
+
blocks = []
|
|
305
|
+
parts = {r: [] for r in domains}
|
|
306
|
+
counts = {r: 0 for r in domains}
|
|
307
|
+
for s, runs in data.items():
|
|
308
|
+
for r, mods in runs.items():
|
|
309
|
+
for m, ts in mods.items():
|
|
310
|
+
if m not in self.preprocessing_.get(s, {}):
|
|
311
|
+
raise ValueError(f"conditioning mapping {s}/{m} unavailable")
|
|
312
|
+
stats = self.preprocessing_[s][m]
|
|
313
|
+
if ts.values.shape[1] != len(stats["mean"]):
|
|
314
|
+
raise ValueError(f"feature count differs from fitted mapping for {s}/{m}")
|
|
315
|
+
valid = self._support(ts.times, m, domains[r]) & ts.mask.any(axis=1)
|
|
316
|
+
values = (ts.values - stats["mean"]) / stats["scale"]
|
|
317
|
+
block = NativeBlock(s, r, m, ts.times, values, ts.mask, valid)
|
|
318
|
+
blocks.append(block)
|
|
319
|
+
for f in range(values.shape[1]):
|
|
320
|
+
rows = valid & ts.mask[:, f]
|
|
321
|
+
count = int(rows.sum())
|
|
322
|
+
counts[r] += count
|
|
323
|
+
if counts[r] > self.max_observations:
|
|
324
|
+
raise ValueError(
|
|
325
|
+
f"run {r} exceeds max_observations={self.max_observations}"
|
|
326
|
+
)
|
|
327
|
+
if count:
|
|
328
|
+
parts[r].append((ts.times[rows], [(s, m, f)] * count, values[rows, f]))
|
|
329
|
+
systems = {}
|
|
330
|
+
for r, chunks in parts.items():
|
|
331
|
+
if not chunks:
|
|
332
|
+
raise ValueError(f"run {r} has no support-eligible conditioning observations")
|
|
333
|
+
systems[r] = ObservationSystem(
|
|
334
|
+
np.concatenate([c[0] for c in chunks]),
|
|
335
|
+
[key for c in chunks for key in c[1]],
|
|
336
|
+
np.concatenate([c[2] for c in chunks]),
|
|
337
|
+
)
|
|
338
|
+
return systems, blocks
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Ordered process tasks with one active level of parallelism."""
|
|
2
|
+
|
|
3
|
+
import sys
|
|
4
|
+
import warnings
|
|
5
|
+
from contextvars import ContextVar
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
from joblib import Parallel, cpu_count, delayed, parallel_config
|
|
9
|
+
|
|
10
|
+
_worker = ContextVar("multimodal_parallel_worker", default=False)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def worker_count(n_jobs, tasks):
|
|
14
|
+
if (
|
|
15
|
+
isinstance(n_jobs, (bool, np.bool_))
|
|
16
|
+
or not isinstance(n_jobs, (int, np.integer))
|
|
17
|
+
or (n_jobs != -1 and n_jobs < 1)
|
|
18
|
+
):
|
|
19
|
+
raise ValueError("n_jobs must be a positive integer or -1")
|
|
20
|
+
if _worker.get():
|
|
21
|
+
return 1
|
|
22
|
+
return max(1, min(cpu_count() if n_jobs == -1 else int(n_jobs), tasks))
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _run_worker(function, arguments, warning_filters):
|
|
26
|
+
token = _worker.set(True)
|
|
27
|
+
try:
|
|
28
|
+
with warnings.catch_warnings(record=True) as caught:
|
|
29
|
+
# catch_warnings invalidates warning registries on entry. Install
|
|
30
|
+
# the caller's filters before any task code can issue a warning.
|
|
31
|
+
warnings.filters[:] = warning_filters
|
|
32
|
+
result = function(*arguments)
|
|
33
|
+
modules = {
|
|
34
|
+
getattr(module, "__file__", None): name for name, module in list(sys.modules.items())
|
|
35
|
+
}
|
|
36
|
+
return result, [
|
|
37
|
+
(w.message, w.category, w.filename, w.lineno, modules.get(w.filename)) for w in caught
|
|
38
|
+
]
|
|
39
|
+
finally:
|
|
40
|
+
_worker.reset(token)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def ordered_tasks(function, arguments, n_jobs):
|
|
44
|
+
"""Run tasks in isolated processes; preserve input order and failures.
|
|
45
|
+
|
|
46
|
+
Inside our workers, downstream fold/restart requests run serially. Loky's
|
|
47
|
+
inner thread limit covers OMP, OpenBLAS, MKL and Accelerate environment
|
|
48
|
+
settings, without changing the parent process environment.
|
|
49
|
+
"""
|
|
50
|
+
arguments = list(arguments)
|
|
51
|
+
workers = worker_count(n_jobs, len(arguments))
|
|
52
|
+
if workers == 1:
|
|
53
|
+
return [function(*args) for args in arguments]
|
|
54
|
+
with parallel_config(backend="loky", inner_max_num_threads=1):
|
|
55
|
+
completed = Parallel(
|
|
56
|
+
n_jobs=workers,
|
|
57
|
+
pre_dispatch=workers,
|
|
58
|
+
batch_size=1,
|
|
59
|
+
max_nbytes="1M",
|
|
60
|
+
mmap_mode="r",
|
|
61
|
+
)(delayed(_run_worker)(function, args, list(warnings.filters)) for args in arguments)
|
|
62
|
+
results = []
|
|
63
|
+
for result, caught in completed:
|
|
64
|
+
for message, category, filename, lineno, module in caught:
|
|
65
|
+
kwargs = {}
|
|
66
|
+
if module is not None:
|
|
67
|
+
kwargs["module"] = module
|
|
68
|
+
if module in sys.modules:
|
|
69
|
+
kwargs["registry"] = vars(sys.modules[module]).setdefault(
|
|
70
|
+
"__warningregistry__", {}
|
|
71
|
+
)
|
|
72
|
+
warnings.warn_explicit(message, category, filename, lineno, **kwargs)
|
|
73
|
+
results.append(result)
|
|
74
|
+
return results
|