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.
Files changed (86) hide show
  1. multimodalsrm/__init__.py +58 -0
  2. multimodalsrm/_observation_preparation.py +338 -0
  3. multimodalsrm/_parallel.py +74 -0
  4. multimodalsrm/_version.py +3 -0
  5. multimodalsrm/alignment.py +261 -0
  6. multimodalsrm/bayesian/__init__.py +24 -0
  7. multimodalsrm/bayesian/_archive.py +255 -0
  8. multimodalsrm/bayesian/_backend.py +92 -0
  9. multimodalsrm/bayesian/baselines.py +97 -0
  10. multimodalsrm/bayesian/blocks.py +100 -0
  11. multimodalsrm/bayesian/calibration.py +284 -0
  12. multimodalsrm/bayesian/calibration_archive.py +70 -0
  13. multimodalsrm/bayesian/calibration_problem.py +52 -0
  14. multimodalsrm/bayesian/covariance_pairs.py +47 -0
  15. multimodalsrm/bayesian/diagnostics.py +243 -0
  16. multimodalsrm/bayesian/execution.py +37 -0
  17. multimodalsrm/bayesian/factorization.py +107 -0
  18. multimodalsrm/bayesian/fitting.py +810 -0
  19. multimodalsrm/bayesian/gp_hyperparameters.py +51 -0
  20. multimodalsrm/bayesian/grouped.py +105 -0
  21. multimodalsrm/bayesian/grouped_score.py +42 -0
  22. multimodalsrm/bayesian/identity.py +25 -0
  23. multimodalsrm/bayesian/map_conditioning.py +237 -0
  24. multimodalsrm/bayesian/map_parallel.py +56 -0
  25. multimodalsrm/bayesian/model.py +951 -0
  26. multimodalsrm/bayesian/multifactor.py +117 -0
  27. multimodalsrm/bayesian/multifactor_cholesky.py +85 -0
  28. multimodalsrm/bayesian/multifactor_score.py +49 -0
  29. multimodalsrm/bayesian/noise_profile.py +287 -0
  30. multimodalsrm/bayesian/observation_adapter.py +12 -0
  31. multimodalsrm/bayesian/orientation_diagnostics.py +268 -0
  32. multimodalsrm/bayesian/orientation_persistence.py +186 -0
  33. multimodalsrm/bayesian/orthogonal.py +217 -0
  34. multimodalsrm/bayesian/persistence.py +412 -0
  35. multimodalsrm/bayesian/polishing.py +295 -0
  36. multimodalsrm/bayesian/posterior_coordinates.py +36 -0
  37. multimodalsrm/bayesian/posterior_participants.py +118 -0
  38. multimodalsrm/bayesian/posterior_persistence.py +573 -0
  39. multimodalsrm/bayesian/posterior_updates.py +499 -0
  40. multimodalsrm/bayesian/prediction.py +380 -0
  41. multimodalsrm/bayesian/priors.py +135 -0
  42. multimodalsrm/bayesian/problem.py +470 -0
  43. multimodalsrm/bayesian/quality.py +251 -0
  44. multimodalsrm/bayesian/reference.py +94 -0
  45. multimodalsrm/bayesian/refinement_coordinates.py +59 -0
  46. multimodalsrm/bayesian/response_quadrature.py +243 -0
  47. multimodalsrm/bayesian/response_scope.py +57 -0
  48. multimodalsrm/bayesian/results.py +144 -0
  49. multimodalsrm/bayesian/spectral.py +194 -0
  50. multimodalsrm/bayesian/state_space.py +354 -0
  51. multimodalsrm/bayesian/state_space_bach.py +172 -0
  52. multimodalsrm/bayesian/state_space_compact.py +329 -0
  53. multimodalsrm/bayesian/state_space_delays.py +124 -0
  54. multimodalsrm/bayesian/state_space_gaussian.py +172 -0
  55. multimodalsrm/bayesian/state_space_gaussian_rational.py +195 -0
  56. multimodalsrm/bayesian/state_space_parameters.py +411 -0
  57. multimodalsrm/bayesian/state_space_rational.py +177 -0
  58. multimodalsrm/bayesian/state_space_responses.py +267 -0
  59. multimodalsrm/bayesian/temporal_noise.py +192 -0
  60. multimodalsrm/bayesian/timing.py +30 -0
  61. multimodalsrm/bayesian/trajectories.py +177 -0
  62. multimodalsrm/bayesian/transform.py +199 -0
  63. multimodalsrm/bayesian/updated_posterior_persistence.py +95 -0
  64. multimodalsrm/bayesian/warmup_checkpoint.py +190 -0
  65. multimodalsrm/bayesian/workflow.py +270 -0
  66. multimodalsrm/calibration.py +380 -0
  67. multimodalsrm/data.py +84 -0
  68. multimodalsrm/estimator.py +617 -0
  69. multimodalsrm/grouping.py +33 -0
  70. multimodalsrm/inference.py +298 -0
  71. multimodalsrm/initialization.py +77 -0
  72. multimodalsrm/inspection.py +167 -0
  73. multimodalsrm/kernel_optimization.py +316 -0
  74. multimodalsrm/kernels.py +485 -0
  75. multimodalsrm/objective.py +437 -0
  76. multimodalsrm/operators.py +181 -0
  77. multimodalsrm/optimization.py +348 -0
  78. multimodalsrm/posterior_results.py +29 -0
  79. multimodalsrm/results.py +33 -0
  80. multimodalsrm/selection.py +574 -0
  81. multimodalsrm/validation.py +258 -0
  82. multimodalsrm-0.1.0.dist-info/METADATA +128 -0
  83. multimodalsrm-0.1.0.dist-info/RECORD +86 -0
  84. multimodalsrm-0.1.0.dist-info/WHEEL +5 -0
  85. multimodalsrm-0.1.0.dist-info/licenses/LICENSE +21 -0
  86. multimodalsrm-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,261 @@
