calibrain 1.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


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

Files changed (31) hide show
  1. calibrain-1.0.1/LICENSE +29 -0
  2. calibrain-1.0.1/PKG-INFO +163 -0
  3. calibrain-1.0.1/README.rst +125 -0
  4. calibrain-1.0.1/calibrain/__init__.py +27 -0
  5. calibrain-1.0.1/calibrain/calibration_dataset.py +352 -0
  6. calibrain-1.0.1/calibrain/calibration_storage.py +157 -0
  7. calibrain-1.0.1/calibrain/data_generation.py +988 -0
  8. calibrain-1.0.1/calibrain/extract_leadfield.py +220 -0
  9. calibrain-1.0.1/calibrain/leadfield_builder.py +800 -0
  10. calibrain-1.0.1/calibrain/metric_evaluation.py +1024 -0
  11. calibrain-1.0.1/calibrain/reduce_fwd.py +81 -0
  12. calibrain-1.0.1/calibrain/run_manifest.py +121 -0
  13. calibrain-1.0.1/calibrain/sensor_simulation.py +307 -0
  14. calibrain-1.0.1/calibrain/source_estimation.py +2286 -0
  15. calibrain-1.0.1/calibrain/source_simulation.py +349 -0
  16. calibrain-1.0.1/calibrain/uncertainty_calibration.py +1039 -0
  17. calibrain-1.0.1/calibrain/uncertainty_estimation.py +2041 -0
  18. calibrain-1.0.1/calibrain/utils.py +197 -0
  19. calibrain-1.0.1/calibrain/visualization.py +3050 -0
  20. calibrain-1.0.1/calibrain/workflows/__init__.py +0 -0
  21. calibrain-1.0.1/calibrain/workflows/aggregation.py +288 -0
  22. calibrain-1.0.1/calibrain/workflows/calibration.py +563 -0
  23. calibrain-1.0.1/calibrain/workflows/data_generation.py +199 -0
  24. calibrain-1.0.1/calibrain/workflows/plot_paper_calibration_figures.py +703 -0
  25. calibrain-1.0.1/calibrain.egg-info/PKG-INFO +163 -0
  26. calibrain-1.0.1/calibrain.egg-info/SOURCES.txt +29 -0
  27. calibrain-1.0.1/calibrain.egg-info/dependency_links.txt +1 -0
  28. calibrain-1.0.1/calibrain.egg-info/requires.txt +26 -0
  29. calibrain-1.0.1/calibrain.egg-info/top_level.txt +1 -0
  30. calibrain-1.0.1/pyproject.toml +63 -0
  31. calibrain-1.0.1/setup.cfg +4 -0
