calibrain 1.0.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.

Potentially problematic release.


This version of calibrain might be problematic. Click here for more details.

calibrain/__init__.py ADDED
@@ -0,0 +1,27 @@
1
+ from calibrain.leadfield_builder import LeadfieldBuilder
2
+ from calibrain.source_simulation import SourceSimulator
3
+ from calibrain.sensor_simulation import SensorSimulator
4
+ from calibrain.source_estimation import SourceEstimator, gamma_map_sflex, BMN, gamma_lambda_map_sflex, BMN_joint
5
+ from calibrain.uncertainty_estimation import UncertaintyEstimator
6
+ from calibrain.metric_evaluation import MetricEvaluator
7
+ from calibrain.uncertainty_calibration import UncertaintyCalibrator
8
+ from calibrain.visualization import Visualizer
9
+ from calibrain.data_generation import DataGenerator
10
+
11
+ __all__ = [
12
+ "DataGenerator",
13
+ "LeadfieldBuilder",
14
+ "SourceSimulator",
15
+ "SensorSimulator",
16
+ "SourceEstimator",
17
+ "UncertaintyEstimator",
18
+ "UncertaintyCalibrator",
19
+ "MetricEvaluator",
20
+ "Visualizer",
21
+ "gamma_map_sflex",
22
+ "BMN",
23
+ "BMN_joint",
24
+ "gamma_lambda_map_sflex",
25
+ ]
26
+
27
+ __version__ = "1.0.1"
@@ -0,0 +1,352 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ import json
5
+ from pathlib import Path
6
+ from typing import Any, Dict, Iterable, List, Sequence, Tuple
7
+
8
+ import h5py
9
+ import numpy as np
10
+ from mne.io.constants import FIFF
11
+ from scipy.linalg import block_diag
12
+
13
+ EEG_COIL_TYPES = {FIFF.FIFFV_COIL_EEG}
14
+ MEG_COIL_TYPES = {
15
+ FIFF.FIFFV_COIL_VV_MAG_T1,
16
+ FIFF.FIFFV_COIL_VV_PLANAR_T1,
17
+ }
18
+ ALLOWED_COIL_TYPES = EEG_COIL_TYPES | MEG_COIL_TYPES
19
+
20
+
21
+ def _maybe_q_basis_array(array: Any) -> np.ndarray | None:
22
+ if array is None:
23
+ return None
24
+ arr = np.asarray(array)
25
+ if arr.size == 0:
26
+ return None
27
+ if arr.ndim == 0:
28
+ # Scalar placeholder (e.g., NaN for fixed orientation)
29
+ return None
30
+ return arr.astype(float, copy=False)
31
+
32
+
33
+
34
+
35
+ @dataclass
36
+ class PosteriorSummary:
37
+ """Container describing a saved posterior summary file and metadata."""
38
+
39
+ path: Path
40
+ metadata: dict | None = None
41
+
42
+
43
+ def _normalize_orientation(orientation_type: str | None) -> str:
44
+ if orientation_type is None:
45
+ return "fixed"
46
+ normalized = orientation_type.lower()
47
+ if normalized not in {"fixed", "free"}:
48
+ raise ValueError(f"Unsupported orientation_type '{orientation_type}'")
49
+ return normalized
50
+
51
+
52
+ def _validate_coil_type(coil_type: int | None) -> None:
53
+ if coil_type is None:
54
+ return
55
+ if coil_type not in ALLOWED_COIL_TYPES:
56
+ raise ValueError(
57
+ f"Unsupported coil_type '{coil_type}'. Expected one of "
58
+ f"{sorted(ALLOWED_COIL_TYPES)} or None."
59
+ )
60
+
61
+
62
+ def is_fixed_orientation(orientation_type: str | None) -> bool:
63
+ return _normalize_orientation(orientation_type) == "fixed"
64
+
65
+
66
+ def is_free_eeg_orientation(
67
+ orientation_type: str | None,
68
+ coil_type: int | None,
69
+ n_components: int | None = None,
70
+ ) -> bool:
71
+ if _normalize_orientation(orientation_type) != "free":
72
+ return False
73
+ if coil_type is not None:
74
+ _validate_coil_type(coil_type)
75
+ return coil_type in EEG_COIL_TYPES
76
+ return n_components == 3
77
+
78
+
79
+ def is_free_meg_orientation(
80
+ orientation_type: str | None,
81
+ coil_type: int | None,
82
+ n_components: int | None = None,
83
+ ) -> bool:
84
+ if _normalize_orientation(orientation_type) != "free":
85
+ return False
86
+ if coil_type is not None:
87
+ _validate_coil_type(coil_type)
88
+ return coil_type in MEG_COIL_TYPES
89
+ return n_components == 2
90
+
91
+
92
+ def _load_h5_metadata(path: Path) -> dict | None:
93
+ try:
94
+ with h5py.File(path, "r") as handle:
95
+ meta_json = handle.attrs.get("metadata_json")
96
+ if meta_json is None:
97
+ return None
98
+ if isinstance(meta_json, bytes):
99
+ meta_json = meta_json.decode("utf-8")
100
+ return json.loads(meta_json)
101
+ except Exception:
102
+ return None
103
+
104
+
105
+ def _load_legacy_metadata(path: Path) -> dict | None:
106
+ meta_path = path.with_suffix(".json")
107
+ if not meta_path.exists():
108
+ return None
109
+ try:
110
+ return json.loads(meta_path.read_text())
111
+ except json.JSONDecodeError:
112
+ return None
113
+
114
+ def load_posterior_summary(summary: PosteriorSummary) -> dict:
115
+ """
116
+ Load a single posterior summary file produced by the data-generation workflow.
117
+ Supports the new HDF5 format as well as legacy ``.npz`` files.
118
+ """
119
+ suffix = summary.path.suffix.lower()
120
+ metadata = summary.metadata or {}
121
+ orientation_type = metadata.get("orientation_type")
122
+ coil_type = metadata.get("coil_type")
123
+ _validate_coil_type(coil_type)
124
+
125
+ if suffix in {".h5", ".hdf5"}:
126
+ with h5py.File(summary.path, "r") as handle:
127
+ def _require(name: str) -> np.ndarray:
128
+ if name not in handle:
129
+ raise KeyError(f"Dataset '{name}' missing in {summary.path}")
130
+ return handle[name][:]
131
+
132
+ payload: Dict[str, Any] = {"metadata": metadata}
133
+ payload["x_true"] = _require("x_true")
134
+ payload["x_hat"] = _require("x_hat")
135
+ payload["posterior_cov"] = _require("posterior_cov")
136
+ if "Q_basis" in handle:
137
+ q_dataset = handle["Q_basis"]
138
+ q_data = q_dataset[()] if q_dataset.shape == () else q_dataset[:]
139
+ q_basis = _maybe_q_basis_array(q_data)
140
+ if q_basis is not None:
141
+ payload["Q_basis"] = q_basis
142
+ return payload
143
+
144
+ if suffix == ".npz":
145
+ with np.load(summary.path) as data:
146
+ payload = {"metadata": metadata}
147
+ payload["x_true"] = data["x_true"]
148
+ payload["x_hat"] = data["x_hat"]
149
+ payload["posterior_cov"] = data["posterior_cov"]
150
+ if "Q_basis" in data:
151
+ q_basis = _maybe_q_basis_array(data["Q_basis"])
152
+ if q_basis is not None:
153
+ payload["Q_basis"] = q_basis
154
+ return payload
155
+
156
+ raise ValueError(f"Unsupported posterior summary format: {summary.path}")
157
+
158
+
159
+ def discover_posterior_summaries(root: Path) -> Iterable[PosteriorSummary]:
160
+ for path in root.rglob("posterior_summary*.h5"):
161
+ metadata = _load_h5_metadata(path)
162
+ yield PosteriorSummary(path=path, metadata=metadata)
163
+ for path in root.rglob("posterior_summary*.npz"):
164
+ metadata = _load_legacy_metadata(path)
165
+ yield PosteriorSummary(path=path, metadata=metadata)
166
+
167
+
168
+ def metadata_matches(metadata: dict | None, criteria: dict | None) -> bool:
169
+ if not criteria:
170
+ return True
171
+ metadata = metadata or {}
172
+ for key, allowed in criteria.items():
173
+ current_value = metadata.get(key)
174
+ if callable(allowed):
175
+ if not allowed(current_value):
176
+ return False
177
+ continue
178
+ if isinstance(allowed, (list, tuple, set, frozenset)):
179
+ if current_value not in allowed:
180
+ return False
181
+ else:
182
+ if current_value != allowed:
183
+ return False
184
+ return True
185
+
186
+
187
+ def filter_summaries_by_metadata(
188
+ summaries: Sequence[PosteriorSummary],
189
+ criteria: dict | None,
190
+ ) -> List[PosteriorSummary]:
191
+ if not criteria:
192
+ return list(summaries)
193
+ return [s for s in summaries if metadata_matches(s.metadata, criteria)]
194
+
195
+
196
+ def split_summaries_by_metadata(
197
+ summaries: Sequence[PosteriorSummary],
198
+ train_criteria: dict | None,
199
+ test_criteria: dict | None = None,
200
+ ) -> Tuple[List[PosteriorSummary], List[PosteriorSummary]]:
201
+ train = filter_summaries_by_metadata(summaries, train_criteria)
202
+ train_paths = {s.path for s in train}
203
+ remainder = [s for s in summaries if s.path not in train_paths]
204
+
205
+ if test_criteria is None:
206
+ test = remainder
207
+ else:
208
+ test = filter_summaries_by_metadata(remainder, test_criteria)
209
+
210
+ return train, test
211
+
212
+
213
+ def concatenate_summaries(
214
+ summaries: Sequence[PosteriorSummary],
215
+ ) -> dict:
216
+ if not summaries:
217
+ raise ValueError("At least one posterior summary is required.")
218
+
219
+ reference_orientation: str | None = None
220
+ reference_coil: int | None = None
221
+ reference_metadata: dict | None = None
222
+ collected_metadata: List[dict | None] = []
223
+
224
+ fixed_true: List[np.ndarray] = []
225
+ fixed_hat: List[np.ndarray] = []
226
+ fixed_covs: List[np.ndarray] = []
227
+
228
+ eeg_true: List[np.ndarray] = []
229
+ eeg_hat: List[np.ndarray] = []
230
+ eeg_covs: List[np.ndarray] = []
231
+
232
+ meg_true: List[np.ndarray] = []
233
+ meg_hat: List[np.ndarray] = []
234
+ meg_covs: List[np.ndarray] = []
235
+ meg_qbasis: List[np.ndarray] = []
236
+
237
+ for summary in summaries:
238
+ payload = load_posterior_summary(summary)
239
+ metadata = payload.get("metadata") or {}
240
+ orientation = metadata.get("orientation_type")
241
+ orientation_norm = _normalize_orientation(orientation)
242
+ coil = metadata.get("coil_type")
243
+ _validate_coil_type(coil)
244
+ if orientation_norm == "free" and coil is None:
245
+ raise ValueError(
246
+ "Free-orientation summaries must record a supported coil_type."
247
+ )
248
+
249
+ if reference_orientation is None:
250
+ reference_metadata = metadata
251
+ reference_orientation = orientation_norm
252
+ reference_coil = coil
253
+ else:
254
+ if orientation_norm != reference_orientation:
255
+ raise ValueError(
256
+ "Cannot mix orientation_type values while concatenating summaries."
257
+ )
258
+ if reference_coil != coil:
259
+ raise ValueError(
260
+ "Cannot mix coil_type values while concatenating summaries."
261
+ )
262
+ collected_metadata.append(metadata)
263
+
264
+ x_true = np.asarray(payload["x_true"], dtype=float)
265
+ x_hat = np.asarray(payload["x_hat"], dtype=float)
266
+ posterior_cov = np.asarray(payload["posterior_cov"], dtype=float)
267
+
268
+ if orientation_norm == "fixed":
269
+ fixed_true.append(x_true)
270
+ fixed_hat.append(x_hat)
271
+ fixed_covs.append(posterior_cov)
272
+ continue
273
+
274
+ if orientation_norm == "free" and coil in EEG_COIL_TYPES:
275
+ eeg_true.append(x_true)
276
+ eeg_hat.append(x_hat)
277
+ eeg_covs.append(posterior_cov)
278
+ continue
279
+
280
+ if orientation_norm == "free" and coil in MEG_COIL_TYPES:
281
+ q_basis = _maybe_q_basis_array(payload.get("Q_basis"))
282
+ if q_basis is None:
283
+ raise ValueError(
284
+ "Free-orientation MEG summaries must include Q_basis."
285
+ )
286
+ meg_true.append(x_true)
287
+ meg_hat.append(x_hat)
288
+ meg_covs.append(posterior_cov)
289
+ meg_qbasis.append(q_basis)
290
+ continue
291
+
292
+ raise ValueError("Unhandled orientation case while concatenating summaries.")
293
+
294
+ if reference_orientation == "fixed":
295
+ x_true = np.concatenate(fixed_true, axis=0)
296
+ x_hat = np.concatenate(fixed_hat, axis=0)
297
+ posterior_cov = (
298
+ block_diag(*fixed_covs) if len(fixed_covs) > 1 else fixed_covs[0]
299
+ )
300
+ return {
301
+ "orientation_type": reference_orientation,
302
+ "coil_type": reference_coil,
303
+ "sensor_kind": (reference_metadata or {}).get("sensor_kind"),
304
+ "x_true": x_true,
305
+ "x_hat": x_hat,
306
+ "posterior_cov": posterior_cov,
307
+ "metadata": collected_metadata,
308
+ "n_sources": x_true.shape[0],
309
+ "n_times": x_true.shape[-1],
310
+ }
311
+
312
+ if reference_orientation == "free" and reference_coil in EEG_COIL_TYPES:
313
+ x_true = np.concatenate(eeg_true, axis=0)
314
+ x_hat = np.concatenate(eeg_hat, axis=0)
315
+ posterior_cov = (
316
+ block_diag(*eeg_covs) if len(eeg_covs) > 1 else eeg_covs[0]
317
+ )
318
+ return {
319
+ "orientation_type": reference_orientation,
320
+ "coil_type": reference_coil,
321
+ "sensor_kind": (reference_metadata or {}).get("sensor_kind"),
322
+ "x_true": x_true,
323
+ "x_hat": x_hat,
324
+ "posterior_cov": posterior_cov,
325
+ "metadata": collected_metadata,
326
+ "n_sources": x_true.shape[0],
327
+ "n_times": x_true.shape[-1],
328
+ }
329
+
330
+ if reference_orientation == "free" and reference_coil in MEG_COIL_TYPES:
331
+ x_true_cat = np.concatenate(meg_true, axis=0)
332
+ x_hat_cat = np.concatenate(meg_hat, axis=0)
333
+ posterior_cov = (
334
+ block_diag(*meg_covs)
335
+ if len(meg_covs) > 1
336
+ else meg_covs[0]
337
+ )
338
+ q_basis_cat = np.concatenate(meg_qbasis, axis=0)
339
+ return {
340
+ "orientation_type": reference_orientation,
341
+ "coil_type": reference_coil,
342
+ "sensor_kind": (reference_metadata or {}).get("sensor_kind"),
343
+ "x_true": x_true_cat,
344
+ "x_hat": x_hat_cat,
345
+ "posterior_cov": posterior_cov,
346
+ "Q_basis": q_basis_cat,
347
+ "metadata": collected_metadata,
348
+ "n_sources": x_true_cat.shape[0],
349
+ "n_times": x_true_cat.shape[-1],
350
+ }
351
+
352
+ raise RuntimeError("Unhandled orientation case while concatenating summaries.")
@@ -0,0 +1,157 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from pathlib import Path
5
+ from typing import Any, Callable, Dict, Iterable, Iterator, Mapping, Optional, Sequence, Tuple, Union
6
+
7
+ import numpy as np
8
+
9
+ SCHEMA_VERSION = 1
10
+ _RECORD_GLOB = "calibration_run-*.json"
11
+
12
+ Serializable = Union[str, int, float, None, bool, Sequence["Serializable"], Mapping[str, "Serializable"]]
13
+
14
+
15
+ def _to_serializable(value: Any) -> Serializable:
16
+ if isinstance(value, Path):
17
+ return value.as_posix()
18
+ if isinstance(value, (np.generic,)):
19
+ return value.item()
20
+ if isinstance(value, np.ndarray):
21
+ return np.asarray(value).tolist()
22
+ if isinstance(value, dict):
23
+ return {str(k): _to_serializable(v) for k, v in value.items()}
24
+ if isinstance(value, (list, tuple)):
25
+ return [_to_serializable(v) for v in value]
26
+ return value # type: ignore[arg-type]
27
+
28
+
29
+ def _infer_n_observations(stage_data: Mapping[str, Any]) -> Optional[int]:
30
+ if "n_observations" in stage_data and stage_data["n_observations"] is not None:
31
+ return int(stage_data["n_observations"])
32
+ ci_lowers = stage_data.get("ci_lowers")
33
+ if ci_lowers is not None:
34
+ return int(np.asarray(ci_lowers).shape[-1])
35
+ ci_counts = stage_data.get("ci_counts")
36
+ empirical = stage_data.get("empirical_coverages")
37
+ if ci_counts is not None and empirical is not None:
38
+ counts = np.asarray(ci_counts, dtype=float)
39
+ empirical = np.asarray(empirical, dtype=float)
40
+ valid = empirical > 0
41
+ if np.any(valid):
42
+ denom = counts[valid] / empirical[valid]
43
+ return int(round(float(np.median(denom))))
44
+ return None
45
+
46
+
47
+ def _compact_stage(stage_data: Optional[Mapping[str, Any]], stage: str) -> Dict[str, Any]:
48
+ if not stage_data:
49
+ return {}
50
+ payload: Dict[str, Any] = {}
51
+ for key in ("nominal_coverages", "empirical_coverages"):
52
+ value = stage_data.get(key)
53
+ if value is not None:
54
+ payload[key] = value
55
+ metrics = stage_data.get("calibration_metrics")
56
+ if metrics:
57
+ payload["calibration_metrics"] = metrics
58
+ if stage == "pre":
59
+ ci_counts = stage_data.get("ci_counts")
60
+ if ci_counts is not None:
61
+ payload["ci_counts"] = ci_counts
62
+ n_obs = _infer_n_observations(stage_data)
63
+ if n_obs is not None:
64
+ payload["n_observations"] = n_obs
65
+ if stage == "post":
66
+ recal = stage_data.get("recalibrated_nominal_coverages")
67
+ if recal is not None:
68
+ payload["recalibrated_nominal_coverages"] = recal
69
+ return payload
70
+
71
+
72
+ def save_calibration_record(
73
+ output_dir: Union[str, Path],
74
+ record_name: str,
75
+ metadata: Mapping[str, Any],
76
+ pre_calibration: Mapping[str, Any],
77
+ post_calibration: Mapping[str, Any],
78
+ ) -> Path:
79
+ """Persist calibration payload alongside metadata in JSON format."""
80
+ output_dir = Path(output_dir)
81
+ output_dir.mkdir(parents=True, exist_ok=True)
82
+ payload = {
83
+ "schema_version": SCHEMA_VERSION,
84
+ "metadata": _to_serializable(dict(metadata)),
85
+ "pre_calibration": _to_serializable(_compact_stage(pre_calibration, "pre")),
86
+ "post_calibration": _to_serializable(_compact_stage(post_calibration, "post")),
87
+ }
88
+ record_path = output_dir / f"{record_name}.json"
89
+ with record_path.open("w", encoding="utf-8") as f:
90
+ json.dump(payload, f, indent=2)
91
+ return record_path
92
+
93
+
94
+ def load_calibration_record(path: Union[str, Path]) -> Dict[str, Any]:
95
+ path = Path(path)
96
+ with path.open("r", encoding="utf-8") as f:
97
+ data = json.load(f)
98
+ data["path"] = path.as_posix()
99
+ return data
100
+
101
+
102
+ def iter_calibration_records(
103
+ root: Union[str, Path],
104
+ predicate: Optional[Callable[[Mapping[str, Any]], bool]] = None,
105
+ ) -> Iterator[Dict[str, Any]]:
106
+ root_path = Path(root)
107
+ if root_path.is_file():
108
+ paths = [root_path]
109
+ else:
110
+ paths = sorted(root_path.rglob(_RECORD_GLOB))
111
+ for path in paths:
112
+ record = load_calibration_record(path)
113
+ meta = record.get("metadata", {})
114
+ if predicate and not predicate(meta):
115
+ continue
116
+ yield record
117
+
118
+
119
+ def metadata_matcher(**expected: Any) -> Callable[[Mapping[str, Any]], bool]:
120
+ def _match(meta: Mapping[str, Any]) -> bool:
121
+ for key, value in expected.items():
122
+ if meta.get(key) != value:
123
+ return False
124
+ return True
125
+
126
+ return _match
127
+
128
+
129
+ def stack_empirical_curves(
130
+ records: Iterable[Mapping[str, Any]],
131
+ stage: str = "pre",
132
+ ) -> Tuple[np.ndarray, np.ndarray, Optional[np.ndarray]]:
133
+ curves = []
134
+ weights = []
135
+ nominal = None
136
+ for record in records:
137
+ stage_payload = record.get(f"{stage}_calibration") or {}
138
+ empirical = stage_payload.get("empirical_coverages")
139
+ if empirical is None:
140
+ continue
141
+ empirical_arr = np.asarray(empirical, dtype=float)
142
+ curves.append(empirical_arr)
143
+ if nominal is None and stage_payload.get("nominal_coverages") is not None:
144
+ nominal = np.asarray(stage_payload["nominal_coverages"], dtype=float)
145
+ if stage == "pre":
146
+ weights.append(stage_payload.get("n_observations", 1.0))
147
+ else:
148
+ weights.append(stage_payload.get("weight", 1.0))
149
+ if not curves:
150
+ raise ValueError(f"No calibration curves found for stage '{stage}'")
151
+ if nominal is None:
152
+ nominal = np.arange(curves[0].shape[-1])
153
+ curves_arr = np.vstack(curves)
154
+ weights_arr = np.asarray(weights, dtype=float)
155
+ if not np.any(weights_arr):
156
+ weights_arr = None
157
+ return nominal, curves_arr, weights_arr