1
+ """Descriptive held-out alignment scores, one run and common query clock at a time.
2
+
3
+ No fitting, sign selection, time warping, or inferential p-values occur here.
4
+ TimeSeries inputs must already be in comparable coordinates; the caller owns
5
+ their train/test provenance. Bayesian inputs must come from independent transform.
6
+ """
7
+
8
+ from collections.abc import Mapping
9
+
10
+ import numpy as np
11
+
12
+ from .data import TimeSeries
13
+
14
+
15
+ def _inputs(series):
16
+ from .bayesian.results import GaussianMixtureSeries
17
+
18
+ if not isinstance(series, Mapping) or len(series) < 2:
19
+ raise ValueError("supply at least two participants for one run")
20
+ values, masks, kinds, conventions, runs = [], [], set(), [], set()
21
+ references, calibrated, readouts = [], False, set()
22
+ times, features = None, None
23
+ for subject, item in series.items():
24
+ if isinstance(item, TimeSeries):
25
+ mask = item.mask
26
+ kinds.add("raw")
27
+ elif isinstance(item, GaussianMixtureSeries):
28
+ meta = item.metadata
29
+ if (
30
+ meta.get("independent_subject_inference") is not True
31
+ or meta.get("conditioning_subject") != subject
32
+ or meta.get("parameter_source")
33
+ not in (
34
+ "original_training_MAP",
35
+ "group_MAP_plus_participant_calibration_MAP",
36
+ )
37
+ or meta.get("parameter_refits") != 0
38
+ or meta.get("quantity") != "unfiltered_shared_latent"
39
+ ):
40
+ raise ValueError(
41
+ "Bayesian alignment requires independent subject transform results"
42
+ )
43
+ mask = np.broadcast_to(item.valid[:, None], item.values.shape)
44
+ kinds.add("independent_training_MAP")
45
+ conventions.append(meta.get("reference_convention"))
46
+ runs.add(meta.get("conditioning_run"))
47
+ readouts.add(meta.get("alignment_readout", "gp"))
48
+ calibrated |= (
49
+ meta.get("parameter_source") == "group_MAP_plus_participant_calibration_MAP"
50
+ )
51
+ references.append(meta.get("training_reference_id"))
52
+ else:
53
+ raise ValueError("inputs must be TimeSeries or independent GaussianMixtureSeries")
54
+ if times is not None and not np.array_equal(times, item.times):
55
+ raise ValueError("participants must have the same query clock")
56
+ if features is not None and features != item.values.shape[1]:
57
+ raise ValueError("participants must have the same feature count")
58
+ times, features = item.times, item.values.shape[1]
59
+ values.append(item.values)
60
+ masks.append(mask)
61
+ if len(kinds) != 1:
62
+ raise ValueError("do not mix raw and transformed coordinates in one evaluation")
63
+ if len(runs) > 1 or any(c != conventions[0] for c in conventions):
64
+ raise ValueError("transformed participants must share a run and reference convention")
65
+ if len(readouts) > 1:
66
+ raise ValueError("transformed participants must share the same alignment readout")
67
+ if calibrated and (
68
+ any(not isinstance(r, str) or not r for r in references) or len(set(references)) != 1
69
+ ):
70
+ raise ValueError("calibrated participants must share the same frozen group reference")
71
+ valid = np.stack(masks).all(axis=0)
72
+ # Masked values can be NaN or infinite. They must not enter any arithmetic.
73
+ values = np.where(valid[None, :, :], np.stack(values), 0.0)
74
+ source = "independent_group_and_calibration_MAP" if calibrated else kinds.pop()
75
+ return list(series), values, valid, times, source
76
+
77
+
78
+ def _mean(values):
79
+ """Average finite values without overflowing the sum across participants."""
80
+ scale = np.max(np.abs(values), axis=0)
81
+ divisor = np.where(scale == 0, 1, scale)
82
+ return np.clip(np.mean(values / divisor, axis=0), -1, 1) * scale
83
+
84
+
85
+ def _unit(vector):
86
+ # Scale first to avoid overflow. Near-constant signals are undefined, not noise wins.
87
+ if not np.isfinite(vector).all():
88
+ raise FloatingPointError("nonfinite alignment vector")
89
+ scale = np.max(np.abs(vector))
90
+ if scale == 0:
91
+ return None
92
+ centered = vector / scale - np.mean(vector / scale)
93
+ norm = np.linalg.norm(centered)
94
+ if norm <= 1e-12 * np.sqrt(len(vector)):
95
+ return None
96
+ return centered / norm
97
+
98
+
99
+ def temporal_isc(series):
100
+ """Per-feature temporal Pearson ISC against the leave-one-participant-out mean.
101
+
102
+ Use each feature's intersection of valid rows across ALL participants.
103
+ At least three rows and nonconstant query/reference signals are required.
104
+ Aggregate Fisher-z means are undefined if any participant is undefined;
105
+ individual outcomes and support counts are always retained. This is temporal
106
+ ISC, not correlation over features at each time (pattern ISC).
107
+ """
108
+ subjects, values, valid, times, source = _inputs(series)
109
+ output = {}
110
+ for s, subject in enumerate(subjects):
111
+ correlations, reasons = [], []
112
+ for f in range(values.shape[2]):
113
+ rows = valid[:, f]
114
+ reason, correlation = None, None
115
+ if rows.sum() < 3:
116
+ reason = "insufficient_support"
117
+ else:
118
+ query = _unit(values[s, rows, f])
119
+ reference = _unit(_mean(np.delete(values, s, axis=0)[:, rows, f]))
120
+ if query is None or reference is None:
121
+ reason = "constant_signal"
122
+ else:
123
+ correlation = float(np.clip(query @ reference, -1, 1))
124
+ correlations.append(correlation)
125
+ reasons.append(reason)
126
+ output[subject] = dict(correlations=correlations, reasons=reasons)
127
+ means = []
128
+ for f in range(values.shape[2]):
129
+ scores = [output[s]["correlations"][f] for s in subjects]
130
+ means.append(
131
+ None
132
+ if any(r is None for r in scores)
133
+ else float(np.tanh(np.mean(np.arctanh(np.clip(scores, -1 + 1e-12, 1 - 1e-12)))))
134
+ )
135
+ return dict(
136
+ metric="temporal_isc",
137
+ reference="leave_one_subject_out_mean",
138
+ input_source=source,
139
+ n_subjects=len(subjects),
140
+ n_times=len(times),
141
+ n_features=values.shape[2],
142
+ n_common_valid_per_feature=valid.sum(axis=0).tolist(),
143
+ subjects=output,
144
+ mean_fisher_z_correlation_per_feature=means,
145
+ fisher_clip=1e-12,
146
+ )
147
+
148
+
149
+ def _window_unit(window, centering):
150
+ if centering == "global":
151
+ return _unit(window.ravel())
152
+ if not np.isfinite(window).all():
153
+ raise FloatingPointError("nonfinite alignment window")
154
+ scale = np.max(np.abs(window))
155
+ if scale == 0:
156
+ return None
157
+ scaled = window / scale
158
+ centered = (scaled - scaled.mean(axis=0)).ravel()
159
+ norm = np.linalg.norm(centered)
160
+ if norm <= 1e-12 * np.linalg.norm(scaled):
161
+ return None
162
+ return centered / norm
163
+
164
+
165
+ def time_segment_matching(series, *, window_size, centering="global"):
166
+ """Match each participant's time windows to the other participants' mean.
167
+
168
+ Query times must be regularly spaced. Fully valid windows are flattened
169
+ over time and features, then compared with Pearson correlation. Competing
170
+ windows that partially overlap the query are excluded; its true match stays.
171
+ Ties within 1e-12 receive fractional credit. Chance is 1/candidate count per
172
+ query, not 1/total windows. Constant vectors or fewer than two candidates
173
+ make a query undefined. An undefined query makes aggregate accuracy None.
174
+ No windows cross masked rows; do not concatenate independent runs upstream.
175
+
176
+ ``centering="feature"`` is a companion score: subtract each feature's
177
+ within-window temporal mean before the normalized dot product. It is
178
+ invariant to a common orthogonal feature rotation (up to roundoff), but
179
+ not arbitrary feature scaling. The historical scalar-centering metric
180
+ remains the default; the companion has a distinct metric identifier.
181
+ """
182
+ if centering not in ("global", "feature"):
183
+ raise ValueError("centering must be global or feature")
184
+ if (
185
+ isinstance(window_size, (bool, np.bool_))
186
+ or not isinstance(window_size, (int, np.integer))
187
+ or window_size < 3
188
+ ):
189
+ raise ValueError("window_size must be an integer of at least three samples")
190
+ subjects, values, valid, times, source = _inputs(series)
191
+ delta = np.diff(times)
192
+ if len(delta) and not np.allclose(delta, delta[0], rtol=1e-7, atol=1e-10):
193
+ raise ValueError("time-segment matching requires a regular query clock")
194
+ rows = valid.all(axis=1)
195
+ possible = max(0, len(times) - window_size + 1)
196
+ starts = np.array([i for i in range(possible) if rows[i : i + window_size].all()], dtype=int)
197
+ output = {}
198
+ for s, subject in enumerate(subjects):
199
+ reference = _mean(np.delete(values, s, axis=0))
200
+ queries = [_window_unit(values[s, i : i + window_size], centering) for i in starts]
201
+ targets = [_window_unit(reference[i : i + window_size], centering) for i in starts]
202
+ target_valid = np.array([t is not None for t in targets], bool)
203
+ target_matrix = np.array(
204
+ [t if t is not None else np.zeros(window_size * values.shape[2]) for t in targets]
205
+ )
206
+ records = []
207
+ # One query at a time avoids a quadratic score matrix in memory.
208
+ for index, (i, query) in enumerate(zip(starts, queries)):
209
+ candidates = (np.abs(starts - i) >= window_size) | (starts == i)
210
+ count = int(candidates.sum())
211
+ reason, credit, ties = None, None, None
212
+ if count < 2:
213
+ reason = "insufficient_candidates"
214
+ elif query is None or not target_valid[candidates].all():
215
+ reason = "constant_signal"
216
+ else:
217
+ scores = target_matrix @ query
218
+ winners = candidates & np.isclose(
219
+ scores, scores[candidates].max(), rtol=0, atol=1e-12
220
+ )
221
+ ties = int(winners.sum())
222
+ credit = float(winners[index]) / ties
223
+ records.append(
224
+ dict(
225
+ start_index=int(i),
226
+ start_time=float(times[i]),
227
+ n_candidates=count,
228
+ credit=credit,
229
+ chance=1 / count if count >= 2 else None,
230
+ n_ties=ties,
231
+ reason=reason,
232
+ )
233
+ )
234
+ complete = bool(records) and all(r["credit"] is not None for r in records)
235
+ output[subject] = dict(
236
+ accuracy=float(np.mean([r["credit"] for r in records])) if complete else None,
237
+ chance=float(np.mean([r["chance"] for r in records]))
238
+ if records and all(r["chance"] is not None for r in records)
239
+ else None,
240
+ n_queries=len(records),
241
+ n_scored_queries=sum(r["credit"] is not None for r in records),
242
+ reason=None if complete else ("undefined_queries" if records else "no_valid_windows"),
243
+ queries=records,
244
+ )
245
+ return dict(
246
+ metric="time_segment_matching"
247
+ if centering == "global"
248
+ else "time_segment_matching_feature_centered",
249
+ reference="leave_one_subject_out_mean",
250
+ input_source=source,
251
+ n_subjects=len(subjects),
252
+ n_times=len(times),
253
+ n_features=values.shape[2],
254
+ window_size=int(window_size),
255
+ query_interval=float(delta[0]) if len(delta) else None,
256
+ window_starts=starts.tolist(),
257
+ n_common_valid_rows=int(rows.sum()),
258
+ n_excluded_windows=possible - len(starts),
259
+ subjects=output,
260
+ tie_tolerance=1e-12,
261
+ )
@@ -0,0 +1,24 @@
1
+ """Experimental Bayesian SRM; optional runtime is loaded only when fitting."""
2
+
3
+ from .blocks import ParameterSubspace
4
+ from .calibration import ParticipantCalibration
5
+ from .fitting import SamplerConfig, SearchConfig
6
+ from .model import BayesianMultimodalSRM
7
+ from .priors import BayesianPriors, Prior
8
+ from .problem import BayesianProblem
9
+ from .results import GaussianMixtureSeries, TrajectorySamples
10
+ from .spectral import SpectralConfig
11
+
12
+ __all__ = [
13
+ "Prior",
14
+ "BayesianPriors",
15
+ "BayesianProblem",
16
+ "ParameterSubspace",
17
+ "BayesianMultimodalSRM",
18
+ "SearchConfig",
19
+ "SamplerConfig",
20
+ "GaussianMixtureSeries",
21
+ "TrajectorySamples",
22
+ "SpectralConfig",
23
+ "ParticipantCalibration",
24
+ ]
@@ -0,0 +1,255 @@
1
+ """Versioned non-executable storage for built-in Bayesian model configurations."""
2
+
3
+ import hashlib
4
+ import json
5
+ import os
6
+ import tempfile
7
+ from dataclasses import fields, is_dataclass
8
+ from pathlib import Path
9
+ from zipfile import BadZipFile
10
+
11
+ import numpy as np
12
+
13
+ from ..data import TimeSeries, readonly_array
14
+ from ..kernels import BachSCR, DoubleGamma, Gamma, Gaussian, Identity, Response
15
+ from .fitting import SamplerConfig, SearchConfig
16
+ from .priors import BayesianPriors, Prior
17
+ from .spectral import SpectralConfig
18
+ from .workflow import TrainingStandardizer
19
+
20
+ CLASSES = {
21
+ c.__name__: c
22
+ for c in (
23
+ TimeSeries,
24
+ Identity,
25
+ Gaussian,
26
+ Gamma,
27
+ DoubleGamma,
28
+ BachSCR,
29
+ Response,
30
+ Prior,
31
+ BayesianPriors,
32
+ SearchConfig,
33
+ SamplerConfig,
34
+ SpectralConfig,
35
+ TrainingStandardizer,
36
+ )
37
+ }
38
+ FORMAT = "personalized-srm-bayesian-map"
39
+ VERSION = 1
40
+
41
+
42
+ def same(a, b):
43
+ """Compare supported state without ambiguous array truth values."""
44
+ if isinstance(a, np.ndarray) or isinstance(b, np.ndarray):
45
+ return (
46
+ isinstance(a, np.ndarray)
47
+ and isinstance(b, np.ndarray)
48
+ and a.dtype == b.dtype
49
+ and np.array_equal(a, b, equal_nan=True)
50
+ )
51
+ if is_dataclass(a) or is_dataclass(b):
52
+ return type(a) is type(b) and all(
53
+ same(getattr(a, f.name), getattr(b, f.name)) for f in fields(a)
54
+ )
55
+ if isinstance(a, dict) or isinstance(b, dict):
56
+ return (
57
+ isinstance(a, dict)
58
+ and isinstance(b, dict)
59
+ and a.keys() == b.keys()
60
+ and all(same(a[k], b[k]) for k in a)
61
+ )
62
+ if isinstance(a, (list, tuple)) or isinstance(b, (list, tuple)):
63
+ return type(a) is type(b) and len(a) == len(b) and all(same(x, y) for x, y in zip(a, b))
64
+ if isinstance(a, (float, np.floating)) and np.isnan(a):
65
+ return isinstance(b, (float, np.floating)) and np.isnan(b)
66
+ return a == b
67
+
68
+
69
+ def encode(value, arrays):
70
+ if isinstance(value, np.ndarray):
71
+ if value.dtype.kind not in "biuf":
72
+ raise ValueError("model arrays must have real numeric or Boolean dtype")
73
+ name = f"a{len(arrays)}"
74
+ arrays[name] = value.copy()
75
+ return {"type": "array", "name": name}
76
+ if isinstance(value, np.generic):
77
+ return encode(value.item(), arrays)
78
+ if type(value) in CLASSES.values():
79
+ return {
80
+ "type": "record",
81
+ "class": type(value).__name__,
82
+ "fields": {f.name: encode(getattr(value, f.name), arrays) for f in fields(value)},
83
+ }
84
+ if isinstance(value, dict):
85
+ return {
86
+ "type": "dict",
87
+ "items": [[encode(k, arrays), encode(v, arrays)] for k, v in value.items()],
88
+ }
89
+ if isinstance(value, (list, tuple)):
90
+ return {
91
+ "type": "tuple" if isinstance(value, tuple) else "list",
92
+ "items": [encode(v, arrays) for v in value],
93
+ }
94
+ if isinstance(value, float) and not np.isfinite(value):
95
+ return {"type": "float", "value": str(value)}
96
+ if value is None or type(value) in (bool, int, float, str):
97
+ return value
98
+ raise ValueError(f"unsupported model archive object: {type(value).__name__}")
99
+
100
+
101
+ def decode(value, arrays, used):
102
+ if value is None or type(value) in (bool, int, float, str):
103
+ return value
104
+ if not isinstance(value, dict):
105
+ raise ValueError("invalid encoded model state")
106
+ kind = value.get("type")
107
+ if kind == "array" and set(value) == {"type", "name"}:
108
+ name = value["name"]
109
+ if name not in arrays.files:
110
+ raise ValueError("missing model array")
111
+ array = arrays[name]
112
+ if array.dtype.kind not in "biuf":
113
+ raise ValueError("invalid model array dtype")
114
+ used.add(name)
115
+ return readonly_array(array, array.dtype)
116
+ if kind == "float" and set(value) == {"type", "value"}:
117
+ if value["value"] not in ("inf", "-inf", "nan"):
118
+ raise ValueError("invalid encoded float")
119
+ return float(value["value"])
120
+ if kind in ("tuple", "list", "dict") and set(value) == {"type", "items"}:
121
+ items = value["items"]
122
+ if not isinstance(items, list):
123
+ raise ValueError("invalid encoded container")
124
+ if kind == "dict":
125
+ result = {}
126
+ for pair in items:
127
+ if not isinstance(pair, list) or len(pair) != 2:
128
+ raise ValueError("invalid dictionary entry")
129
+ key, item = [decode(v, arrays, used) for v in pair]
130
+ if key in result:
131
+ raise ValueError("duplicate model state key")
132
+ result[key] = item
133
+ return result
134
+ result = [decode(v, arrays, used) for v in items]
135
+ return tuple(result) if kind == "tuple" else result
136
+ if kind == "record" and set(value) == {"type", "class", "fields"}:
137
+ cls = CLASSES.get(value["class"])
138
+ record_fields = value["fields"]
139
+ # Fill only additive fitting defaults in older archives; all other
140
+ # missing or unknown fields remain errors. Keep provenance unchanged.
141
+ if cls is SearchConfig and isinstance(record_fields, dict):
142
+ expected = {f.name for f in fields(cls)}
143
+ defaults = {"polish_max_parameters": 256, "n_jobs": 1, "conditioning": "none"}
144
+ if expected - defaults.keys() <= record_fields.keys() <= expected:
145
+ record_fields = {**defaults, **record_fields}
146
+ if cls is SamplerConfig and isinstance(record_fields, dict):
147
+ expected = {f.name for f in fields(cls)}
148
+ defaults = {
149
+ "mass_matrix": "dense",
150
+ "max_dense_parameters": 1024,
151
+ "orientation_refresh": "none",
152
+ }
153
+ if expected - defaults.keys() <= record_fields.keys() <= expected:
154
+ record_fields = {**defaults, **record_fields}
155
+ if (
156
+ cls is None
157
+ or not isinstance(record_fields, dict)
158
+ or set(record_fields) != {f.name for f in fields(cls)}
159
+ ):
160
+ raise ValueError("unsupported model record or fields")
161
+ return cls(**{k: decode(v, arrays, used) for k, v in record_fields.items()})
162
+ raise ValueError("unsupported encoded model state")
163
+
164
+
165
+ def digest(path):
166
+ result = hashlib.sha256()
167
+ with Path(path).open("rb") as stream:
168
+ for chunk in iter(lambda: stream.read(1024 * 1024), b""):
169
+ result.update(chunk)
170
+ return result.hexdigest()
171
+
172
+
173
+ def write(path, state, *, version=VERSION):
174
+ path = Path(path)
175
+ if os.path.lexists(path):
176
+ raise FileExistsError(path)
177
+ arrays = {}
178
+ manifest = dict(format=FORMAT, schema_version=version, state=encode(state, arrays))
179
+ # All payload construction happens before claiming the destination. The final
180
+ # checksum is the completion marker; incomplete publication cannot be loaded.
181
+ path.parent.mkdir(parents=True, exist_ok=True)
182
+ with tempfile.TemporaryDirectory(prefix=".srm-model-", dir=path.parent) as folder:
183
+ temporary = Path(folder)
184
+ np.savez_compressed(temporary / "arrays.npz", **arrays)
185
+ manifest["arrays_sha256"] = digest(temporary / "arrays.npz")
186
+ (temporary / "manifest.json").write_text(
187
+ json.dumps(manifest, allow_nan=False, indent=2) + "\n"
188
+ )
189
+ (temporary / "manifest.sha256").write_text(digest(temporary / "manifest.json") + "\n")
190
+ path.mkdir(exist_ok=False)
191
+ for name in ("arrays.npz", "manifest.json", "manifest.sha256"):
192
+ os.replace(temporary / name, path / name)
193
+
194
+
195
+ def _unique_object(pairs):
196
+ result = {}
197
+ for key, value in pairs:
198
+ if key in result:
199
+ raise ValueError("duplicate JSON key in model archive")
200
+ result[key] = value
201
+ return result
202
+
203
+
204
+ def _invalid_constant(value):
205
+ raise ValueError(f"invalid JSON number: {value}")
206
+
207
+
208
+ def read(path):
209
+ path = Path(path)
210
+ try:
211
+ if digest(path / "manifest.json") != (path / "manifest.sha256").read_text().strip():
212
+ raise ValueError("model manifest hash mismatch")
213
+ manifest = json.loads(
214
+ (path / "manifest.json").read_text(),
215
+ object_pairs_hook=_unique_object,
216
+ parse_constant=_invalid_constant,
217
+ )
218
+ if not isinstance(manifest, dict) or set(manifest) != {
219
+ "format",
220
+ "schema_version",
221
+ "arrays_sha256",
222
+ "state",
223
+ }:
224
+ raise ValueError("invalid model archive manifest")
225
+ if (
226
+ manifest["format"] != FORMAT
227
+ or type(manifest["schema_version"]) is not int
228
+ or manifest["schema_version"] not in (1, 2, 3, 4)
229
+ ):
230
+ raise ValueError("unsupported model archive format or version")
231
+ if digest(path / "arrays.npz") != manifest["arrays_sha256"]:
232
+ raise ValueError("model array hash mismatch")
233
+ with np.load(path / "arrays.npz", allow_pickle=False) as arrays:
234
+ if len(set(arrays.files)) != len(arrays.files):
235
+ raise ValueError("duplicate model array names")
236
+ used = set()
237
+ state = decode(manifest["state"], arrays, used)
238
+ if used != set(arrays.files):
239
+ raise ValueError("unreferenced model arrays")
240
+ posterior = isinstance(state, dict) and state.get("kind") == "posterior_training"
241
+ if (manifest["schema_version"] == 3) != posterior:
242
+ raise ValueError("posterior archive kind requires schema version 3")
243
+ updated = isinstance(state, dict) and state.get("kind") == "posterior_updated"
244
+ if (manifest["schema_version"] == 4) != updated:
245
+ raise ValueError("updated posterior archive kind requires schema version 4")
246
+ return state
247
+ except (
248
+ OSError,
249
+ KeyError,
250
+ TypeError,
251
+ AttributeError,
252
+ OverflowError,
253
+ BadZipFile,
254
+ ) as exc:
255
+ raise ValueError(f"invalid or incomplete model archive: {exc}") from exc
@@ -0,0 +1,92 @@
1
+ """Optional float64 runtime and differentiable continuous response covariance."""
2
+
3
+ import numpy as np
4
+ from scipy.special import erf, ndtr
5
+
6
+
7
+ def runtime():
8
+ try:
9
+ import jax
10
+ import jax.numpy as jnp
11
+ import jax.scipy as jsp
12
+ import numpyro.distributions as dist
13
+ except ImportError as exc:
14
+ raise ImportError("Bayesian SRM requires multimodalsrm[bayesian]") from exc
15
+ if not jax.config.x64_enabled:
16
+ raise RuntimeError(
17
+ "Bayesian SRM requires float64: set JAX_ENABLE_X64=true before starting Python"
18
+ )
19
+ return jax, jnp, jsp, dist
20
+
21
+
22
+ def accuracy_bound(responses, length_scale, tolerance):
23
+ """Conservative temporal-entry bound over every allowed filter width.
24
+
25
+ Six-sigma tail mass times maximal response mass bounds the omitted
26
+ integral, since the unit-variance Matérn covariance lies in [0, 1]. The
27
+ rounding term is an estimate, not interval arithmetic certification.
28
+ Unsupported broad-filter cancellation regimes are rejected explicitly.
29
+ """
30
+ from ..kernels import Gaussian
31
+
32
+ widths = [
33
+ r.parameter_bounds()["width"][1]
34
+ if "width" in r.free_parameters
35
+ else r.initial_kernel().width
36
+ for r in responses.values()
37
+ if type(r.initial_kernel()) is Gaussian
38
+ ]
39
+ if not widths:
40
+ return 0.0
41
+ width = max(widths)
42
+ mass = max(1.0, np.sqrt(2) * np.pi**0.25 * np.sqrt(width) / np.sqrt(erf(6.0)))
43
+ q = np.sqrt(6.0) * width / length_scale
44
+ tail = mass**2 * (4 * ndtr(-6.0) - 4 * ndtr(-6.0) ** 2)
45
+ bound = tail + 64 * np.finfo(float).eps * mass**2 * (1 + q * q)
46
+ if q > 5 or bound > tolerance:
47
+ raise ValueError(
48
+ "requested covariance accuracy is unsupported for these width/length_scale bounds; narrow widths or use the finite-integral continuous reference"
49
+ )
50
+ return float(bound)
51
+
52
+
53
+ def temporal(times_a, times_b, width_a, width_b, lag_a, lag_b, length_scale):
54
+ """Gaussian/Identity functional covariance with finite-L2 normalization."""
55
+ _, jnp, _, _ = runtime()
56
+ delta = (
57
+ jnp.asarray(times_a)[:, None]
58
+ - jnp.asarray(times_b)[None, :]
59
+ - lag_a[:, None]
60
+ + lag_b[None, :]
61
+ )
62
+ return temporal_values(
63
+ delta, jnp.asarray(width_a)[:, None], jnp.asarray(width_b)[None, :], length_scale
64
+ )
65
+
66
+
67
+ def temporal_values(delta, width_a, width_b, length_scale):
68
+ """Evaluate broadcast-compatible separations without forming a pair grid."""
69
+ _, jnp, jsp, _ = runtime()
70
+ wa, wb = jnp.asarray(width_a), jnp.asarray(width_b)
71
+ identity = (wa == 0) & (wb == 0)
72
+ sigma = jnp.sqrt(wa**2 + wb**2 + identity)
73
+ rate = np.sqrt(3.0) / length_scale
74
+ d = jnp.abs(delta)
75
+ q, r = rate * sigma, d / sigma
76
+ plus = jnp.exp(0.5 * q * q - rate * d + jsp.special.log_ndtr(r - q))
77
+ minus = jnp.exp(0.5 * q * q + rate * d + jsp.special.log_ndtr(-r - q))
78
+ normal = (
79
+ (1 + rate * d - q * q) * plus
80
+ + (1 - rate * d - q * q) * minus
81
+ + 2 * q * jnp.exp(-0.5 * r * r) / np.sqrt(2 * np.pi)
82
+ )
83
+
84
+ def mass(w):
85
+ safe = jnp.where(w == 0, 1.0, w)
86
+ return jnp.where(w == 0, 1.0, np.sqrt(2) * np.pi**0.25 * jnp.sqrt(safe) / np.sqrt(erf(6.0)))
87
+
88
+ return jnp.where(
89
+ identity,
90
+ (1 + rate * d) * jnp.exp(-rate * d),
91
+ normal * mass(wa) * mass(wb),
92
+ )