@@ -0,0 +1,29 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2025, Mohammad Orabe
4
+ All rights reserved.
5
+
6
+ Redistribution and use in source and binary forms, with or without
7
+ modification, are permitted provided that the following conditions are met:
8
+
9
+ 1. Redistributions of source code must retain the above copyright notice, this
10
+ list of conditions and the following disclaimer.
11
+
12
+ 2. Redistributions in binary form must reproduce the above copyright notice,
13
+ this list of conditions and the following disclaimer in the documentation
14
+ and/or other materials provided with the distribution.
15
+
16
+ 3. Neither the name of the copyright holder nor the names of its
17
+ contributors may be used to endorse or promote products derived from
18
+ this software without specific prior written permission.
19
+
20
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
26
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,163 @@
1
+ Metadata-Version: 2.4
2
+ Name: calibrain
3
+ Version: 1.0.1
4
+ Summary: Simulation-based evaluation of uncertainty estimation and calibration in EEG/MEG inverse source imaging
5
+ Author-email: Mohammad Orabe <orabe.mhd@gmail.com>, Ismail Huseynov <ismailhuseynov6666@gmail.com>, Srikantan Nagarajan <Srikantan.Nagarajan@ucsf.edu>, Stefan Haufe <haufe@tu-berlin.de>
6
+ License: BSD-3-Clause
7
+ Project-URL: Homepage, https://github.com/braindatalab/CaliBrain
8
+ Project-URL: Repository, https://github.com/braindatalab/CaliBrain
9
+ Project-URL: Documentation, https://calibrain.readthedocs.io/
10
+ Requires-Python: >=3.10
11
+ Description-Content-Type: text/x-rst
12
+ License-File: LICENSE
13
+ Requires-Dist: numpy
14
+ Requires-Dist: pandas
15
+ Requires-Dist: scikit-learn
16
+ Requires-Dist: mne
17
+ Requires-Dist: POT
18
+ Requires-Dist: nibabel
19
+ Requires-Dist: pyyaml
20
+ Requires-Dist: pyvistaqt
21
+ Requires-Dist: ipywidgets
22
+ Requires-Dist: PyQt5
23
+ Requires-Dist: scipy
24
+ Requires-Dist: h5py
25
+ Requires-Dist: matplotlib
26
+ Requires-Dist: joblib
27
+ Requires-Dist: myst-parser
28
+ Provides-Extra: dev
29
+ Requires-Dist: pytest==6.2.4; extra == "dev"
30
+ Provides-Extra: docs
31
+ Requires-Dist: sphinx<8.0.0,>=5.0.0; extra == "docs"
32
+ Requires-Dist: sphinx-rtd-theme>=1.0.1; extra == "docs"
33
+ Requires-Dist: pydata-sphinx-theme>=0.13.0; extra == "docs"
34
+ Requires-Dist: sphinx-autodoc-typehints>=1.19.0; extra == "docs"
35
+ Requires-Dist: sphinx-copybutton>=0.5.0; extra == "docs"
36
+ Requires-Dist: sphinx-gallery>=0.19.0; extra == "docs"
37
+ Dynamic: license-file
38
+
39
+ CaliBrain
40
+ =========
41
+
42
+ .. image:: https://img.shields.io/badge/PyPI%20downloads-not%20published-lightgrey
43
+ :target: https://pypi.org/project/calibrain/
44
+ :alt: PyPI version
45
+
46
+ .. image:: https://img.shields.io/pypi/pyversions/calibrain.svg
47
+ :target: https://pypi.org/project/calibrain/
48
+ :alt: Supported Python versions
49
+
50
+ .. image:: https://readthedocs.org/projects/calibrain/badge/?version=latest
51
+ :target: https://calibrain.readthedocs.io/en/latest/
52
+ :alt: Documentation status
53
+
54
+ .. image:: https://github.com/braindatalab/CaliBrain/actions/workflows/docs-check.yml/badge.svg
55
+ :target: https://github.com/braindatalab/CaliBrain/actions/workflows/docs-check.yml
56
+ :alt: Documentation build
57
+
58
+ .. image:: https://img.shields.io/pypi/l/calibrain.svg
59
+ :target: https://github.com/braindatalab/CaliBrain/blob/main/LICENSE
60
+ :alt: License
61
+
62
+ .. image:: https://img.shields.io/github/v/release/braindatalab/CaliBrain
63
+ :target: https://github.com/braindatalab/CaliBrain/releases
64
+ :alt: Latest GitHub release
65
+
66
+ .. image:: https://zenodo.org/badge/DOI/10.5281/zenodo.20703249.svg
67
+ :target: https://doi.org/10.5281/zenodo.20703249
68
+ :alt: DOI
69
+
70
+ CaliBrain is a Python package for simulation-based evaluation of uncertainty
71
+ estimation and calibration in EEG/MEG inverse source imaging. It combines
72
+ source and sensor simulation, inverse modeling, posterior uncertainty
73
+ extraction, and isotonic recalibration into a reproducible workflow for
74
+ comparing methods under controlled conditions.
75
+
76
+ Current workflow
77
+ ----------------
78
+
79
+ The current analysis pipeline is organized around explicit workflow scripts and
80
+ Python config files:
81
+
82
+ 1. ``calibrain/workflows/data_generation.py``
83
+ generates simulated runs, solves inverse problems, writes per-run HDF5
84
+ posterior summaries, and updates a manifest CSV.
85
+ 2. ``calibrain/workflows/aggregation.py``
86
+ reads the manifest, filters runs by metadata, and writes calibration-ready
87
+ NPZ datasets plus JSON sidecars.
88
+ 3. ``calibrain/workflows/calibration.py``
89
+ fits or evaluates isotonic recalibration maps and writes calibration JSON
90
+ summaries.
91
+ 4. ``calibrain/workflows/plot_paper_calibration_figures.py``
92
+ reads calibration JSON outputs and generates paper-style figures.
93
+
94
+ The workflow configs live in ``configs/``. Inspect and edit those files before
95
+ running large experiments, because they define solver grids, split definitions,
96
+ data paths, and output locations.
97
+
98
+ Core package components
99
+ -----------------------
100
+
101
+ * ``LeadfieldBuilder``: load or construct leadfield data.
102
+ * ``SourceSimulator`` and ``SensorSimulator``: simulate source activity and
103
+ sensor measurements.
104
+ * ``gamma_map_sflex``, ``gamma_lambda_map_sflex``, ``BMN``, and
105
+ ``BMN_joint``: inverse solvers.
106
+ * ``UncertaintyEstimator``: construct coverage curves for intervals,
107
+ ellipses, and ellipsoids.
108
+ * ``UncertaintyCalibrator``: fit isotonic nominal-coverage recalibration maps.
109
+ * ``MetricEvaluator``: compute calibration and source-space metrics.
110
+ * ``DataGenerator``: orchestrate simulation and posterior-summary generation.
111
+
112
+ Installation
113
+ ------------
114
+
115
+ From a local checkout:
116
+
117
+ .. code-block:: bash
118
+
119
+ git clone https://github.com/braindatalab/CaliBrain.git
120
+ cd CaliBrain
121
+ python -m pip install -e .
122
+
123
+ For documentation work:
124
+
125
+ .. code-block:: bash
126
+
127
+ python -m pip install -e ".[docs]"
128
+
129
+ The package metadata defines the distribution name as ``calibrain``. It is not
130
+ currently published on PyPI or conda-forge, so installation is presently from a
131
+ source checkout or a local environment specification such as ``environment.yml``.
132
+
133
+ Build documentation
134
+ -------------------
135
+
136
+ .. code-block:: bash
137
+
138
+ cd docs
139
+ make html
140
+
141
+ The rendered site is written to ``docs/build/html/index.html``.
142
+
143
+ Documentation
144
+ -------------
145
+
146
+ The redesigned documentation is under ``docs/source`` and is based on the
147
+ current source tree and workflow scripts. Executable tutorials in
148
+ ``tutorials/`` are rendered with Sphinx-Gallery during ``make html``.
149
+
150
+ The canonical published documentation is hosted on Read the Docs:
151
+ https://calibrain.readthedocs.io/
152
+
153
+ Citation
154
+ --------
155
+
156
+ If you use CaliBrain in academic work, please cite the software archive:
157
+
158
+ ``Orabe, M., Huseynov, I., Nagarajan, S., & Haufe, S. (2026). CaliBrain (v1.0.1). Zenodo. https://doi.org/10.5281/zenodo.20703249``
159
+
160
+ License
161
+ -------
162
+
163
+ CaliBrain is distributed under the BSD 3-Clause License. See ``LICENSE``.
@@ -0,0 +1,125 @@
1
+ CaliBrain
2
+ =========
3
+
4
+ .. image:: https://img.shields.io/badge/PyPI%20downloads-not%20published-lightgrey
5
+ :target: https://pypi.org/project/calibrain/
6
+ :alt: PyPI version
7
+
8
+ .. image:: https://img.shields.io/pypi/pyversions/calibrain.svg
9
+ :target: https://pypi.org/project/calibrain/
10
+ :alt: Supported Python versions
11
+
12
+ .. image:: https://readthedocs.org/projects/calibrain/badge/?version=latest
13
+ :target: https://calibrain.readthedocs.io/en/latest/
14
+ :alt: Documentation status
15
+
16
+ .. image:: https://github.com/braindatalab/CaliBrain/actions/workflows/docs-check.yml/badge.svg
17
+ :target: https://github.com/braindatalab/CaliBrain/actions/workflows/docs-check.yml
18
+ :alt: Documentation build
19
+
20
+ .. image:: https://img.shields.io/pypi/l/calibrain.svg
21
+ :target: https://github.com/braindatalab/CaliBrain/blob/main/LICENSE
22
+ :alt: License
23
+
24
+ .. image:: https://img.shields.io/github/v/release/braindatalab/CaliBrain
25
+ :target: https://github.com/braindatalab/CaliBrain/releases
26
+ :alt: Latest GitHub release
27
+
28
+ .. image:: https://zenodo.org/badge/DOI/10.5281/zenodo.20703249.svg
29
+ :target: https://doi.org/10.5281/zenodo.20703249
30
+ :alt: DOI
31
+
32
+ CaliBrain is a Python package for simulation-based evaluation of uncertainty
33
+ estimation and calibration in EEG/MEG inverse source imaging. It combines
34
+ source and sensor simulation, inverse modeling, posterior uncertainty
35
+ extraction, and isotonic recalibration into a reproducible workflow for
36
+ comparing methods under controlled conditions.
37
+
38
+ Current workflow
39
+ ----------------
40
+
41
+ The current analysis pipeline is organized around explicit workflow scripts and
42
+ Python config files:
43
+
44
+ 1. ``calibrain/workflows/data_generation.py``
45
+ generates simulated runs, solves inverse problems, writes per-run HDF5
46
+ posterior summaries, and updates a manifest CSV.
47
+ 2. ``calibrain/workflows/aggregation.py``
48
+ reads the manifest, filters runs by metadata, and writes calibration-ready
49
+ NPZ datasets plus JSON sidecars.
50
+ 3. ``calibrain/workflows/calibration.py``
51
+ fits or evaluates isotonic recalibration maps and writes calibration JSON
52
+ summaries.
53
+ 4. ``calibrain/workflows/plot_paper_calibration_figures.py``
54
+ reads calibration JSON outputs and generates paper-style figures.
55
+
56
+ The workflow configs live in ``configs/``. Inspect and edit those files before
57
+ running large experiments, because they define solver grids, split definitions,
58
+ data paths, and output locations.
59
+
60
+ Core package components
61
+ -----------------------
62
+
63
+ * ``LeadfieldBuilder``: load or construct leadfield data.
64
+ * ``SourceSimulator`` and ``SensorSimulator``: simulate source activity and
65
+ sensor measurements.
66
+ * ``gamma_map_sflex``, ``gamma_lambda_map_sflex``, ``BMN``, and
67
+ ``BMN_joint``: inverse solvers.
68
+ * ``UncertaintyEstimator``: construct coverage curves for intervals,
69
+ ellipses, and ellipsoids.
70
+ * ``UncertaintyCalibrator``: fit isotonic nominal-coverage recalibration maps.
71
+ * ``MetricEvaluator``: compute calibration and source-space metrics.
72
+ * ``DataGenerator``: orchestrate simulation and posterior-summary generation.
73
+
74
+ Installation
75
+ ------------
76
+
77
+ From a local checkout:
78
+
79
+ .. code-block:: bash
80
+
81
+ git clone https://github.com/braindatalab/CaliBrain.git
82
+ cd CaliBrain
83
+ python -m pip install -e .
84
+
85
+ For documentation work:
86
+
87
+ .. code-block:: bash
88
+
89
+ python -m pip install -e ".[docs]"
90
+
91
+ The package metadata defines the distribution name as ``calibrain``. It is not
92
+ currently published on PyPI or conda-forge, so installation is presently from a
93
+ source checkout or a local environment specification such as ``environment.yml``.
94
+
95
+ Build documentation
96
+ -------------------
97
+
98
+ .. code-block:: bash
99
+
100
+ cd docs
101
+ make html
102
+
103
+ The rendered site is written to ``docs/build/html/index.html``.
104
+
105
+ Documentation
106
+ -------------
107
+
108
+ The redesigned documentation is under ``docs/source`` and is based on the
109
+ current source tree and workflow scripts. Executable tutorials in
110
+ ``tutorials/`` are rendered with Sphinx-Gallery during ``make html``.
111
+
112
+ The canonical published documentation is hosted on Read the Docs:
113
+ https://calibrain.readthedocs.io/
114
+
115
+ Citation
116
+ --------
117
+
118
+ If you use CaliBrain in academic work, please cite the software archive:
119
+
120
+ ``Orabe, M., Huseynov, I., Nagarajan, S., & Haufe, S. (2026). CaliBrain (v1.0.1). Zenodo. https://doi.org/10.5281/zenodo.20703249``
121
+
122
+ License
123
+ -------
124
+
125
+ CaliBrain is distributed under the BSD 3-Clause License. See ``LICENSE``.
@@ -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.")