From fb21b7f73b4bb808d65d1c6925195570df11c0ef Mon Sep 17 00:00:00 2001 From: Aadhav Thaniga Date: Thu, 17 Sep 2026 16:23:01 -0400 Subject: [PATCH 1/9] read assembly path from LITCODER_LEBEL_ASSEMBLY env var --- train_simple.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/train_simple.py b/train_simple.py index 463bba9..6b46caa 100644 --- a/train_simple.py +++ b/train_simple.py @@ -1,6 +1,7 @@ #!/usr/bin/env python3 import logging +import os from encoding.assembly.assembly_loader import load_assembly from encoding.features.factory import FeatureExtractorFactory @@ -14,7 +15,10 @@ def main(): logger = logging.getLogger(__name__) # 1) Load the packaged assembly - assembly_path = "/storage/coda1/p-aivanova7/0/shared/litcoder_core/scripts/assembly_lebel_uts03.pkl" + assembly_path = os.environ.get( + "LITCODER_LEBEL_ASSEMBLY", + "/storage/coda1/p-aivanova7/0/shared/litcoder_core/scripts/assembly_lebel_uts03.pkl", + ) logger.info(f"Loading assembly from {assembly_path}") assembly = load_assembly(assembly_path) From 0a869dda1dc2d2665eeffd79005a56adddc460da Mon Sep 17 00:00:00 2001 From: Aadhav Thaniga Date: Thu, 17 Sep 2026 16:29:53 -0400 Subject: [PATCH 2/9] seed fold shuffling for reproducible splits --- encoding/models/folding.py | 29 ++++++++++++++++++++++------- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/encoding/models/folding.py b/encoding/models/folding.py index 23db8f1..60c27f1 100644 --- a/encoding/models/folding.py +++ b/encoding/models/folding.py @@ -12,6 +12,7 @@ def create_folds( chunk_length: Optional[int] = None, trim_size: Optional[int] = None, groups: Optional[np.ndarray] = None, + seed: int = 0, ) -> List[Tuple[List[int], List[int]]]: """Create train/test indices according to the specified folding strategy @@ -24,6 +25,7 @@ def create_folds( trim_size: Number of TRs to trim from beginning and end of test folds/chunks (used for 'chunked_trimmed' and 'kfold_trimmed' fold types) groups: Group labels for group-based folding + seed: Random seed for chunk shuffling, for reproducible folds Returns: List of (train_indices, test_indices) tuples @@ -31,17 +33,21 @@ def create_folds( print(f"THIS IS THE FOLDING TYPE: {fold_type} inside folding.py") if fold_type == "chunked": # Current chunked implementation with random shuffling - return create_chunked_folds(n_samples, n_folds, chunk_length, shuffle=True) + return create_chunked_folds( + n_samples, n_folds, chunk_length, shuffle=True, seed=seed + ) elif fold_type == "chunked_trimmed": # Chunked with trimmed test chunks to reduce autocorrelation if trim_size is None: trim_size = 5 # Default trim size of 5 TRs return create_chunked_folds_trimmed( - n_samples, n_folds, chunk_length, trim_size, shuffle=True + n_samples, n_folds, chunk_length, trim_size, shuffle=True, seed=seed ) elif fold_type == "chunked_contiguous": # Chunked but maintaining original order - return create_chunked_folds(n_samples, n_folds, chunk_length, shuffle=False) + return create_chunked_folds( + n_samples, n_folds, chunk_length, shuffle=False, seed=seed + ) elif fold_type == "kfold": # Regular KFold with shuffle=False for contiguity kf = KFold(n_splits=n_folds, shuffle=False) @@ -65,7 +71,11 @@ def create_folds( def create_chunked_folds( - n_samples: int, n_folds: int, chunk_length: int, shuffle: bool = True + n_samples: int, + n_folds: int, + chunk_length: int, + shuffle: bool = True, + seed: int = 0, ) -> List[Tuple[List[int], List[int]]]: """Create KFold splits that respect chunk structure of fMRI data. @@ -74,6 +84,7 @@ def create_chunked_folds( n_folds: Number of folds to create chunk_length: Length of chunks shuffle: Whether to shuffle chunks or keep them in original order + seed: Random seed for chunk shuffling, for reproducible folds Returns: List of (train_indices, test_indices) tuples @@ -83,7 +94,7 @@ def create_chunked_folds( chunk_indices = list(range(n_complete_chunks)) if shuffle: - random.shuffle(chunk_indices) + random.Random(seed).shuffle(chunk_indices) # Divide chunks evenly into n_folds chunks_per_fold = n_complete_chunks // n_folds @@ -92,7 +103,9 @@ def create_chunked_folds( logging.warning( "Not enough chunks for the requested folds, falling back to regular KFold" ) - kf = KFold(n_splits=n_folds, shuffle=shuffle) + kf = KFold( + n_splits=n_folds, shuffle=shuffle, random_state=seed if shuffle else None + ) return list(kf.split(range(n_samples))) # Create exactly n_folds splits @@ -130,6 +143,7 @@ def create_chunked_folds_trimmed( chunk_length: int, trim_size: int = 5, shuffle: bool = True, + seed: int = 0, ) -> List[Tuple[List[int], List[int]]]: """Create KFold splits with trimmed test chunks to reduce autocorrelation effects. @@ -144,6 +158,7 @@ def create_chunked_folds_trimmed( chunk_length: Length of chunks trim_size: Number of time points to trim from beginning and end of test chunks shuffle: Whether to shuffle chunks or keep them in original order + seed: Random seed for chunk shuffling, for reproducible folds Returns: List of (train_indices, test_indices) tuples @@ -153,7 +168,7 @@ def create_chunked_folds_trimmed( chunk_indices = list(range(n_complete_chunks)) if shuffle: - random.shuffle(chunk_indices) + random.Random(seed).shuffle(chunk_indices) # Divide chunks evenly into n_folds chunks_per_fold = n_complete_chunks // n_folds From 2fb909193ec2ca43d4f73e41b98d6e9c7797c0ec Mon Sep 17 00:00:00 2001 From: Aadhav Thaniga Date: Thu, 17 Sep 2026 16:51:42 -0400 Subject: [PATCH 3/9] add synthetic end-to-end test suite --- tests/conftest.py | 419 +++++++++++++++++++++ tests/test_pipeline_synthetic.py | 621 +++++++++++++++++++++++++++++++ 2 files changed, 1040 insertions(+) create mode 100644 tests/conftest.py create mode 100644 tests/test_pipeline_synthetic.py diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..abfd5a2 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,419 @@ +"""Shared fixtures for the synthetic end-to-end pipeline tests. + +The real LeBel assembly is ~3 GB and needs a GPU-ish machine to be useful. These +tests instead build a small assembly with the *same structural conventions* and a +signal planted at known FIR lags, so the whole extract -> downsample -> FIR -> +trim -> ridge path can be checked for correctness in seconds. + +Conventions copied from ``data/assembly_lebel_uts03.pkl`` (verified against all 25 +stories of that file): + +* ``len(split_indices) + 1 == len(tr_times)`` -- split_indices are *cut points* + into the word axis, consumed by ``np.split``, not a per-word TR label. +* ``brain_data.shape[0] == len(tr_times) - 15`` -- 10 TRs trimmed at the head and + 5 at the tail upstream of the assembly. +* ``len(words) == len(stimuli) == len(data_times) == n_words`` +* ``word_rates.shape == (n_trs, 1)`` +""" + +import os + +# Must happen before anything imports matplotlib/wandb (encoding.trainer pulls in +# encoding.plotting.plotting_utils, which imports matplotlib and nilearn at module +# scope). Belt and braces with the monkeypatching in _no_external_side_effects. +os.environ.setdefault("MPLBACKEND", "Agg") +os.environ.setdefault("WANDB_MODE", "disabled") +os.environ.setdefault("WANDB_SILENT", "true") +os.environ.setdefault("WANDB_DISABLED", "true") + +import hashlib +from dataclasses import dataclass, field +from typing import Dict, List, Optional, Tuple + +import numpy as np +import pytest + +from encoding.assembly.assemblies import SimpleNeuroidAssembly +from encoding.assembly.story_data import StoryData +from encoding.features.base import BaseFeatureExtractor +from encoding.features.embeddings import StaticEmbeddingFeatureExtractor + +# -------------------------------------------------------------------------- +# Constants mirroring the real LeBel assembly / train_simple.py +# -------------------------------------------------------------------------- + +N_VERTICES = 20484 # fsaverage5, both hemispheres +N_FEATURES = 4 # synthetic embedding dimensionality +N_SIGNAL_VERTICES = 10 # vertices 0..9 carry the planted signal +PLANTED_LAGS = (2, 3) # the "bump" in the planted FIR kernel +FIR_DELAYS = [1, 2, 3, 4] # delays the pipeline is run with +TR = 1.5 +BRAIN_TRIM_HEAD = 10 # TRs already removed from brain_data at the front +BRAIN_TRIM_TAIL = 5 # ... and at the back +BRAIN_TRIM_TOTAL = BRAIN_TRIM_HEAD + BRAIN_TRIM_TAIL + +# Same trimming used in train_simple.py for the LeBel dataset. +TRIMMING_CONFIG = { + "train_features_start": 10, + "train_features_end": -5, + "train_targets_start": 0, + "train_targets_end": None, + "test_features_start": 50, + "test_features_end": -5, + "test_targets_start": 40, + "test_targets_end": None, +} + + +# -------------------------------------------------------------------------- +# Deterministic token -> vector map (a stand-in for a static embedding model) +# -------------------------------------------------------------------------- + +def token_vector(token: str, dim: int = N_FEATURES) -> np.ndarray: + """Map a token to a fixed pseudo-random vector. + + Uses blake2b rather than ``hash()`` so the mapping is stable across processes + (Python salts str hashes per interpreter run). + """ + digest = hashlib.blake2b(token.encode("utf-8"), digest_size=8).digest() + seed = int.from_bytes(digest, "little") + return np.random.default_rng(seed).standard_normal(dim) + + +class SyntheticTokenFeatureExtractor(StaticEmbeddingFeatureExtractor): + """Word-level feature extractor that plugs into the real factory dispatch. + + Subclasses ``StaticEmbeddingFeatureExtractor`` so that + ``FeatureExtractorFactory._get_modality_from_extractor`` reports "embeddings" + and the factory feeds it ``assembly.get_words()[idx]`` (one entry per word). + The parent ``__init__`` is deliberately bypassed: it requires a gensim vector + file on disk, which is exactly what we are replacing. + + The class name must not contain "wordrate", or ``AbstractTrainer._should_downsample`` + would skip downsampling for it. + """ + + def __init__(self, dim: int = N_FEATURES): + BaseFeatureExtractor.__init__(self, {"model_name": "synthetic-tokens"}) + self.dim = dim + + def extract_features(self, stimuli, **kwargs) -> np.ndarray: + if isinstance(stimuli, str): + stimuli = stimuli.split() + return np.vstack([token_vector(tok, self.dim) for tok in stimuli]) + + +# -------------------------------------------------------------------------- +# Reference implementations -- deliberately independent of encoding/ +# -------------------------------------------------------------------------- + +def reference_legacy_average(word_features: np.ndarray, counts: np.ndarray) -> np.ndarray: + """Average word features per TR, given the number of words in each TR. + + Written from ``counts`` rather than from ``split_indices``/``np.split`` so it + is an independent oracle for LegacyAverageDownsampler rather than a restatement + of it. TRs with no words stay as zero rows, matching the library. + """ + out = np.zeros((len(counts), word_features.shape[1])) + pos = 0 + for i, c in enumerate(counts): + if c: + out[i] = word_features[pos:pos + c].mean(axis=0) + pos += c + return out + + +def reference_make_delayed(features: np.ndarray, delays) -> np.ndarray: + """Causal FIR expansion: block d of row t holds features[t - d], else zeros.""" + n_t, n_d = features.shape + blocks = [] + for d in delays: + block = np.zeros((n_t, n_d)) + if d > 0: + block[d:] = features[:-d] + elif d == 0: + block = features.copy() + else: + block[:d] = features[-d:] + blocks.append(block) + return np.hstack(blocks) + + +def column_correlations(a: np.ndarray, b: np.ndarray) -> np.ndarray: + """Pearson r between matching columns of two (n_samples, n_targets) matrices.""" + az = a - a.mean(axis=0) + bz = b - b.mean(axis=0) + denom = np.linalg.norm(az, axis=0) * np.linalg.norm(bz, axis=0) + out = np.zeros(a.shape[1]) + nz = denom > 0 + out[nz] = (az[:, nz] * bz[:, nz]).sum(axis=0) / denom[nz] + return out + + +def ridge_fit_predict(X_train, Y_train, X_test, alpha: float = 100.0) -> np.ndarray: + """Plain closed-form ridge; a fast stand-in for NestedCVModel in ablations.""" + n_feat = X_train.shape[1] + gram = X_train.T @ X_train + alpha * np.eye(n_feat) + weights = np.linalg.solve(gram, X_train.T @ Y_train) + return X_test @ weights + + +# -------------------------------------------------------------------------- +# Ground truth bundled alongside the assembly +# -------------------------------------------------------------------------- + +@dataclass +class StoryTruth: + """Everything a test needs to know about how one synthetic story was built.""" + + name: str + n_trs: int + n_words: int + counts: np.ndarray # words per TR, length n_trs + word_features: np.ndarray # (n_words, N_FEATURES) + tr_features: np.ndarray # (n_trs, N_FEATURES), the correct downsampling + empty_trs: np.ndarray # indices of TRs containing no words + + +@dataclass +class GroundTruth: + """Ground truth for the whole synthetic assembly.""" + + stories: Dict[str, StoryTruth] = field(default_factory=dict) + lag_weights: Dict[int, np.ndarray] = field(default_factory=dict) # lag -> (N_FEATURES, N_SIGNAL) + signal_vertices: np.ndarray = field(default_factory=lambda: np.arange(N_SIGNAL_VERTICES)) + noise_vertices: np.ndarray = field(default_factory=lambda: np.arange(N_SIGNAL_VERTICES, N_VERTICES)) + planted_lags: Tuple[int, ...] = PLANTED_LAGS + fir_delays: Tuple[int, ...] = tuple(FIR_DELAYS) + trimming_config: Dict = field(default_factory=lambda: dict(TRIMMING_CONFIG)) + + +# -------------------------------------------------------------------------- +# The fixture builder +# -------------------------------------------------------------------------- + +def synthetic_assembly( + n_stories: int = 3, + n_trs: Tuple[int, ...] = (200, 185, 210), + n_vertices: int = N_VERTICES, + n_features: int = N_FEATURES, + n_signal_vertices: int = N_SIGNAL_VERTICES, + planted_lags: Tuple[int, ...] = PLANTED_LAGS, + noise_ratio: float = 0.5, + max_words_per_tr: int = 12, + seed: int = 0, +) -> SimpleNeuroidAssembly: + """Build a small assembly with a signal planted at known FIR lags. + + The returned object is a real ``SimpleNeuroidAssembly`` and can be handed to + ``AbstractTrainer`` anywhere the LeBel assembly would go. Ground truth is + attached as ``assembly.truth`` (a :class:`GroundTruth`). + + How the signal is planted + ------------------------- + Per story, word-level features ``W`` are averaged into TR-level features ``F`` + using the legacy convention. Brain data is then + + brain[j, v] = sum_{d in planted_lags} F[j + BRAIN_TRIM_HEAD - d] @ lag_weights[d][:, v] + + for ``v`` in the first ``n_signal_vertices``, and pure noise elsewhere. + + The ``+ BRAIN_TRIM_HEAD`` offset is what makes the planting consistent with + ``TRIMMING_CONFIG``: the trainer pairs ``features[10:-5]`` with ``targets[0:]``, + so brain row ``j`` is aligned with feature row ``j + 10``, whose FIR block for + delay ``d`` holds ``F[j + 10 - d]``. Only *past* TRs are ever referenced, so the + construction is causal by design. + + Args: + n_stories: Number of stories. The last one becomes the held-out test story. + n_trs: Per-story TR counts (cycled if shorter than ``n_stories``). + noise_ratio: Noise std as a fraction of each signal vertex's own std. + 0.5 gives an achievable ceiling of r ~= 0.89. + max_words_per_tr: Words per TR are drawn uniformly from [0, this), so some + TRs are empty -- which is what exercises the zero-row path in the + legacy downsamplers. + """ + if n_stories < 2: + raise ValueError("need at least 2 stories for a train/test split") + if max(planted_lags) >= BRAIN_TRIM_HEAD: + raise ValueError("planted lags must be < BRAIN_TRIM_HEAD to stay in range") + + rng = np.random.default_rng(seed) + + # One shared set of lag weights, so the planted kernel is identical across stories. + lag_weights = { + lag: rng.standard_normal((n_features, n_signal_vertices)) + for lag in planted_lags + } + + truth = GroundTruth( + lag_weights=lag_weights, + signal_vertices=np.arange(n_signal_vertices), + noise_vertices=np.arange(n_signal_vertices, n_vertices), + planted_lags=tuple(planted_lags), + ) + + story_data_list: List[StoryData] = [] + + for s in range(n_stories): + story_rng = np.random.default_rng(seed + 1000 + s) + name = f"synthstory{s}" + n_tr = n_trs[s % len(n_trs)] + + # --- word/TR bookkeeping, legacy split_indices convention ------------- + counts = story_rng.integers(0, max_words_per_tr, size=n_tr) + # Mirror the real data: silence at the very start and end of a run. + counts[:3] = 0 + counts[-2:] = 0 + n_words = int(counts.sum()) + + # Cut points into the word axis: cumsum minus the final total, giving + # exactly n_tr - 1 entries so that np.split yields n_tr chunks. + split_indices = np.cumsum(counts)[:-1].astype(np.int64).tolist() + + words = [f"w{s}_{i}" for i in range(n_words)] + # Cumulative-context stimuli, one per word, as in the real assembly. + stimuli = [" ".join(words[max(0, i - 5):i + 1]) for i in range(n_words)] + + tr_times = np.arange(n_tr, dtype=np.float64) * TR + + # Word onsets spread inside their own TR, so data_times stays sorted. + data_times = np.empty(n_words, dtype=np.float64) + pos = 0 + for i, c in enumerate(counts): + if c: + offsets = np.sort(story_rng.uniform(0, TR, size=c)) + data_times[pos:pos + c] = tr_times[i] + offsets + pos += c + + word_features = np.vstack([token_vector(w, n_features) for w in words]) + tr_features = reference_legacy_average(word_features, counts) + + # --- plant the FIR signal -------------------------------------------- + n_brain = n_tr - BRAIN_TRIM_TOTAL + j = np.arange(n_brain) + signal = np.zeros((n_brain, n_signal_vertices)) + for lag in planted_lags: + signal += tr_features[j + BRAIN_TRIM_HEAD - lag] @ lag_weights[lag] + + brain = np.empty((n_brain, n_vertices), dtype=np.float64) + signal_std = signal.std(axis=0) + brain[:, :n_signal_vertices] = signal + story_rng.standard_normal( + (n_brain, n_signal_vertices) + ) * (signal_std * noise_ratio) + # Noise vertices get a comparable scale so nothing is separable by variance alone. + brain[:, n_signal_vertices:] = story_rng.standard_normal( + (n_brain, n_vertices - n_signal_vertices) + ) * float(np.median(signal_std)) + + truth.stories[name] = StoryTruth( + name=name, + n_trs=n_tr, + n_words=n_words, + counts=counts, + word_features=word_features, + tr_features=tr_features, + empty_trs=np.flatnonzero(counts == 0), + ) + + story_data_list.append( + StoryData( + name=name, + brain_data=brain, + stimuli=stimuli, + split_indices=split_indices, + tr_times=tr_times, + data_times=data_times, + temporal_baseline=None, + word_rates=counts.reshape(-1, 1).astype(np.float64), + words=words, + mask_indices=None, + audio_path=f"/nonexistent/audio/{name}.wav", + ) + ) + + assembly = SimpleNeuroidAssembly(story_data_list, validation_method="outer") + assembly.truth = truth + return assembly + + +# -------------------------------------------------------------------------- +# Fixtures +# -------------------------------------------------------------------------- + +class _NullLogger: + """Stand-in for WandBLogger/TensorBoardLogger that records calls in memory.""" + + def __init__(self, *args, **kwargs): + self.scalars: Dict[str, float] = {} + self.images: List[str] = [] + + def log_scalar(self, name, value, step=None): + self.scalars[name] = value + + def log_image(self, name, figure, step=None): + self.images.append(name) + + def log_histogram(self, name, values, step=None): + pass + + +class _NullBrainPlotter: + """Stand-in for BrainPlotter; the real one downloads fsaverage and renders 3D.""" + + def __init__(self, logger=None): + self.logger = logger + self.calls = 0 + + def log_plots(self, *args, **kwargs): + self.calls += 1 + + +@pytest.fixture(autouse=True) +def _no_external_side_effects(monkeypatch): + """Keep tests offline: no wandb run, no nilearn surface download, no GUI backend.""" + import matplotlib + matplotlib.use("Agg", force=True) + + import encoding.trainer as trainer_mod + + monkeypatch.setattr(trainer_mod, "WandBLogger", _NullLogger) + monkeypatch.setattr(trainer_mod, "TensorBoardLogger", _NullLogger) + monkeypatch.setattr(trainer_mod, "BrainPlotter", _NullBrainPlotter) + + # setup_logger calls wandb.init() directly before constructing WandBLogger. + import wandb + monkeypatch.setattr(wandb, "init", lambda *a, **k: None, raising=False) + monkeypatch.setattr(wandb, "log", lambda *a, **k: None, raising=False) + monkeypatch.setattr(wandb, "finish", lambda *a, **k: None, raising=False) + + # Last line of defence if a test reaches the real plotting utilities. + import encoding.plotting.plotting_utils as plotting_utils + monkeypatch.setattr( + plotting_utils.datasets, + "fetch_surf_fsaverage", + lambda *a, **k: pytest.fail("test tried to download fsaverage"), + raising=False, + ) + + +@pytest.fixture(scope="module") +def assembly() -> SimpleNeuroidAssembly: + """The synthetic assembly, built once per test module.""" + return synthetic_assembly() + + +@pytest.fixture(scope="module") +def truth(assembly) -> GroundTruth: + return assembly.truth + + +@pytest.fixture +def extractor() -> SyntheticTokenFeatureExtractor: + return SyntheticTokenFeatureExtractor() + + +@pytest.fixture +def downsample_config() -> Dict: + """legacy_average is the only averaging method that reads split_indices correctly.""" + return {"method": "legacy_average"} diff --git a/tests/test_pipeline_synthetic.py b/tests/test_pipeline_synthetic.py new file mode 100644 index 0000000..e2830c1 --- /dev/null +++ b/tests/test_pipeline_synthetic.py @@ -0,0 +1,621 @@ +"""End-to-end tests for the encoding pipeline against a synthetic assembly. + +Three groups: + +* **Structural** -- the assembly obeys the same conventions as the real LeBel + assembly, and each stage transforms shapes the way the next stage expects. +* **Recovery** -- a signal planted at FIR lags 2 and 3 in vertices 0..9 is + recovered by the real pipeline, at the right lags and in the right vertices. +* **Leakage / ordering** -- the held-out story cannot reach the training matrix, + the FIR expansion is causal, and the recovered correlation genuinely depends on + temporal alignment rather than on some artefact of the plumbing. + +Everything runs offline: no wandb run, no fsaverage download, Agg backend. See +``conftest._no_external_side_effects``. +""" + +import numpy as np +import pytest + +from conftest import ( + BRAIN_TRIM_HEAD, + BRAIN_TRIM_TAIL, + BRAIN_TRIM_TOTAL, + FIR_DELAYS, + N_FEATURES, + N_SIGNAL_VERTICES, + N_VERTICES, + PLANTED_LAGS, + TR, + TRIMMING_CONFIG, + SyntheticTokenFeatureExtractor, + column_correlations, + reference_legacy_average, + reference_make_delayed, + ridge_fit_predict, + synthetic_assembly, + _NullBrainPlotter, + _NullLogger, +) + +from encoding.downsample.downsampling import Downsampler +from encoding.features.FIR_expander import FIR +from encoding.models.nested_cv import NestedCVModel +from encoding.trainer import AbstractTrainer + +# Keep the nested CV cheap; the point is correctness, not hyperparameter search. +MODEL_KWARGS = dict(alphas=[1.0, 10.0, 100.0, 1000.0], n_inner_folds=2, use_gpu=False) + + +# -------------------------------------------------------------------------- +# Helpers +# -------------------------------------------------------------------------- + +def make_trainer(assembly, results_dir, **overrides): + """Build an AbstractTrainer wired the way train_simple.py wires it.""" + kwargs = dict( + assembly=assembly, + feature_extractors=[SyntheticTokenFeatureExtractor()], + downsampler=Downsampler(), + model=NestedCVModel(model_name="ridge_regression"), + fir_delays=FIR_DELAYS, + trimming_config=dict(TRIMMING_CONFIG), + use_train_test_split=True, + logger_backend="wandb", + dataset_type="synthetic", + results_dir=str(results_dir), + downsample_config={"method": "legacy_average"}, + ) + kwargs.update(overrides) + return AbstractTrainer(**kwargs) + + +@pytest.fixture(scope="module") +def pipeline_data(assembly, tmp_path_factory): + """Run extract -> downsample -> FIR -> structure once and reuse it. + + Module-scoped, so the function-scoped autouse patching in conftest is not yet + active; patch explicitly for the duration of trainer construction. + """ + results_dir = tmp_path_factory.mktemp("results") + with pytest.MonkeyPatch.context() as mp: + import encoding.trainer as trainer_mod + import wandb + + mp.setattr(trainer_mod, "WandBLogger", _NullLogger) + mp.setattr(trainer_mod, "BrainPlotter", _NullBrainPlotter) + mp.setattr(wandb, "init", lambda *a, **k: None, raising=False) + + trainer = make_trainer(assembly, results_dir) + features = trainer.extract_and_downsample_features() + delayed = trainer.apply_fir_delays(features) + data = trainer.structure_data(delayed) + + return { + "trainer": trainer, + "features": features, + "delayed": delayed, + "data": data, + "results_dir": results_dir, + } + + +@pytest.fixture(scope="module") +def fitted(pipeline_data): + """The nested-CV ridge fit. One fit shared by the recovery tests.""" + data = pipeline_data["data"] + model = pipeline_data["trainer"].model + metrics, weights, alphas = model.fit_predict( + features=data["Rstim"], + targets=data["Rresp"], + X_test=data["Pstim"], + y_test=data["Presp"], + **MODEL_KWARGS, + ) + return {"metrics": metrics, "weights": weights, "alphas": alphas} + + +# ========================================================================== +# Structural +# ========================================================================== + +def test_assembly_top_level_structure(assembly): + """Top-level attributes mirror SimpleNeuroidAssembly's contract.""" + assert assembly.stories == ["synthstory0", "synthstory1", "synthstory2"] + assert assembly.dims == ("presentation", "neuroid") + assert assembly.get_validation_method() == "outer" + assert set(assembly.story_data) == set(assembly.stories) + + expected_rows = sum(sd.brain_data.shape[0] for sd in assembly.story_data.values()) + assert assembly.shape == (expected_rows, N_VERTICES) + assert assembly.data.shape == assembly.shape + + +def test_story_field_shapes_match_lebel_conventions(assembly, truth): + """Word-clock fields agree with each other; TR-clock fields agree with each other.""" + for name in assembly.stories: + sd = assembly.story_data[name] + st = truth.stories[name] + + # Word clock: one entry per word. + assert len(sd.words) == st.n_words + assert len(sd.stimuli) == st.n_words + assert sd.data_times.shape == (st.n_words,) + + # TR clock: one entry per TR. + assert sd.tr_times.shape == (st.n_trs,) + assert sd.word_rates.shape == (st.n_trs, 1) + + # Brain data is 15 TRs shorter: 10 trimmed at the head, 5 at the tail. + assert sd.brain_data.shape == (st.n_trs - BRAIN_TRIM_TOTAL, N_VERTICES) + + # Optional fields, as in the packaged LeBel assembly. + assert sd.temporal_baseline is None + assert sd.mask_indices is None + + # Word onsets are sorted and land inside the run. + assert np.all(np.diff(sd.data_times) > 0) + assert sd.data_times.min() >= sd.tr_times[0] + assert sd.data_times.max() < sd.tr_times[-1] + TR + + +def test_split_indices_are_legacy_cut_points(assembly, truth): + """split_indices are np.split cut points into the word axis, not per-word labels. + + This is the invariant that holds for all 25 stories of the real assembly: + len(split_indices) + 1 == len(tr_times). + """ + for name in assembly.stories: + sd = assembly.story_data[name] + st = truth.stories[name] + si = np.asarray(sd.split_indices) + + assert si.size + 1 == len(sd.tr_times) + assert np.all(np.diff(si) >= 0), "cut points must be non-decreasing" + assert si.min() >= 0 + assert si.max() <= st.n_words + # Empty TRs show up as repeated cut points, not as missing entries. + assert np.unique(si).size < si.size + + +def test_legacy_average_matches_independent_reference(assembly, truth): + """LegacyAverageDownsampler == averaging each TR's words, computed from counts.""" + ds = Downsampler() + for name in assembly.stories: + sd = assembly.story_data[name] + st = truth.stories[name] + + out = ds.downsample( + data=st.word_features, + data_times=sd.data_times, + tr_times=sd.tr_times, + method="legacy_average", + split_indices=sd.split_indices, + ) + assert out.shape == (st.n_trs, N_FEATURES) + np.testing.assert_allclose(out, reference_legacy_average(st.word_features, st.counts)) + + +def test_legacy_average_leaves_empty_trs_as_zero_rows(assembly, truth): + """TRs with no words come back as exact zero rows, not NaN and not interpolated. + + Worth pinning: a silent TR is indistinguishable from a genuinely zero feature, + so downstream code must not treat "all zero" as missing data. + """ + ds = Downsampler() + name = assembly.stories[0] + sd = assembly.story_data[name] + st = truth.stories[name] + + out = ds.downsample( + data=st.word_features, + data_times=sd.data_times, + tr_times=sd.tr_times, + method="legacy_average", + split_indices=sd.split_indices, + ) + + assert st.empty_trs.size > 0, "fixture should contain some silent TRs" + assert np.all(out[st.empty_trs] == 0.0) + assert np.isfinite(out).all() + + occupied = np.setdiff1d(np.arange(st.n_trs), st.empty_trs) + assert np.any(out[occupied] != 0.0) + + +@pytest.mark.parametrize("method", ["legacy_average", "legacy_sum", "legacy_last"]) +def test_legacy_downsamplers_return_one_row_per_tr(assembly, truth, method): + """All three legacy methods use np.split, so all produce len(split_indices)+1 rows.""" + ds = Downsampler() + name = assembly.stories[0] + sd = assembly.story_data[name] + st = truth.stories[name] + + out = ds.downsample( + data=st.word_features, + data_times=sd.data_times, + tr_times=sd.tr_times, + method=method, + split_indices=sd.split_indices, + ) + assert out.shape == (st.n_trs, N_FEATURES) + assert out.shape[0] == len(sd.split_indices) + 1 + + +@pytest.mark.parametrize("method", ["average", "sum", "last"]) +def test_nonlegacy_downsamplers_misread_split_indices(assembly, truth, method): + """Pin a known bug: the non-legacy methods read split_indices as per-word TR labels. + + They compute ``max(split_indices) + 1`` rows, which for this convention is + roughly the word count rather than the TR count. Only the ``legacy_*`` methods + are usable with these assemblies. If this test ever fails because the output is + now (n_trs, ...), the bug has been fixed and this test should become the + positive assertion instead. + """ + ds = Downsampler() + name = assembly.stories[0] + sd = assembly.story_data[name] + st = truth.stories[name] + + out = ds.downsample( + data=st.word_features, + data_times=sd.data_times, + tr_times=sd.tr_times, + method=method, + split_indices=sd.split_indices, + ) + assert out.shape[0] == max(sd.split_indices) + 1 + assert out.shape[0] != st.n_trs + assert out.shape[0] > st.n_trs + + +@pytest.mark.parametrize( + "method", ["legacy_average", "legacy_sum", "legacy_last", "average", "sum", "last"] +) +def test_downsamplers_require_split_indices(assembly, truth, method): + """Omitting split_indices is a loud error, not a silent fallback.""" + ds = Downsampler() + sd = assembly.story_data[assembly.stories[0]] + st = truth.stories[assembly.stories[0]] + + with pytest.raises(ValueError, match="split_indices"): + ds.downsample( + data=st.word_features, + data_times=sd.data_times, + tr_times=sd.tr_times, + method=method, + ) + + +def test_fir_expansion_matches_reference(assembly, truth): + """FIR.make_delayed stacks one block per delay, in the order given.""" + st = truth.stories[assembly.stories[0]] + delayed = FIR.make_delayed(st.tr_features, FIR_DELAYS) + + assert delayed.shape == (st.n_trs, N_FEATURES * len(FIR_DELAYS)) + np.testing.assert_allclose(delayed, reference_make_delayed(st.tr_features, FIR_DELAYS)) + + # Block d holds features shifted forward by d, zero-padded at the front. + for block, d in enumerate(FIR_DELAYS): + cols = slice(block * N_FEATURES, (block + 1) * N_FEATURES) + assert np.all(delayed[:d, cols] == 0.0) + np.testing.assert_allclose(delayed[d:, cols], st.tr_features[:-d]) + + +def test_structure_data_shapes_and_story_split(pipeline_data, assembly, truth): + """Trimming pairs features with targets row-for-row, and the last story is held out.""" + features = pipeline_data["features"] + delayed = pipeline_data["delayed"] + data = pipeline_data["data"] + + for name in assembly.stories: + st = truth.stories[name] + assert features[name].shape == (st.n_trs, N_FEATURES) + assert delayed[name].shape == (st.n_trs, N_FEATURES * len(FIR_DELAYS)) + + train_stories = assembly.stories[:-1] + test_story = assembly.stories[-1] + + expected_train = sum(truth.stories[s].n_trs - BRAIN_TRIM_TOTAL for s in train_stories) + expected_test = truth.stories[test_story].n_trs - ( + TRIMMING_CONFIG["test_features_start"] + BRAIN_TRIM_TAIL + ) + + assert data["Rstim"].shape == (expected_train, N_FEATURES * len(FIR_DELAYS)) + assert data["Rresp"].shape == (expected_train, N_VERTICES) + assert data["Pstim"].shape == (expected_test, N_FEATURES * len(FIR_DELAYS)) + assert data["Presp"].shape == (expected_test, N_VERTICES) + + # Features and targets must line up row-for-row, which nothing in + # _create_train_test_split actually checks. + assert data["Rstim"].shape[0] == data["Rresp"].shape[0] + assert data["Pstim"].shape[0] == data["Presp"].shape[0] + assert np.isfinite(data["Rstim"]).all() + assert np.isfinite(data["Pstim"]).all() + + +# ========================================================================== +# Recovery +# ========================================================================== + +def test_recovers_planted_signal_vertices(fitted, truth): + """Vertices 0..9 carry the planted signal and should be predicted well.""" + correlations = np.asarray(fitted["metrics"]["correlations"]) + assert correlations.shape == (N_VERTICES,) + + signal_r = correlations[truth.signal_vertices] + # Ceiling is ~0.89 at the fixture's default noise_ratio of 0.5. + assert np.median(signal_r) > 0.75 + assert signal_r.min() > 0.6 + + +def test_noise_vertices_are_not_predicted(fitted, truth): + """Everything past vertex 9 is noise and must not be predictable.""" + correlations = np.asarray(fitted["metrics"]["correlations"]) + noise_r = np.abs(correlations[truth.noise_vertices]) + + assert np.median(noise_r) < 0.12 + assert np.percentile(noise_r, 99) < 0.35 + # And the signal vertices must stand clearly apart from the noise floor. + signal_r = correlations[truth.signal_vertices] + assert signal_r.min() > np.percentile(noise_r, 99.9) + + +def test_fdr_selects_the_planted_vertices(fitted, truth): + """FDR correction should flag the planted vertices and few others.""" + significant = np.asarray(fitted["metrics"]["significant_mask"], dtype=bool) + assert significant[truth.signal_vertices].all() + # Allow a handful of false positives, but nothing like a whole-brain flag. + assert significant.sum() < 5 * N_SIGNAL_VERTICES + + +def test_recovered_kernel_peaks_at_planted_lags(fitted, truth): + """The learned FIR kernel bumps at lags 2 and 3, and is flat at lags 1 and 4.""" + weights = fitted["weights"] + assert weights.shape == (N_FEATURES * len(FIR_DELAYS), N_VERTICES) + + # (n_delays, n_features, n_vertices) -- make_delayed hstacks blocks in delay order. + by_lag = weights.reshape(len(FIR_DELAYS), N_FEATURES, N_VERTICES) + signal_norms = { + delay: float(np.linalg.norm(by_lag[i][:, truth.signal_vertices])) + for i, delay in enumerate(FIR_DELAYS) + } + + planted = [signal_norms[d] for d in PLANTED_LAGS] + empty = [signal_norms[d] for d in FIR_DELAYS if d not in PLANTED_LAGS] + + assert min(planted) > 3 * max(empty), ( + f"kernel did not peak at lags {PLANTED_LAGS}: {signal_norms}" + ) + + # Noise vertices should have no structured kernel at all. + noise_norm = float(np.linalg.norm(by_lag[:, :, truth.noise_vertices])) + per_vertex_noise = noise_norm / np.sqrt(len(truth.noise_vertices)) + per_vertex_signal = min(planted) / np.sqrt(N_SIGNAL_VERTICES) + assert per_vertex_signal > per_vertex_noise + + +def test_trainer_train_runs_offline_and_reports_metrics(assembly, tmp_path): + """trainer.train() end to end, with logging and brain plotting stubbed out.""" + trainer = make_trainer(assembly, tmp_path) + assert isinstance(trainer.experiment_logger, _NullLogger) + assert isinstance(trainer.brain_plotter, _NullBrainPlotter) + + metrics = trainer.train(**MODEL_KWARGS) + + correlations = np.asarray(metrics["correlations"]) + assert np.median(correlations[:N_SIGNAL_VERTICES]) > 0.75 + assert metrics["median_score"] == pytest.approx(float(np.median(correlations))) + assert 0 < metrics["n_significant"] < 5 * N_SIGNAL_VERTICES + + # Metrics reached the logger and the plotter was invoked but drew nothing. + assert "median_correlation" in trainer.experiment_logger.scalars + assert trainer.brain_plotter.calls == 1 + + # ModelSaver wrote under the temp results dir, not into the repo. + assert any(tmp_path.rglob("hyperparams.json")) + + +# ========================================================================== +# Leakage and ordering +# ========================================================================== + +def test_fir_is_causal(assembly, truth): + """No delay is negative, and perturbing TR t never changes rows before t.""" + assert all(d > 0 for d in FIR_DELAYS), "a delay <= 0 would expose the present/future" + + st = truth.stories[assembly.stories[0]] + base = FIR.make_delayed(st.tr_features, FIR_DELAYS) + + perturb_at = st.n_trs // 2 + bumped = st.tr_features.copy() + bumped[perturb_at] += 1000.0 + after = FIR.make_delayed(bumped, FIR_DELAYS) + + changed_rows = np.flatnonzero(np.any(base != after, axis=1)) + assert changed_rows.size > 0 + assert changed_rows.min() > perturb_at, ( + "a future timepoint leaked into an earlier delayed row" + ) + # Only the planted delays' worth of rows should move. + assert set(changed_rows.tolist()) == {perturb_at + d for d in FIR_DELAYS} + + +def test_held_out_story_cannot_influence_training_matrix(pipeline_data, assembly): + """Corrupting the held-out story leaves the training matrices bit-identical. + + Poisoning is a sharper check than comparing row counts: if any test-story value + reached X_train or Y_train, the training matrices would move. Both the features + and the brain data of the held-out story are corrupted, so the check covers + predictors and targets. + """ + trainer = pipeline_data["trainer"] + baseline = pipeline_data["data"] + test_story = assembly.stories[-1] + + poisoned = {k: v.copy() for k, v in pipeline_data["delayed"].items()} + poisoned[test_story][:] = np.nan + + story = assembly.story_data[test_story] + clean_brain = story.brain_data + try: + story.brain_data = np.full_like(clean_brain, np.nan) + data = trainer.structure_data(poisoned) + finally: + story.brain_data = clean_brain + + assert np.isfinite(data["Rstim"]).all() + assert np.isfinite(data["Rresp"]).all() + np.testing.assert_array_equal(data["Rstim"], baseline["Rstim"]) + np.testing.assert_array_equal(data["Rresp"], baseline["Rresp"]) + + # The poison did land on the test side, so the check above is not vacuous. + assert not np.array_equal(data["Pstim"], baseline["Pstim"]) + assert np.isnan(data["Presp"]).all() + + +def test_nan_features_are_silently_zeroed(pipeline_data, assembly): + """Pin a silent-failure path: NaN *features* are laundered by np.nan_to_num. + + _create_train_test_split wraps X_train/X_test in np.nan_to_num but leaves + Y_train/Y_test alone. A feature extractor that starts emitting NaN therefore + produces an all-zero predictor block and a plausible-looking fit instead of an + error, while the same corruption in the targets propagates loudly. + """ + trainer = pipeline_data["trainer"] + test_story = assembly.stories[-1] + + poisoned = {k: v.copy() for k, v in pipeline_data["delayed"].items()} + poisoned[test_story][:] = np.nan + + data = trainer.structure_data(poisoned) + + assert np.all(data["Pstim"] == 0.0), "NaN features are converted to zeros, not raised" + assert np.isfinite(data["Presp"]).all() + + +def test_train_and_test_draw_from_disjoint_stories(pipeline_data, assembly, truth): + """The split is by story: the last one is test, everything before it is train.""" + trainer = pipeline_data["trainer"] + stories = list(pipeline_data["features"].keys()) + + assert stories == assembly.stories + train_stories, test_stories = stories[:-1], stories[-1:] + assert set(train_stories).isdisjoint(test_stories) + assert len(test_stories) == 1 + + # Row budget accounts for every train row, leaving no room for test rows. + expected = sum(truth.stories[s].n_trs - BRAIN_TRIM_TOTAL for s in train_stories) + assert pipeline_data["data"]["Rstim"].shape[0] == expected + + +def test_each_split_is_zscored_independently(pipeline_data, assembly): + """z-scoring happens per story within a split; train data cannot shift the test set. + + Note this also documents that the *test* split is standardised with its own + statistics rather than the training set's -- standard in this literature, but + it is test-set information entering the test features, so it is pinned here + deliberately rather than by accident. + """ + trainer = pipeline_data["trainer"] + delayed = pipeline_data["delayed"] + baseline = pipeline_data["data"] + + scaled = {k: v.copy() for k, v in delayed.items()} + for story in assembly.stories[:-1]: + scaled[story] = scaled[story] * 50.0 + 7.0 + + data = trainer.structure_data(scaled) + + # Test split untouched by the train-side rescaling. + np.testing.assert_allclose(data["Pstim"], baseline["Pstim"]) + # And z-scoring makes the train split invariant to affine rescaling. + np.testing.assert_allclose(data["Rstim"], baseline["Rstim"], atol=1e-8) + + # Each split is standardised with its own statistics. + assert np.allclose(baseline["Pstim"].mean(axis=0), 0.0, atol=1e-8) + assert np.allclose(baseline["Pstim"].std(axis=0), 1.0, atol=1e-6) + + +def test_alignment_is_load_bearing(pipeline_data, truth): + """Break the temporal alignment and the recovered correlation collapses. + + Guards against a result that looks good for the wrong reason: if prediction + survived an arbitrary time shift, the correlation would be coming from + something other than the planted lag structure. + """ + data = pipeline_data["data"] + signal = truth.signal_vertices + + aligned = ridge_fit_predict(data["Rstim"], data["Rresp"][:, signal], data["Pstim"]) + aligned_r = column_correlations(aligned, data["Presp"][:, signal]) + assert np.median(aligned_r) > 0.7 + + # A shift well outside the delay set, so no lag can absorb it. + shift = 37 + rolled_train = np.roll(data["Rstim"], shift, axis=0) + rolled_test = np.roll(data["Pstim"], shift, axis=0) + rolled = ridge_fit_predict(rolled_train, data["Rresp"][:, signal], rolled_test) + rolled_r = column_correlations(rolled, data["Presp"][:, signal]) + + assert np.median(np.abs(rolled_r)) < 0.2 + assert np.median(aligned_r) > 3 * np.median(np.abs(rolled_r)) + + +def test_pipeline_order_is_downsample_then_fir(pipeline_data, assembly, truth): + """Downsampling must precede FIR expansion; the row counts pin the order. + + Expanding word-level features first would give one row per word and silently + misalign everything downstream, so the two orders are not interchangeable. + """ + features = pipeline_data["features"] + delayed = pipeline_data["delayed"] + + for name in assembly.stories: + st = truth.stories[name] + + assert features[name].shape[0] == st.n_trs + assert features[name].shape[0] != st.n_words + + assert delayed[name].shape == (st.n_trs, N_FEATURES * len(FIR_DELAYS)) + + # The other order produces a word-length matrix that cannot pair with brain data. + fir_first = FIR.make_delayed(st.word_features, FIR_DELAYS) + assert fir_first.shape[0] == st.n_words + assert fir_first.shape[0] != assembly.story_data[name].brain_data.shape[0] + + +def test_trimming_config_pairs_features_with_past_tr_only(truth): + """The trimming offsets keep every predictor at or before its target's TR. + + Brain row j is paired with feature row j + 10, whose planted lags point at TRs + j + 8 and j + 7. Both precede the feature TR, so no target is predicted from + its own future. + """ + feature_offset = TRIMMING_CONFIG["train_features_start"] + target_offset = TRIMMING_CONFIG["train_targets_start"] + assert feature_offset - target_offset == BRAIN_TRIM_HEAD + + for lag in PLANTED_LAGS: + source_tr = feature_offset - lag + assert 0 <= source_tr < feature_offset, "predictor must come from a past TR" + + # The test split uses different offsets but must preserve the same relationship. + assert ( + TRIMMING_CONFIG["test_features_start"] - TRIMMING_CONFIG["test_targets_start"] + == BRAIN_TRIM_HEAD + ) + assert TRIMMING_CONFIG["train_features_end"] == -BRAIN_TRIM_TAIL + assert TRIMMING_CONFIG["test_features_end"] == -BRAIN_TRIM_TAIL + + +def test_fixture_is_deterministic(): + """Same seed, same assembly -- so a failure is reproducible.""" + a = synthetic_assembly(n_stories=2, n_trs=(60, 60), n_vertices=64, seed=3) + b = synthetic_assembly(n_stories=2, n_trs=(60, 60), n_vertices=64, seed=3) + + for name in a.stories: + np.testing.assert_array_equal( + a.story_data[name].brain_data, b.story_data[name].brain_data + ) + assert a.story_data[name].split_indices == b.story_data[name].split_indices From a217253665b942e0f8b2f92c109110b900b249bd Mon Sep 17 00:00:00 2001 From: Aadhav Thaniga Date: Thu, 17 Sep 2026 18:13:49 -0400 Subject: [PATCH 4/9] add golden regression test with measured tolerances --- tests/fixtures/golden_lebel_uts03.json | 157 +++++++++ tests/test_golden_lebel.py | 429 +++++++++++++++++++++++++ tests/test_pipeline_synthetic.py | 54 ++++ 3 files changed, 640 insertions(+) create mode 100644 tests/fixtures/golden_lebel_uts03.json create mode 100644 tests/test_golden_lebel.py diff --git a/tests/fixtures/golden_lebel_uts03.json b/tests/fixtures/golden_lebel_uts03.json new file mode 100644 index 0000000..b79c872 --- /dev/null +++ b/tests/fixtures/golden_lebel_uts03.json @@ -0,0 +1,157 @@ +{ + "fixture": { + "file": "assembly_lebel_uts03.pkl", + "md5": "9bec82d87d528ca0e68e421c3c73136e", + "source": "Google Drive link in README", + "env_var": "LITCODER_LEBEL_ASSEMBLY" + }, + "run": { + "date": "2026-09-17", + "commit": "a53ee0f9d989e218b98b528b69588c2ce5497273", + "script": "train_simple.py", + "machine": "macOS, Apple Silicon, MPS (linalg_svd falls back to CPU)", + "env": "conda env 'litcoder'", + "fit_seconds": 14.5, + "fold_seed": 0 + }, + "environment": { + "note": "Tolerances are chosen strict when this fingerprint matches the running environment exactly, loose otherwise. See tolerances.rationale.", + "fingerprint": { + "platform_system": "Darwin", + "platform_machine": "arm64", + "torch": "2.13.0", + "numpy": "2.4.6", + "scipy": "1.18.0", + "device": "mps:0", + "torch_threads": 4 + } + }, + "config": { + "extractor": "wordrate", + "fir_delays": [ + 1, + 2, + 3, + 4 + ], + "folding_type": "chunked", + "n_inner_folds": 5, + "chunk_length": 20, + "alphas": "np.logspace(-1, 8, 10) (fit_predict default)", + "downsampler": "default (rect; wordrate is not downsampled)", + "trimming_config": { + "train_features_start": 10, + "train_features_end": -5, + "train_targets_start": 0, + "train_targets_end": null, + "test_features_start": 50, + "test_features_end": -5, + "test_targets_start": 40, + "test_targets_end": null + } + }, + "shapes": { + "X_train": [ + 8673, + 4 + ], + "Y_train": [ + 8673, + 20484 + ], + "X_test": [ + 251, + 4 + ], + "Y_test": [ + 251, + 20484 + ] + }, + "metrics": { + "median_score": 0.042643629, + "n_significant": 2867, + "n_voxels": 20484 + }, + "quantiles": { + "1": -0.1695338935, + "5": -0.1018701419, + "25": -0.0154135684, + "50": 0.042643629, + "75": 0.1100961417, + "90": 0.1946224123, + "95": 0.2598253787, + "99": 0.4205047786 + }, + "threshold_counts": { + "0.1": 5721, + "0.2": 1924 + }, + "tolerances": { + "quantile_atol_strict": 1e-05, + "quantile_atol_loose": 0.002, + "count_rtol_strict": 0.01, + "count_rtol_loose": 0.05, + "rationale": "Derived from measurement, not from the two historical runs. Across four configurations of the same input (two processes on CPU, one on MPS, one with torch 2.11/numpy 1.26/scipy 1.13) the largest spread of any asserted quantile was 2.4e-07, and n_significant was identical (2867) in all four. Strict quantile atol of 1e-5 is ~40x that observed spread and ~1x the mean spacing of the correlation distribution near the median, so a single voxel changing rank cannot trip it. Loose atol of 2e-3 covers the regime where per-voxel correlations move by 1e-3; real regressions (misaligned trimming, wrong downsampler, wrong FIR window) move quantiles by 1e-2 or more, so the loose band still catches them with an order of magnitude to spare. Counts are banded rather than exact because FDR thresholding is an order statistic with a cascade (see measured_variance.bh_cutoff)." + }, + "measured_variance": { + "method": "Same persisted train/test matrices fed to NestedCVModel.fit_predict under four configurations.", + "cpu_process_1_vs_process_2": { + "bitwise_identical": true, + "max_abs_dr": 0.0, + "delta_median": 0.0, + "alpha_flips": 0, + "significance_flips": 0 + }, + "cpu_vs_mps": { + "bitwise_identical": false, + "max_abs_dr": 6.654e-06, + "p99_abs_dr": 4.321e-07, + "delta_median": 0.0, + "alpha_flips": 0, + "significance_flips": 0 + }, + "cross_library_torch_2_11_numpy_1_26_scipy_1_13": { + "bitwise_identical": false, + "max_abs_dr": 1.067e-07, + "delta_median": 4.717e-09, + "alpha_flips": 0, + "significance_flips": 0 + }, + "max_quantile_spread_across_all_four": 2.384e-07, + "correlation_spacing_at_median": { + "adjacent_gap": 4.247e-07, + "mean_gap_within_100_ranks": 9.449e-06, + "max_gap_within_100_ranks": 6.757e-05 + }, + "bh_cutoff": { + "alpha": 0.05, + "p_at_cutoff": 0.006986395, + "bh_step_alpha_over_m": 2.441e-06, + "gap_to_next_p_value": 2.414e-05, + "voxels_within_one_bh_index_step": 1, + "n_significant_swing_for_uniform_r_shift": { + "1e-05": 0, + "0.0001": 10, + "0.001": 59 + } + }, + "threshold_count_swing_for_uniform_r_shift": { + "r_gt_0.1": { + "1e-05": 0, + "0.0001": 16, + "0.001": 128 + }, + "r_gt_0.2": { + "1e-05": 1, + "0.0001": 4, + "0.001": 44 + } + } + }, + "regeneration": { + "command": "LITCODER_LEBEL_ASSEMBLY=/path/to/assembly_lebel_uts03.pkl python tests/test_golden_lebel.py --update", + "when": "Run this only when a change to the pipeline is intended. It rewrites metrics, quantiles, threshold_counts, shapes and the environment fingerprint from a fresh run, and leaves tolerances and notes alone. Review the diff: a change you did not expect is the test doing its job." + }, + "notes": "Baseline generated locally rather than on PACE. An earlier run recorded on 2026-08 (median 0.043, 2853 significant voxels) is NOT comparable to this one and must not be used to justify a tolerance. That run predates commit 33e167b ('seed fold shuffling for reproducible splits'); before it, create_chunked_folds called bare random.shuffle() on the global unseeded RNG, so the inner-CV folds differed on every invocation and the fit was a different model each time. The gap between the two recorded numbers is therefore not evidence of environmental variance, and the August run is not reproducible by current code on any machine." +} diff --git a/tests/test_golden_lebel.py b/tests/test_golden_lebel.py new file mode 100644 index 0000000..c0fb914 --- /dev/null +++ b/tests/test_golden_lebel.py @@ -0,0 +1,429 @@ +"""Characterization test for the real LeBel assembly. + +This pins the numbers that ``train_simple.py`` produces against a 2.8 GB fixture +that is not in the repository. It is opt-in: without the fixture it skips, so CI +without the file passes clean. + +Running it:: + + export LITCODER_LEBEL_ASSEMBLY=/path/to/assembly_lebel_uts03.pkl + pytest tests/test_golden_lebel.py -v + +Regenerating the golden values after an *intended* change:: + + LITCODER_LEBEL_ASSEMBLY=/path/to/assembly_lebel_uts03.pkl \ + python tests/test_golden_lebel.py --update + +Why the assertions look the way they do +--------------------------------------- +Shapes and the fixture md5 are exact -- they are integers and a hash, and there is +no reason for either to drift. + +Distribution statistics (quantiles of the per-voxel correlation vector) are +asserted with a tight absolute tolerance. They are threshold-free: a voxel moving +slightly changes a quantile by the local spacing of the distribution (~9e-6 near +the median on this fixture), not by a jump. + +Counts (``n_significant``, voxels above a fixed r) are asserted as a *relative +band*, never exactly. ``n_significant`` comes from Benjamini-Hochberg, whose +cutoff is a global order statistic: when one voxel crosses, the threshold index +itself moves and can admit or drop a run of neighbours. Measured on this fixture, +a uniform 1e-4 shift in r swings the count by 10 voxels and a 1e-3 shift by 59, +while the same perturbations leave every asserted quantile untouched. + +Tolerances are chosen strict or loose by comparing the running environment's +fingerprint against the one recorded in the JSON, and the chosen set is printed. +See ``tolerances.rationale`` and ``measured_variance`` in the JSON for the +measurements these numbers come from. +""" + +import hashlib +import json +import os +import platform +import sys +import warnings +from pathlib import Path + +import numpy as np +import pytest + +GOLDEN_PATH = Path(__file__).parent / "fixtures" / "golden_lebel_uts03.json" +ENV_VAR = "LITCODER_LEBEL_ASSEMBLY" + +# Same trimming train_simple.py uses for LeBel. +TRIMMING_CONFIG = { + "train_features_start": 10, + "train_features_end": -5, + "train_targets_start": 0, + "train_targets_end": None, + "test_features_start": 50, + "test_features_end": -5, + "test_targets_start": 40, + "test_targets_end": None, +} +FIR_DELAYS = [1, 2, 3, 4] + + +# -------------------------------------------------------------------------- +# Fixture discovery and integrity +# -------------------------------------------------------------------------- + +def load_golden() -> dict: + with open(GOLDEN_PATH) as f: + return json.load(f) + + +def skip_reason(golden: dict) -> str: + """An actionable message, not just 'skipped'.""" + raw = os.environ.get(ENV_VAR) + where = golden["fixture"]["source"] + name = golden["fixture"]["file"] + md5 = golden["fixture"]["md5"] + if not raw: + return ( + f"{ENV_VAR} is not set, so the real LeBel assembly is unavailable.\n" + f" This test is opt-in and CI is expected to skip it.\n" + f" To run it: export {ENV_VAR}=/path/to/{name}\n" + f" The file is ~2.8 GB (md5 {md5}); get it from: {where}." + ) + return ( + f"{ENV_VAR} is set to {raw!r}, but no file exists there.\n" + f" Point it at {name} (~2.8 GB, md5 {md5}).\n" + f" Get it from: {where}." + ) + + +def file_md5(path: Path, chunk: int = 8 << 20) -> str: + h = hashlib.md5() + with open(path, "rb") as f: + for block in iter(lambda: f.read(chunk), b""): + h.update(block) + return h.hexdigest() + + +def environment_fingerprint() -> dict: + """What the numerics actually depend on, beyond the input file.""" + import scipy + import torch + + if torch.backends.mps.is_available(): + device = "mps:0" + elif torch.cuda.is_available(): + device = "cuda" + else: + device = "cpu" + + return { + "platform_system": platform.system(), + "platform_machine": platform.machine(), + "torch": torch.__version__, + "numpy": np.__version__, + "scipy": scipy.__version__, + "device": device, + "torch_threads": torch.get_num_threads(), + } + + +# -------------------------------------------------------------------------- +# The pipeline under test +# -------------------------------------------------------------------------- + +def run_pipeline(assembly_path: str, results_dir: str) -> dict: + """Run exactly what train_simple.py runs, with logging and plotting stubbed. + + Deliberately calls ``fit_predict`` with no model kwargs, because + ``train_simple.py`` calls ``trainer.train()`` with none -- so the defaults + (5 inner folds, chunked folds of length 20, alphas=logspace(-1, 8, 10), + fold seed 0) are part of what is being characterized. + """ + # Imported lazily so that collection works without the heavy stack present. + from conftest import _NullBrainPlotter, _NullLogger + import encoding.trainer as trainer_mod + from encoding.assembly.assembly_loader import load_assembly + from encoding.downsample.downsampling import Downsampler + from encoding.features.factory import FeatureExtractorFactory + from encoding.models.nested_cv import NestedCVModel + + assembly = load_assembly(assembly_path) + extractor = FeatureExtractorFactory.create_extractor( + modality="wordrate", + model_name="wordrate", + config={}, + cache_dir=str(Path(results_dir) / "cache"), + ) + trainer = trainer_mod.AbstractTrainer( + assembly=assembly, + feature_extractors=[extractor], + downsampler=Downsampler(), + model=NestedCVModel(model_name="ridge_regression"), + fir_delays=FIR_DELAYS, + trimming_config=dict(TRIMMING_CONFIG), + use_train_test_split=True, + logger_backend="wandb", + dataset_type="lebel", + results_dir=results_dir, + downsample_config={}, + ) + assert isinstance(trainer.experiment_logger, _NullLogger) + assert isinstance(trainer.brain_plotter, _NullBrainPlotter) + + data = trainer.structure_data( + trainer.apply_fir_delays(trainer.extract_and_downsample_features()) + ) + metrics, weights, alphas = trainer.model.fit_predict( + features=data["Rstim"], + targets=data["Rresp"], + X_test=data["Pstim"], + y_test=data["Presp"], + ) + return { + "shapes": { + "X_train": list(data["Rstim"].shape), + "Y_train": list(data["Rresp"].shape), + "X_test": list(data["Pstim"].shape), + "Y_test": list(data["Presp"].shape), + }, + "correlations": np.asarray(metrics["correlations"]), + "n_significant": int(metrics["n_significant"]), + "median_score": float(metrics["median_score"]), + } + + +# -------------------------------------------------------------------------- +# Fixtures +# -------------------------------------------------------------------------- + +@pytest.fixture(scope="module") +def golden() -> dict: + return load_golden() + + +@pytest.fixture(scope="module") +def verified_assembly_path(golden) -> str: + """Skip when the fixture is absent; fail loudly when it is the wrong file.""" + raw = os.environ.get(ENV_VAR) + if not raw or not Path(raw).is_file(): + pytest.skip(skip_reason(golden)) + + path = Path(raw) + actual = file_md5(path) + expected = golden["fixture"]["md5"] + if actual != expected: + pytest.fail( + f"Assembly at {path} has md5 {actual}, but the golden values in " + f"{GOLDEN_PATH.name} were generated against md5 {expected}.\n" + f"Golden values are meaningless against a different input, so this is a " + f"hard failure rather than a skip.\n" + f"Either point {ENV_VAR} at the correct file, or -- if this new file is " + f"intentional -- regenerate with:\n" + f" {golden['regeneration']['command']}" + ) + return str(path) + + +@pytest.fixture(scope="module") +def result(verified_assembly_path, golden, tmp_path_factory) -> dict: + """Run the pipeline once for the whole module (it takes ~25 s warm).""" + with pytest.MonkeyPatch.context() as mp: + from conftest import _NullBrainPlotter, _NullLogger + import encoding.trainer as trainer_mod + import wandb + + mp.setattr(trainer_mod, "WandBLogger", _NullLogger) + mp.setattr(trainer_mod, "BrainPlotter", _NullBrainPlotter) + mp.setattr(wandb, "init", lambda *a, **k: None, raising=False) + + results_dir = tmp_path_factory.mktemp("golden_results") + return run_pipeline(verified_assembly_path, str(results_dir)) + + +@pytest.fixture(scope="module") +def tolerances(golden) -> dict: + """Pick the strict or loose set by fingerprint, and say which was used.""" + current = environment_fingerprint() + recorded = golden["environment"]["fingerprint"] + strict = current == recorded + + tol = golden["tolerances"] + chosen = { + "strict": strict, + "quantile_atol": tol["quantile_atol_strict"] if strict else tol["quantile_atol_loose"], + "count_rtol": tol["count_rtol_strict"] if strict else tol["count_rtol_loose"], + } + + banner = ( + f"\n[golden_lebel] tolerance set: {'STRICT' if strict else 'LOOSE'} " + f"(quantile atol={chosen['quantile_atol']:g}, count rtol={chosen['count_rtol']:g})" + ) + if not strict: + diff = { + k: (recorded.get(k), current.get(k)) + for k in sorted(set(recorded) | set(current)) + if recorded.get(k) != current.get(k) + } + banner += ( + f"\n[golden_lebel] environment differs from the recorded baseline " + f"(recorded -> current): {diff}" + ) + warnings.warn(banner.strip(), stacklevel=2) + print(banner) + return chosen + + +# -------------------------------------------------------------------------- +# Tests +# -------------------------------------------------------------------------- + +def test_golden_json_is_well_formed(golden): + """Runs everywhere, including CI without the fixture.""" + for key in ("fixture", "shapes", "metrics", "quantiles", "tolerances", "regeneration"): + assert key in golden + assert len(golden["fixture"]["md5"]) == 32 + assert golden["tolerances"]["quantile_atol_strict"] < golden["tolerances"]["quantile_atol_loose"] + assert golden["tolerances"]["count_rtol_strict"] < golden["tolerances"]["count_rtol_loose"] + # The median must agree with the p50 quantile, or the two would drift apart. + assert golden["metrics"]["median_score"] == pytest.approx(golden["quantiles"]["50"]) + + +def test_skip_reason_is_actionable(golden): + """The skip message must tell someone what to set and where to get the file.""" + reason = skip_reason(golden) + assert ENV_VAR in reason + assert golden["fixture"]["md5"] in reason + assert golden["fixture"]["file"] in reason + assert "2.8 GB" in reason + + +def test_shapes_match_exactly(result, golden): + """Shapes are integers; there is no tolerance to apply.""" + assert result["shapes"] == {k: list(v) for k, v in golden["shapes"].items()} + + +def test_correlation_quantiles(result, golden, tolerances): + """Threshold-free distribution statistics, asserted tightly.""" + correlations = result["correlations"] + assert correlations.shape == (golden["metrics"]["n_voxels"],) + + atol = tolerances["quantile_atol"] + failures = [] + for q_str, expected in sorted(golden["quantiles"].items(), key=lambda kv: float(kv[0])): + actual = float(np.percentile(correlations, float(q_str))) + if abs(actual - expected) > atol: + failures.append(f" p{q_str}: expected {expected:.10f}, got {actual:.10f} " + f"(delta {actual - expected:+.3e}, atol {atol:g})") + assert not failures, ( + "Correlation distribution moved:\n" + "\n".join(failures) + + f"\nIf this change is intended, regenerate with:\n {golden['regeneration']['command']}" + ) + + +def test_median_score(result, golden, tolerances): + """The headline number train_simple.py prints.""" + expected = golden["metrics"]["median_score"] + actual = result["median_score"] + assert actual == pytest.approx(expected, abs=tolerances["quantile_atol"]), ( + f"median r moved from {expected:.10f} to {actual:.10f} " + f"(delta {actual - expected:+.3e}).\n" + f"If intended, regenerate with:\n {golden['regeneration']['command']}" + ) + + +def test_n_significant_within_band(result, golden, tolerances): + """Banded, never exact -- the BH cutoff is an order statistic with a cascade.""" + expected = golden["metrics"]["n_significant"] + actual = result["n_significant"] + rtol = tolerances["count_rtol"] + lo, hi = expected * (1 - rtol), expected * (1 + rtol) + assert lo <= actual <= hi, ( + f"n_significant={actual} outside [{lo:.0f}, {hi:.0f}] (expected {expected}, rtol {rtol:g}).\n" + f"A few voxels either side is normal: FDR thresholding means voxels near the " + f"cutoff flip on tiny correlation changes. A move this large is not that.\n" + f"If intended, regenerate with:\n {golden['regeneration']['command']}" + ) + + +def test_threshold_counts_within_band(result, golden, tolerances): + """Counts above a fixed r -- same cliff reasoning as n_significant, same banding.""" + correlations = result["correlations"] + rtol = tolerances["count_rtol"] + for cut_str, expected in golden["threshold_counts"].items(): + actual = int((correlations > float(cut_str)).sum()) + lo, hi = expected * (1 - rtol), expected * (1 + rtol) + assert lo <= actual <= hi, ( + f"voxels with r > {cut_str}: {actual} outside [{lo:.0f}, {hi:.0f}] " + f"(expected {expected}, rtol {rtol:g}).\n" + f"If intended, regenerate with:\n {golden['regeneration']['command']}" + ) + + +# -------------------------------------------------------------------------- +# Regeneration entry point +# -------------------------------------------------------------------------- + +def regenerate() -> int: + """Rewrite the measured fields of the golden JSON from a fresh run. + + Leaves tolerances, rationale and notes alone -- those are human judgements, + not measurements, and silently overwriting them would defeat the point. + """ + import tempfile + + golden = load_golden() + raw = os.environ.get(ENV_VAR) + if not raw or not Path(raw).is_file(): + print(skip_reason(golden), file=sys.stderr) + return 1 + + actual_md5 = file_md5(Path(raw)) + if actual_md5 != golden["fixture"]["md5"]: + print( + f"note: fixture md5 changed ({golden['fixture']['md5']} -> {actual_md5}); " + f"recording the new one.", + file=sys.stderr, + ) + + import encoding.trainer as trainer_mod + import wandb + from conftest import _NullBrainPlotter, _NullLogger + + trainer_mod.WandBLogger = _NullLogger + trainer_mod.BrainPlotter = _NullBrainPlotter + wandb.init = lambda *a, **k: None + + with tempfile.TemporaryDirectory() as tmp: + result = run_pipeline(raw, tmp) + + correlations = result["correlations"] + golden["fixture"]["md5"] = actual_md5 + golden["environment"]["fingerprint"] = environment_fingerprint() + golden["shapes"] = result["shapes"] + golden["metrics"]["median_score"] = round(float(np.median(correlations)), 10) + golden["metrics"]["n_significant"] = result["n_significant"] + golden["metrics"]["n_voxels"] = int(correlations.size) + golden["quantiles"] = { + q: round(float(np.percentile(correlations, float(q))), 10) + for q in golden["quantiles"] + } + golden["threshold_counts"] = { + cut: int((correlations > float(cut)).sum()) for cut in golden["threshold_counts"] + } + + with open(GOLDEN_PATH, "w") as f: + json.dump(golden, f, indent=2) + f.write("\n") + + print(f"updated {GOLDEN_PATH}") + print(f" median_score = {golden['metrics']['median_score']}") + print(f" n_significant = {golden['metrics']['n_significant']}") + print("Review the diff before committing: an unexpected change is the test working.") + return 0 + + +if __name__ == "__main__": + if "--update" in sys.argv: + sys.path.insert(0, str(Path(__file__).parent)) + sys.exit(regenerate()) + print(__doc__) + print("Run the tests with pytest; pass --update to regenerate the golden values.") + sys.exit(0) diff --git a/tests/test_pipeline_synthetic.py b/tests/test_pipeline_synthetic.py index e2830c1..3e19049 100644 --- a/tests/test_pipeline_synthetic.py +++ b/tests/test_pipeline_synthetic.py @@ -609,6 +609,60 @@ def test_trimming_config_pairs_features_with_past_tr_only(truth): assert TRIMMING_CONFIG["test_features_end"] == -BRAIN_TRIM_TAIL +def test_determinism(pipeline_data, monkeypatch): + """The same seed reproduces the correlation vector; a different fold seed does not. + + The second half is what stops this passing vacuously. Note it has to compare the + *correlation arrays*: changing the fold seed reshuffles which alpha each voxel + gets, but on this fixture it moves the median by only ~5e-6 and leaves + n_significant unchanged, so asserting on either of those would pass no matter + what the pipeline did. + + ``fit_predict`` exposes no seed argument -- ``_find_best_alphas`` calls + ``create_folds`` without one, so the fold seed is always the default 0. The + alternate seed is injected by patching that call site. + """ + data = pipeline_data["data"] + model = pipeline_data["trainer"].model + + def fit(): + metrics, _, alphas = model.fit_predict( + features=data["Rstim"], + targets=data["Rresp"], + X_test=data["Pstim"], + y_test=data["Presp"], + **MODEL_KWARGS, + ) + return np.asarray(metrics["correlations"]), np.asarray(alphas) + + first, first_alphas = fit() + second, second_alphas = fit() + + # Same seed, same everything: reproducible. + assert np.allclose(first, second, rtol=0, atol=1e-12) + np.testing.assert_array_equal(first_alphas, second_alphas) + + # Different fold seed: a genuinely different model. + import encoding.models.nested_cv as nested_cv_mod + from encoding.models.folding import create_folds as real_create_folds + + def seeded_create_folds(n_samples, fold_type, n_folds, chunk_length=None, + trim_size=None, groups=None, seed=0): + return real_create_folds( + n_samples, fold_type, n_folds, chunk_length, trim_size, groups, seed=7 + ) + + monkeypatch.setattr(nested_cv_mod, "create_folds", seeded_create_folds) + other, other_alphas = fit() + + assert not np.allclose(first, other, rtol=0, atol=1e-12), ( + "changing the inner-CV fold seed produced an identical correlation vector, " + "which means the seed is not reaching create_folds and the first half of " + "this test proves nothing" + ) + assert (first_alphas != other_alphas).any(), "no voxel changed its selected alpha" + + def test_fixture_is_deterministic(): """Same seed, same assembly -- so a failure is reproducible.""" a = synthetic_assembly(n_stories=2, n_trs=(60, 60), n_vertices=64, seed=3) From 41f2e1db8f2265c1b2592b88b432a632a8d73b9a Mon Sep 17 00:00:00 2001 From: Aadhav Thaniga Date: Mon, 12 Oct 2026 18:07:53 -0400 Subject: [PATCH 5/9] trim test prose and dead code --- tests/conftest.py | 166 +++-------------- tests/test_golden_lebel.py | 130 ++++--------- tests/test_pipeline_synthetic.py | 306 ++++--------------------------- 3 files changed, 92 insertions(+), 510 deletions(-) diff --git a/tests/conftest.py b/tests/conftest.py index abfd5a2..2f6e689 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,12 +1,8 @@ """Shared fixtures for the synthetic end-to-end pipeline tests. -The real LeBel assembly is ~3 GB and needs a GPU-ish machine to be useful. These -tests instead build a small assembly with the *same structural conventions* and a -signal planted at known FIR lags, so the whole extract -> downsample -> FIR -> -trim -> ridge path can be checked for correctness in seconds. - -Conventions copied from ``data/assembly_lebel_uts03.pkl`` (verified against all 25 -stories of that file): +Builds a small assembly with the same structural conventions as +``data/assembly_lebel_uts03.pkl`` and a signal planted at known FIR lags. +Conventions (verified against all 25 stories of that file): * ``len(split_indices) + 1 == len(tr_times)`` -- split_indices are *cut points* into the word axis, consumed by ``np.split``, not a per-word TR label. @@ -20,7 +16,7 @@ # Must happen before anything imports matplotlib/wandb (encoding.trainer pulls in # encoding.plotting.plotting_utils, which imports matplotlib and nilearn at module -# scope). Belt and braces with the monkeypatching in _no_external_side_effects. +# scope). os.environ.setdefault("MPLBACKEND", "Agg") os.environ.setdefault("WANDB_MODE", "disabled") os.environ.setdefault("WANDB_SILENT", "true") @@ -28,7 +24,7 @@ import hashlib from dataclasses import dataclass, field -from typing import Dict, List, Optional, Tuple +from typing import Dict, List, Tuple import numpy as np import pytest @@ -38,18 +34,14 @@ from encoding.features.base import BaseFeatureExtractor from encoding.features.embeddings import StaticEmbeddingFeatureExtractor -# -------------------------------------------------------------------------- -# Constants mirroring the real LeBel assembly / train_simple.py -# -------------------------------------------------------------------------- - N_VERTICES = 20484 # fsaverage5, both hemispheres -N_FEATURES = 4 # synthetic embedding dimensionality +N_FEATURES = 4 N_SIGNAL_VERTICES = 10 # vertices 0..9 carry the planted signal -PLANTED_LAGS = (2, 3) # the "bump" in the planted FIR kernel -FIR_DELAYS = [1, 2, 3, 4] # delays the pipeline is run with +PLANTED_LAGS = (2, 3) +FIR_DELAYS = [1, 2, 3, 4] TR = 1.5 -BRAIN_TRIM_HEAD = 10 # TRs already removed from brain_data at the front -BRAIN_TRIM_TAIL = 5 # ... and at the back +BRAIN_TRIM_HEAD = 10 +BRAIN_TRIM_TAIL = 5 BRAIN_TRIM_TOTAL = BRAIN_TRIM_HEAD + BRAIN_TRIM_TAIL # Same trimming used in train_simple.py for the LeBel dataset. @@ -65,10 +57,6 @@ } -# -------------------------------------------------------------------------- -# Deterministic token -> vector map (a stand-in for a static embedding model) -# -------------------------------------------------------------------------- - def token_vector(token: str, dim: int = N_FEATURES) -> np.ndarray: """Map a token to a fixed pseudo-random vector. @@ -81,16 +69,12 @@ def token_vector(token: str, dim: int = N_FEATURES) -> np.ndarray: class SyntheticTokenFeatureExtractor(StaticEmbeddingFeatureExtractor): - """Word-level feature extractor that plugs into the real factory dispatch. - - Subclasses ``StaticEmbeddingFeatureExtractor`` so that - ``FeatureExtractorFactory._get_modality_from_extractor`` reports "embeddings" - and the factory feeds it ``assembly.get_words()[idx]`` (one entry per word). - The parent ``__init__`` is deliberately bypassed: it requires a gensim vector - file on disk, which is exactly what we are replacing. + """Word-level extractor that plugs into the real factory dispatch. - The class name must not contain "wordrate", or ``AbstractTrainer._should_downsample`` - would skip downsampling for it. + Subclasses ``StaticEmbeddingFeatureExtractor`` so the factory feeds it + ``assembly.get_words()[idx]``; the parent ``__init__`` is bypassed because it + requires a gensim vector file. The class name must not contain "wordrate", or + ``AbstractTrainer._should_downsample`` would skip downsampling for it. """ def __init__(self, dim: int = N_FEATURES): @@ -103,17 +87,8 @@ def extract_features(self, stimuli, **kwargs) -> np.ndarray: return np.vstack([token_vector(tok, self.dim) for tok in stimuli]) -# -------------------------------------------------------------------------- -# Reference implementations -- deliberately independent of encoding/ -# -------------------------------------------------------------------------- - def reference_legacy_average(word_features: np.ndarray, counts: np.ndarray) -> np.ndarray: - """Average word features per TR, given the number of words in each TR. - - Written from ``counts`` rather than from ``split_indices``/``np.split`` so it - is an independent oracle for LegacyAverageDownsampler rather than a restatement - of it. TRs with no words stay as zero rows, matching the library. - """ + """Per-TR mean of word features, from counts rather than np.split; empty TRs stay zero.""" out = np.zeros((len(counts), word_features.shape[1])) pos = 0 for i, c in enumerate(counts): @@ -129,44 +104,13 @@ def reference_make_delayed(features: np.ndarray, delays) -> np.ndarray: blocks = [] for d in delays: block = np.zeros((n_t, n_d)) - if d > 0: - block[d:] = features[:-d] - elif d == 0: - block = features.copy() - else: - block[:d] = features[-d:] + block[d:] = features[:-d] blocks.append(block) return np.hstack(blocks) -def column_correlations(a: np.ndarray, b: np.ndarray) -> np.ndarray: - """Pearson r between matching columns of two (n_samples, n_targets) matrices.""" - az = a - a.mean(axis=0) - bz = b - b.mean(axis=0) - denom = np.linalg.norm(az, axis=0) * np.linalg.norm(bz, axis=0) - out = np.zeros(a.shape[1]) - nz = denom > 0 - out[nz] = (az[:, nz] * bz[:, nz]).sum(axis=0) / denom[nz] - return out - - -def ridge_fit_predict(X_train, Y_train, X_test, alpha: float = 100.0) -> np.ndarray: - """Plain closed-form ridge; a fast stand-in for NestedCVModel in ablations.""" - n_feat = X_train.shape[1] - gram = X_train.T @ X_train + alpha * np.eye(n_feat) - weights = np.linalg.solve(gram, X_train.T @ Y_train) - return X_test @ weights - - -# -------------------------------------------------------------------------- -# Ground truth bundled alongside the assembly -# -------------------------------------------------------------------------- - @dataclass class StoryTruth: - """Everything a test needs to know about how one synthetic story was built.""" - - name: str n_trs: int n_words: int counts: np.ndarray # words per TR, length n_trs @@ -177,20 +121,11 @@ class StoryTruth: @dataclass class GroundTruth: - """Ground truth for the whole synthetic assembly.""" - stories: Dict[str, StoryTruth] = field(default_factory=dict) lag_weights: Dict[int, np.ndarray] = field(default_factory=dict) # lag -> (N_FEATURES, N_SIGNAL) signal_vertices: np.ndarray = field(default_factory=lambda: np.arange(N_SIGNAL_VERTICES)) noise_vertices: np.ndarray = field(default_factory=lambda: np.arange(N_SIGNAL_VERTICES, N_VERTICES)) - planted_lags: Tuple[int, ...] = PLANTED_LAGS - fir_delays: Tuple[int, ...] = tuple(FIR_DELAYS) - trimming_config: Dict = field(default_factory=lambda: dict(TRIMMING_CONFIG)) - -# -------------------------------------------------------------------------- -# The fixture builder -# -------------------------------------------------------------------------- def synthetic_assembly( n_stories: int = 3, @@ -205,33 +140,18 @@ def synthetic_assembly( ) -> SimpleNeuroidAssembly: """Build a small assembly with a signal planted at known FIR lags. - The returned object is a real ``SimpleNeuroidAssembly`` and can be handed to - ``AbstractTrainer`` anywhere the LeBel assembly would go. Ground truth is - attached as ``assembly.truth`` (a :class:`GroundTruth`). - - How the signal is planted - ------------------------- - Per story, word-level features ``W`` are averaged into TR-level features ``F`` - using the legacy convention. Brain data is then + Ground truth is attached as ``assembly.truth``. Brain data for the first + ``n_signal_vertices`` is brain[j, v] = sum_{d in planted_lags} F[j + BRAIN_TRIM_HEAD - d] @ lag_weights[d][:, v] - for ``v`` in the first ``n_signal_vertices``, and pure noise elsewhere. - - The ``+ BRAIN_TRIM_HEAD`` offset is what makes the planting consistent with - ``TRIMMING_CONFIG``: the trainer pairs ``features[10:-5]`` with ``targets[0:]``, - so brain row ``j`` is aligned with feature row ``j + 10``, whose FIR block for - delay ``d`` holds ``F[j + 10 - d]``. Only *past* TRs are ever referenced, so the - construction is causal by design. - - Args: - n_stories: Number of stories. The last one becomes the held-out test story. - n_trs: Per-story TR counts (cycled if shorter than ``n_stories``). - noise_ratio: Noise std as a fraction of each signal vertex's own std. - 0.5 gives an achievable ceiling of r ~= 0.89. - max_words_per_tr: Words per TR are drawn uniformly from [0, this), so some - TRs are empty -- which is what exercises the zero-row path in the - legacy downsamplers. + where ``F`` is the legacy-averaged TR-level features; other vertices are noise. + The ``+ BRAIN_TRIM_HEAD`` offset matches ``TRIMMING_CONFIG``: the trainer pairs + ``features[10:-5]`` with ``targets[0:]``, so brain row ``j`` is aligned with + feature row ``j + 10``, whose FIR block for delay ``d`` holds ``F[j + 10 - d]``. + + ``noise_ratio`` is noise std as a fraction of each signal vertex's std; 0.5 + gives a ceiling of r ~= 0.89. """ if n_stories < 2: raise ValueError("need at least 2 stories for a train/test split") @@ -239,8 +159,6 @@ def synthetic_assembly( raise ValueError("planted lags must be < BRAIN_TRIM_HEAD to stay in range") rng = np.random.default_rng(seed) - - # One shared set of lag weights, so the planted kernel is identical across stories. lag_weights = { lag: rng.standard_normal((n_features, n_signal_vertices)) for lag in planted_lags @@ -250,7 +168,6 @@ def synthetic_assembly( lag_weights=lag_weights, signal_vertices=np.arange(n_signal_vertices), noise_vertices=np.arange(n_signal_vertices, n_vertices), - planted_lags=tuple(planted_lags), ) story_data_list: List[StoryData] = [] @@ -260,24 +177,20 @@ def synthetic_assembly( name = f"synthstory{s}" n_tr = n_trs[s % len(n_trs)] - # --- word/TR bookkeeping, legacy split_indices convention ------------- counts = story_rng.integers(0, max_words_per_tr, size=n_tr) # Mirror the real data: silence at the very start and end of a run. counts[:3] = 0 counts[-2:] = 0 n_words = int(counts.sum()) - # Cut points into the word axis: cumsum minus the final total, giving - # exactly n_tr - 1 entries so that np.split yields n_tr chunks. + # n_tr - 1 cut points, so np.split yields n_tr chunks. split_indices = np.cumsum(counts)[:-1].astype(np.int64).tolist() words = [f"w{s}_{i}" for i in range(n_words)] - # Cumulative-context stimuli, one per word, as in the real assembly. stimuli = [" ".join(words[max(0, i - 5):i + 1]) for i in range(n_words)] tr_times = np.arange(n_tr, dtype=np.float64) * TR - # Word onsets spread inside their own TR, so data_times stays sorted. data_times = np.empty(n_words, dtype=np.float64) pos = 0 for i, c in enumerate(counts): @@ -289,7 +202,6 @@ def synthetic_assembly( word_features = np.vstack([token_vector(w, n_features) for w in words]) tr_features = reference_legacy_average(word_features, counts) - # --- plant the FIR signal -------------------------------------------- n_brain = n_tr - BRAIN_TRIM_TOTAL j = np.arange(n_brain) signal = np.zeros((n_brain, n_signal_vertices)) @@ -301,13 +213,11 @@ def synthetic_assembly( brain[:, :n_signal_vertices] = signal + story_rng.standard_normal( (n_brain, n_signal_vertices) ) * (signal_std * noise_ratio) - # Noise vertices get a comparable scale so nothing is separable by variance alone. brain[:, n_signal_vertices:] = story_rng.standard_normal( (n_brain, n_vertices - n_signal_vertices) ) * float(np.median(signal_std)) truth.stories[name] = StoryTruth( - name=name, n_trs=n_tr, n_words=n_words, counts=counts, @@ -337,22 +247,17 @@ def synthetic_assembly( return assembly -# -------------------------------------------------------------------------- -# Fixtures -# -------------------------------------------------------------------------- - class _NullLogger: - """Stand-in for WandBLogger/TensorBoardLogger that records calls in memory.""" + """Stand-in for WandBLogger/TensorBoardLogger that records scalars in memory.""" def __init__(self, *args, **kwargs): self.scalars: Dict[str, float] = {} - self.images: List[str] = [] def log_scalar(self, name, value, step=None): self.scalars[name] = value def log_image(self, name, figure, step=None): - self.images.append(name) + pass def log_histogram(self, name, values, step=None): pass @@ -387,7 +292,6 @@ def _no_external_side_effects(monkeypatch): monkeypatch.setattr(wandb, "log", lambda *a, **k: None, raising=False) monkeypatch.setattr(wandb, "finish", lambda *a, **k: None, raising=False) - # Last line of defence if a test reaches the real plotting utilities. import encoding.plotting.plotting_utils as plotting_utils monkeypatch.setattr( plotting_utils.datasets, @@ -399,21 +303,9 @@ def _no_external_side_effects(monkeypatch): @pytest.fixture(scope="module") def assembly() -> SimpleNeuroidAssembly: - """The synthetic assembly, built once per test module.""" return synthetic_assembly() @pytest.fixture(scope="module") def truth(assembly) -> GroundTruth: return assembly.truth - - -@pytest.fixture -def extractor() -> SyntheticTokenFeatureExtractor: - return SyntheticTokenFeatureExtractor() - - -@pytest.fixture -def downsample_config() -> Dict: - """legacy_average is the only averaging method that reads split_indices correctly.""" - return {"method": "legacy_average"} diff --git a/tests/test_golden_lebel.py b/tests/test_golden_lebel.py index c0fb914..3048f79 100644 --- a/tests/test_golden_lebel.py +++ b/tests/test_golden_lebel.py @@ -1,8 +1,7 @@ """Characterization test for the real LeBel assembly. -This pins the numbers that ``train_simple.py`` produces against a 2.8 GB fixture -that is not in the repository. It is opt-in: without the fixture it skips, so CI -without the file passes clean. +Pins the numbers ``train_simple.py`` produces against a 2.8 GB fixture that is not +in the repository. Skips when the fixture is absent. Running it:: @@ -14,33 +13,16 @@ LITCODER_LEBEL_ASSEMBLY=/path/to/assembly_lebel_uts03.pkl \ python tests/test_golden_lebel.py --update -Why the assertions look the way they do ---------------------------------------- -Shapes and the fixture md5 are exact -- they are integers and a hash, and there is -no reason for either to drift. - -Distribution statistics (quantiles of the per-voxel correlation vector) are -asserted with a tight absolute tolerance. They are threshold-free: a voxel moving -slightly changes a quantile by the local spacing of the distribution (~9e-6 near -the median on this fixture), not by a jump. - -Counts (``n_significant``, voxels above a fixed r) are asserted as a *relative -band*, never exactly. ``n_significant`` comes from Benjamini-Hochberg, whose -cutoff is a global order statistic: when one voxel crosses, the threshold index -itself moves and can admit or drop a run of neighbours. Measured on this fixture, -a uniform 1e-4 shift in r swings the count by 10 voxels and a 1e-3 shift by 59, -while the same perturbations leave every asserted quantile untouched. - -Tolerances are chosen strict or loose by comparing the running environment's -fingerprint against the one recorded in the JSON, and the chosen set is printed. -See ``tolerances.rationale`` and ``measured_variance`` in the JSON for the -measurements these numbers come from. +Tolerances and the measurements behind them are in the JSON under +``tolerances.rationale`` and ``measured_variance``. """ +import datetime import hashlib import json import os import platform +import subprocess import sys import warnings from pathlib import Path @@ -65,17 +47,12 @@ FIR_DELAYS = [1, 2, 3, 4] -# -------------------------------------------------------------------------- -# Fixture discovery and integrity -# -------------------------------------------------------------------------- - def load_golden() -> dict: with open(GOLDEN_PATH) as f: return json.load(f) def skip_reason(golden: dict) -> str: - """An actionable message, not just 'skipped'.""" raw = os.environ.get(ENV_VAR) where = golden["fixture"]["source"] name = golden["fixture"]["file"] @@ -103,7 +80,6 @@ def file_md5(path: Path, chunk: int = 8 << 20) -> str: def environment_fingerprint() -> dict: - """What the numerics actually depend on, beyond the input file.""" import scipy import torch @@ -125,19 +101,12 @@ def environment_fingerprint() -> dict: } -# -------------------------------------------------------------------------- -# The pipeline under test -# -------------------------------------------------------------------------- - def run_pipeline(assembly_path: str, results_dir: str) -> dict: - """Run exactly what train_simple.py runs, with logging and plotting stubbed. + """Run what train_simple.py runs, with logging and plotting stubbed. - Deliberately calls ``fit_predict`` with no model kwargs, because - ``train_simple.py`` calls ``trainer.train()`` with none -- so the defaults - (5 inner folds, chunked folds of length 20, alphas=logspace(-1, 8, 10), - fold seed 0) are part of what is being characterized. + Calls ``fit_predict`` with no model kwargs, as ``train_simple.py`` calls + ``trainer.train()`` with none -- the defaults are part of what is characterized. """ - # Imported lazily so that collection works without the heavy stack present. from conftest import _NullBrainPlotter, _NullLogger import encoding.trainer as trainer_mod from encoding.assembly.assembly_loader import load_assembly @@ -190,10 +159,6 @@ def run_pipeline(assembly_path: str, results_dir: str) -> dict: } -# -------------------------------------------------------------------------- -# Fixtures -# -------------------------------------------------------------------------- - @pytest.fixture(scope="module") def golden() -> dict: return load_golden() @@ -201,7 +166,7 @@ def golden() -> dict: @pytest.fixture(scope="module") def verified_assembly_path(golden) -> str: - """Skip when the fixture is absent; fail loudly when it is the wrong file.""" + """Skip when the fixture is absent; fail when it is the wrong file.""" raw = os.environ.get(ENV_VAR) if not raw or not Path(raw).is_file(): pytest.skip(skip_reason(golden)) @@ -211,12 +176,9 @@ def verified_assembly_path(golden) -> str: expected = golden["fixture"]["md5"] if actual != expected: pytest.fail( - f"Assembly at {path} has md5 {actual}, but the golden values in " - f"{GOLDEN_PATH.name} were generated against md5 {expected}.\n" - f"Golden values are meaningless against a different input, so this is a " - f"hard failure rather than a skip.\n" - f"Either point {ENV_VAR} at the correct file, or -- if this new file is " - f"intentional -- regenerate with:\n" + f"Assembly at {path} has md5 {actual}; golden values were generated " + f"against md5 {expected}.\n" + f"If the new file is intentional, regenerate with:\n" f" {golden['regeneration']['command']}" ) return str(path) @@ -224,7 +186,8 @@ def verified_assembly_path(golden) -> str: @pytest.fixture(scope="module") def result(verified_assembly_path, golden, tmp_path_factory) -> dict: - """Run the pipeline once for the whole module (it takes ~25 s warm).""" + """Module-scoped, so conftest's function-scoped autouse patching is not yet + active; patch explicitly for the duration of the run.""" with pytest.MonkeyPatch.context() as mp: from conftest import _NullBrainPlotter, _NullLogger import encoding.trainer as trainer_mod @@ -271,37 +234,17 @@ def tolerances(golden) -> dict: return chosen -# -------------------------------------------------------------------------- -# Tests -# -------------------------------------------------------------------------- - def test_golden_json_is_well_formed(golden): - """Runs everywhere, including CI without the fixture.""" for key in ("fixture", "shapes", "metrics", "quantiles", "tolerances", "regeneration"): assert key in golden - assert len(golden["fixture"]["md5"]) == 32 - assert golden["tolerances"]["quantile_atol_strict"] < golden["tolerances"]["quantile_atol_loose"] - assert golden["tolerances"]["count_rtol_strict"] < golden["tolerances"]["count_rtol_loose"] - # The median must agree with the p50 quantile, or the two would drift apart. assert golden["metrics"]["median_score"] == pytest.approx(golden["quantiles"]["50"]) -def test_skip_reason_is_actionable(golden): - """The skip message must tell someone what to set and where to get the file.""" - reason = skip_reason(golden) - assert ENV_VAR in reason - assert golden["fixture"]["md5"] in reason - assert golden["fixture"]["file"] in reason - assert "2.8 GB" in reason - - def test_shapes_match_exactly(result, golden): - """Shapes are integers; there is no tolerance to apply.""" assert result["shapes"] == {k: list(v) for k, v in golden["shapes"].items()} def test_correlation_quantiles(result, golden, tolerances): - """Threshold-free distribution statistics, asserted tightly.""" correlations = result["correlations"] assert correlations.shape == (golden["metrics"]["n_voxels"],) @@ -313,38 +256,24 @@ def test_correlation_quantiles(result, golden, tolerances): failures.append(f" p{q_str}: expected {expected:.10f}, got {actual:.10f} " f"(delta {actual - expected:+.3e}, atol {atol:g})") assert not failures, ( - "Correlation distribution moved:\n" + "\n".join(failures) - + f"\nIf this change is intended, regenerate with:\n {golden['regeneration']['command']}" - ) - - -def test_median_score(result, golden, tolerances): - """The headline number train_simple.py prints.""" - expected = golden["metrics"]["median_score"] - actual = result["median_score"] - assert actual == pytest.approx(expected, abs=tolerances["quantile_atol"]), ( - f"median r moved from {expected:.10f} to {actual:.10f} " - f"(delta {actual - expected:+.3e}).\n" - f"If intended, regenerate with:\n {golden['regeneration']['command']}" + "Correlation quantiles moved:\n" + "\n".join(failures) + + f"\nIf intended, regenerate with:\n {golden['regeneration']['command']}" ) def test_n_significant_within_band(result, golden, tolerances): - """Banded, never exact -- the BH cutoff is an order statistic with a cascade.""" + """Banded, not exact: voxels near the BH cutoff flip on tiny correlation changes.""" expected = golden["metrics"]["n_significant"] actual = result["n_significant"] rtol = tolerances["count_rtol"] lo, hi = expected * (1 - rtol), expected * (1 + rtol) assert lo <= actual <= hi, ( f"n_significant={actual} outside [{lo:.0f}, {hi:.0f}] (expected {expected}, rtol {rtol:g}).\n" - f"A few voxels either side is normal: FDR thresholding means voxels near the " - f"cutoff flip on tiny correlation changes. A move this large is not that.\n" f"If intended, regenerate with:\n {golden['regeneration']['command']}" ) def test_threshold_counts_within_band(result, golden, tolerances): - """Counts above a fixed r -- same cliff reasoning as n_significant, same banding.""" correlations = result["correlations"] rtol = tolerances["count_rtol"] for cut_str, expected in golden["threshold_counts"].items(): @@ -357,16 +286,8 @@ def test_threshold_counts_within_band(result, golden, tolerances): ) -# -------------------------------------------------------------------------- -# Regeneration entry point -# -------------------------------------------------------------------------- - def regenerate() -> int: - """Rewrite the measured fields of the golden JSON from a fresh run. - - Leaves tolerances, rationale and notes alone -- those are human judgements, - not measurements, and silently overwriting them would defeat the point. - """ + """Rewrite the measured fields of the golden JSON; tolerances and notes are left alone.""" import tempfile golden = load_golden() @@ -396,6 +317,17 @@ def regenerate() -> int: correlations = result["correlations"] golden["fixture"]["md5"] = actual_md5 + golden["run"]["date"] = datetime.date.today().isoformat() + try: + golden["run"]["commit"] = subprocess.run( + ["git", "rev-parse", "HEAD"], + cwd=Path(__file__).parent, + capture_output=True, + text=True, + check=True, + ).stdout.strip() + except (OSError, subprocess.CalledProcessError): + pass golden["environment"]["fingerprint"] = environment_fingerprint() golden["shapes"] = result["shapes"] golden["metrics"]["median_score"] = round(float(np.median(correlations)), 10) @@ -416,7 +348,7 @@ def regenerate() -> int: print(f"updated {GOLDEN_PATH}") print(f" median_score = {golden['metrics']['median_score']}") print(f" n_significant = {golden['metrics']['n_significant']}") - print("Review the diff before committing: an unexpected change is the test working.") + print("Review the diff before committing.") return 0 diff --git a/tests/test_pipeline_synthetic.py b/tests/test_pipeline_synthetic.py index 3e19049..90f9d14 100644 --- a/tests/test_pipeline_synthetic.py +++ b/tests/test_pipeline_synthetic.py @@ -1,24 +1,13 @@ """End-to-end tests for the encoding pipeline against a synthetic assembly. -Three groups: - -* **Structural** -- the assembly obeys the same conventions as the real LeBel - assembly, and each stage transforms shapes the way the next stage expects. -* **Recovery** -- a signal planted at FIR lags 2 and 3 in vertices 0..9 is - recovered by the real pipeline, at the right lags and in the right vertices. -* **Leakage / ordering** -- the held-out story cannot reach the training matrix, - the FIR expansion is causal, and the recovered correlation genuinely depends on - temporal alignment rather than on some artefact of the plumbing. - -Everything runs offline: no wandb run, no fsaverage download, Agg backend. See -``conftest._no_external_side_effects``. +Checks structure, recovery of a signal planted at FIR lags 2 and 3 in vertices +0..9, and that the held-out story cannot leak into training. Runs offline. """ import numpy as np import pytest from conftest import ( - BRAIN_TRIM_HEAD, BRAIN_TRIM_TAIL, BRAIN_TRIM_TOTAL, FIR_DELAYS, @@ -26,14 +15,10 @@ N_SIGNAL_VERTICES, N_VERTICES, PLANTED_LAGS, - TR, TRIMMING_CONFIG, SyntheticTokenFeatureExtractor, - column_correlations, reference_legacy_average, reference_make_delayed, - ridge_fit_predict, - synthetic_assembly, _NullBrainPlotter, _NullLogger, ) @@ -43,14 +28,9 @@ from encoding.models.nested_cv import NestedCVModel from encoding.trainer import AbstractTrainer -# Keep the nested CV cheap; the point is correctness, not hyperparameter search. MODEL_KWARGS = dict(alphas=[1.0, 10.0, 100.0, 1000.0], n_inner_folds=2, use_gpu=False) -# -------------------------------------------------------------------------- -# Helpers -# -------------------------------------------------------------------------- - def make_trainer(assembly, results_dir, **overrides): """Build an AbstractTrainer wired the way train_simple.py wires it.""" kwargs = dict( @@ -72,11 +52,8 @@ def make_trainer(assembly, results_dir, **overrides): @pytest.fixture(scope="module") def pipeline_data(assembly, tmp_path_factory): - """Run extract -> downsample -> FIR -> structure once and reuse it. - - Module-scoped, so the function-scoped autouse patching in conftest is not yet - active; patch explicitly for the duration of trainer construction. - """ + """Module-scoped, so conftest's function-scoped autouse patching is not yet + active; patch explicitly for the duration of trainer construction.""" results_dir = tmp_path_factory.mktemp("results") with pytest.MonkeyPatch.context() as mp: import encoding.trainer as trainer_mod @@ -102,7 +79,6 @@ def pipeline_data(assembly, tmp_path_factory): @pytest.fixture(scope="module") def fitted(pipeline_data): - """The nested-CV ridge fit. One fit shared by the recovery tests.""" data = pipeline_data["data"] model = pipeline_data["trainer"].model metrics, weights, alphas = model.fit_predict( @@ -115,71 +91,24 @@ def fitted(pipeline_data): return {"metrics": metrics, "weights": weights, "alphas": alphas} -# ========================================================================== -# Structural -# ========================================================================== - -def test_assembly_top_level_structure(assembly): - """Top-level attributes mirror SimpleNeuroidAssembly's contract.""" - assert assembly.stories == ["synthstory0", "synthstory1", "synthstory2"] - assert assembly.dims == ("presentation", "neuroid") - assert assembly.get_validation_method() == "outer" - assert set(assembly.story_data) == set(assembly.stories) - - expected_rows = sum(sd.brain_data.shape[0] for sd in assembly.story_data.values()) - assert assembly.shape == (expected_rows, N_VERTICES) - assert assembly.data.shape == assembly.shape - - -def test_story_field_shapes_match_lebel_conventions(assembly, truth): - """Word-clock fields agree with each other; TR-clock fields agree with each other.""" +def test_fixture_matches_lebel_conventions(assembly, truth): + total_brain_rows = 0 for name in assembly.stories: sd = assembly.story_data[name] st = truth.stories[name] - # Word clock: one entry per word. + assert len(sd.split_indices) + 1 == len(sd.tr_times) + assert sd.brain_data.shape[0] == st.n_trs - BRAIN_TRIM_TOTAL assert len(sd.words) == st.n_words assert len(sd.stimuli) == st.n_words - assert sd.data_times.shape == (st.n_words,) - - # TR clock: one entry per TR. - assert sd.tr_times.shape == (st.n_trs,) + assert len(sd.data_times) == st.n_words assert sd.word_rates.shape == (st.n_trs, 1) + total_brain_rows += sd.brain_data.shape[0] - # Brain data is 15 TRs shorter: 10 trimmed at the head, 5 at the tail. - assert sd.brain_data.shape == (st.n_trs - BRAIN_TRIM_TOTAL, N_VERTICES) - - # Optional fields, as in the packaged LeBel assembly. - assert sd.temporal_baseline is None - assert sd.mask_indices is None - - # Word onsets are sorted and land inside the run. - assert np.all(np.diff(sd.data_times) > 0) - assert sd.data_times.min() >= sd.tr_times[0] - assert sd.data_times.max() < sd.tr_times[-1] + TR - - -def test_split_indices_are_legacy_cut_points(assembly, truth): - """split_indices are np.split cut points into the word axis, not per-word labels. - - This is the invariant that holds for all 25 stories of the real assembly: - len(split_indices) + 1 == len(tr_times). - """ - for name in assembly.stories: - sd = assembly.story_data[name] - st = truth.stories[name] - si = np.asarray(sd.split_indices) - - assert si.size + 1 == len(sd.tr_times) - assert np.all(np.diff(si) >= 0), "cut points must be non-decreasing" - assert si.min() >= 0 - assert si.max() <= st.n_words - # Empty TRs show up as repeated cut points, not as missing entries. - assert np.unique(si).size < si.size + assert assembly.shape == (total_brain_rows, N_VERTICES) def test_legacy_average_matches_independent_reference(assembly, truth): - """LegacyAverageDownsampler == averaging each TR's words, computed from counts.""" ds = Downsampler() for name in assembly.stories: sd = assembly.story_data[name] @@ -197,11 +126,7 @@ def test_legacy_average_matches_independent_reference(assembly, truth): def test_legacy_average_leaves_empty_trs_as_zero_rows(assembly, truth): - """TRs with no words come back as exact zero rows, not NaN and not interpolated. - - Worth pinning: a silent TR is indistinguishable from a genuinely zero feature, - so downstream code must not treat "all zero" as missing data. - """ + """Empty TRs come back as exact zero rows, not NaN.""" ds = Downsampler() name = assembly.stories[0] sd = assembly.story_data[name] @@ -225,7 +150,6 @@ def test_legacy_average_leaves_empty_trs_as_zero_rows(assembly, truth): @pytest.mark.parametrize("method", ["legacy_average", "legacy_sum", "legacy_last"]) def test_legacy_downsamplers_return_one_row_per_tr(assembly, truth, method): - """All three legacy methods use np.split, so all produce len(split_indices)+1 rows.""" ds = Downsampler() name = assembly.stories[0] sd = assembly.story_data[name] @@ -244,14 +168,8 @@ def test_legacy_downsamplers_return_one_row_per_tr(assembly, truth, method): @pytest.mark.parametrize("method", ["average", "sum", "last"]) def test_nonlegacy_downsamplers_misread_split_indices(assembly, truth, method): - """Pin a known bug: the non-legacy methods read split_indices as per-word TR labels. - - They compute ``max(split_indices) + 1`` rows, which for this convention is - roughly the word count rather than the TR count. Only the ``legacy_*`` methods - are usable with these assemblies. If this test ever fails because the output is - now (n_trs, ...), the bug has been fixed and this test should become the - positive assertion instead. - """ + """Known bug: non-legacy methods read split_indices as per-word TR labels and + return max(split_indices) + 1 rows (~n_words) instead of n_trs.""" ds = Downsampler() name = assembly.stories[0] sd = assembly.story_data[name] @@ -273,7 +191,6 @@ def test_nonlegacy_downsamplers_misread_split_indices(assembly, truth, method): "method", ["legacy_average", "legacy_sum", "legacy_last", "average", "sum", "last"] ) def test_downsamplers_require_split_indices(assembly, truth, method): - """Omitting split_indices is a loud error, not a silent fallback.""" ds = Downsampler() sd = assembly.story_data[assembly.stories[0]] st = truth.stories[assembly.stories[0]] @@ -288,14 +205,12 @@ def test_downsamplers_require_split_indices(assembly, truth, method): def test_fir_expansion_matches_reference(assembly, truth): - """FIR.make_delayed stacks one block per delay, in the order given.""" st = truth.stories[assembly.stories[0]] delayed = FIR.make_delayed(st.tr_features, FIR_DELAYS) assert delayed.shape == (st.n_trs, N_FEATURES * len(FIR_DELAYS)) np.testing.assert_allclose(delayed, reference_make_delayed(st.tr_features, FIR_DELAYS)) - # Block d holds features shifted forward by d, zero-padded at the front. for block, d in enumerate(FIR_DELAYS): cols = slice(block * N_FEATURES, (block + 1) * N_FEATURES) assert np.all(delayed[:d, cols] == 0.0) @@ -303,7 +218,6 @@ def test_fir_expansion_matches_reference(assembly, truth): def test_structure_data_shapes_and_story_split(pipeline_data, assembly, truth): - """Trimming pairs features with targets row-for-row, and the last story is held out.""" features = pipeline_data["features"] delayed = pipeline_data["delayed"] data = pipeline_data["data"] @@ -326,20 +240,14 @@ def test_structure_data_shapes_and_story_split(pipeline_data, assembly, truth): assert data["Pstim"].shape == (expected_test, N_FEATURES * len(FIR_DELAYS)) assert data["Presp"].shape == (expected_test, N_VERTICES) - # Features and targets must line up row-for-row, which nothing in - # _create_train_test_split actually checks. + # _create_train_test_split does not check that features and targets line up. assert data["Rstim"].shape[0] == data["Rresp"].shape[0] assert data["Pstim"].shape[0] == data["Presp"].shape[0] assert np.isfinite(data["Rstim"]).all() assert np.isfinite(data["Pstim"]).all() -# ========================================================================== -# Recovery -# ========================================================================== - def test_recovers_planted_signal_vertices(fitted, truth): - """Vertices 0..9 carry the planted signal and should be predicted well.""" correlations = np.asarray(fitted["metrics"]["correlations"]) assert correlations.shape == (N_VERTICES,) @@ -350,27 +258,22 @@ def test_recovers_planted_signal_vertices(fitted, truth): def test_noise_vertices_are_not_predicted(fitted, truth): - """Everything past vertex 9 is noise and must not be predictable.""" correlations = np.asarray(fitted["metrics"]["correlations"]) noise_r = np.abs(correlations[truth.noise_vertices]) assert np.median(noise_r) < 0.12 assert np.percentile(noise_r, 99) < 0.35 - # And the signal vertices must stand clearly apart from the noise floor. signal_r = correlations[truth.signal_vertices] assert signal_r.min() > np.percentile(noise_r, 99.9) def test_fdr_selects_the_planted_vertices(fitted, truth): - """FDR correction should flag the planted vertices and few others.""" significant = np.asarray(fitted["metrics"]["significant_mask"], dtype=bool) assert significant[truth.signal_vertices].all() - # Allow a handful of false positives, but nothing like a whole-brain flag. assert significant.sum() < 5 * N_SIGNAL_VERTICES def test_recovered_kernel_peaks_at_planted_lags(fitted, truth): - """The learned FIR kernel bumps at lags 2 and 3, and is flat at lags 1 and 4.""" weights = fitted["weights"] assert weights.shape == (N_FEATURES * len(FIR_DELAYS), N_VERTICES) @@ -388,7 +291,6 @@ def test_recovered_kernel_peaks_at_planted_lags(fitted, truth): f"kernel did not peak at lags {PLANTED_LAGS}: {signal_norms}" ) - # Noise vertices should have no structured kernel at all. noise_norm = float(np.linalg.norm(by_lag[:, :, truth.noise_vertices])) per_vertex_noise = noise_norm / np.sqrt(len(truth.noise_vertices)) per_vertex_signal = min(planted) / np.sqrt(N_SIGNAL_VERTICES) @@ -396,7 +298,6 @@ def test_recovered_kernel_peaks_at_planted_lags(fitted, truth): def test_trainer_train_runs_offline_and_reports_metrics(assembly, tmp_path): - """trainer.train() end to end, with logging and brain plotting stubbed out.""" trainer = make_trainer(assembly, tmp_path) assert isinstance(trainer.experiment_logger, _NullLogger) assert isinstance(trainer.brain_plotter, _NullBrainPlotter) @@ -408,22 +309,13 @@ def test_trainer_train_runs_offline_and_reports_metrics(assembly, tmp_path): assert metrics["median_score"] == pytest.approx(float(np.median(correlations))) assert 0 < metrics["n_significant"] < 5 * N_SIGNAL_VERTICES - # Metrics reached the logger and the plotter was invoked but drew nothing. assert "median_correlation" in trainer.experiment_logger.scalars assert trainer.brain_plotter.calls == 1 - - # ModelSaver wrote under the temp results dir, not into the repo. assert any(tmp_path.rglob("hyperparams.json")) -# ========================================================================== -# Leakage and ordering -# ========================================================================== - def test_fir_is_causal(assembly, truth): - """No delay is negative, and perturbing TR t never changes rows before t.""" - assert all(d > 0 for d in FIR_DELAYS), "a delay <= 0 would expose the present/future" - + """Perturbing TR t never changes delayed rows before t.""" st = truth.stories[assembly.stories[0]] base = FIR.make_delayed(st.tr_features, FIR_DELAYS) @@ -437,18 +329,12 @@ def test_fir_is_causal(assembly, truth): assert changed_rows.min() > perturb_at, ( "a future timepoint leaked into an earlier delayed row" ) - # Only the planted delays' worth of rows should move. assert set(changed_rows.tolist()) == {perturb_at + d for d in FIR_DELAYS} def test_held_out_story_cannot_influence_training_matrix(pipeline_data, assembly): - """Corrupting the held-out story leaves the training matrices bit-identical. - - Poisoning is a sharper check than comparing row counts: if any test-story value - reached X_train or Y_train, the training matrices would move. Both the features - and the brain data of the held-out story are corrupted, so the check covers - predictors and targets. - """ + """NaN-poisoning the held-out story's features and brain data leaves the + training matrices bit-identical.""" trainer = pipeline_data["trainer"] baseline = pipeline_data["data"] test_story = assembly.stories[-1] @@ -469,19 +355,13 @@ def test_held_out_story_cannot_influence_training_matrix(pipeline_data, assembly np.testing.assert_array_equal(data["Rstim"], baseline["Rstim"]) np.testing.assert_array_equal(data["Rresp"], baseline["Rresp"]) - # The poison did land on the test side, so the check above is not vacuous. assert not np.array_equal(data["Pstim"], baseline["Pstim"]) assert np.isnan(data["Presp"]).all() def test_nan_features_are_silently_zeroed(pipeline_data, assembly): - """Pin a silent-failure path: NaN *features* are laundered by np.nan_to_num. - - _create_train_test_split wraps X_train/X_test in np.nan_to_num but leaves - Y_train/Y_test alone. A feature extractor that starts emitting NaN therefore - produces an all-zero predictor block and a plausible-looking fit instead of an - error, while the same corruption in the targets propagates loudly. - """ + """_create_train_test_split applies np.nan_to_num to features but not targets, so + NaN features become zeros and NaN targets stay NaN; neither raises.""" trainer = pipeline_data["trainer"] test_story = assembly.stories[-1] @@ -490,33 +370,13 @@ def test_nan_features_are_silently_zeroed(pipeline_data, assembly): data = trainer.structure_data(poisoned) - assert np.all(data["Pstim"] == 0.0), "NaN features are converted to zeros, not raised" + assert np.all(data["Pstim"] == 0.0) assert np.isfinite(data["Presp"]).all() -def test_train_and_test_draw_from_disjoint_stories(pipeline_data, assembly, truth): - """The split is by story: the last one is test, everything before it is train.""" - trainer = pipeline_data["trainer"] - stories = list(pipeline_data["features"].keys()) - - assert stories == assembly.stories - train_stories, test_stories = stories[:-1], stories[-1:] - assert set(train_stories).isdisjoint(test_stories) - assert len(test_stories) == 1 - - # Row budget accounts for every train row, leaving no room for test rows. - expected = sum(truth.stories[s].n_trs - BRAIN_TRIM_TOTAL for s in train_stories) - assert pipeline_data["data"]["Rstim"].shape[0] == expected - - def test_each_split_is_zscored_independently(pipeline_data, assembly): - """z-scoring happens per story within a split; train data cannot shift the test set. - - Note this also documents that the *test* split is standardised with its own - statistics rather than the training set's -- standard in this literature, but - it is test-set information entering the test features, so it is pinned here - deliberately rather than by accident. - """ + """Each story is z-scored within its split; the test split uses its own + statistics, not the training set's.""" trainer = pipeline_data["trainer"] delayed = pipeline_data["delayed"] baseline = pipeline_data["data"] @@ -527,101 +387,16 @@ def test_each_split_is_zscored_independently(pipeline_data, assembly): data = trainer.structure_data(scaled) - # Test split untouched by the train-side rescaling. np.testing.assert_allclose(data["Pstim"], baseline["Pstim"]) - # And z-scoring makes the train split invariant to affine rescaling. np.testing.assert_allclose(data["Rstim"], baseline["Rstim"], atol=1e-8) - # Each split is standardised with its own statistics. assert np.allclose(baseline["Pstim"].mean(axis=0), 0.0, atol=1e-8) assert np.allclose(baseline["Pstim"].std(axis=0), 1.0, atol=1e-6) -def test_alignment_is_load_bearing(pipeline_data, truth): - """Break the temporal alignment and the recovered correlation collapses. - - Guards against a result that looks good for the wrong reason: if prediction - survived an arbitrary time shift, the correlation would be coming from - something other than the planted lag structure. - """ - data = pipeline_data["data"] - signal = truth.signal_vertices - - aligned = ridge_fit_predict(data["Rstim"], data["Rresp"][:, signal], data["Pstim"]) - aligned_r = column_correlations(aligned, data["Presp"][:, signal]) - assert np.median(aligned_r) > 0.7 - - # A shift well outside the delay set, so no lag can absorb it. - shift = 37 - rolled_train = np.roll(data["Rstim"], shift, axis=0) - rolled_test = np.roll(data["Pstim"], shift, axis=0) - rolled = ridge_fit_predict(rolled_train, data["Rresp"][:, signal], rolled_test) - rolled_r = column_correlations(rolled, data["Presp"][:, signal]) - - assert np.median(np.abs(rolled_r)) < 0.2 - assert np.median(aligned_r) > 3 * np.median(np.abs(rolled_r)) - - -def test_pipeline_order_is_downsample_then_fir(pipeline_data, assembly, truth): - """Downsampling must precede FIR expansion; the row counts pin the order. - - Expanding word-level features first would give one row per word and silently - misalign everything downstream, so the two orders are not interchangeable. - """ - features = pipeline_data["features"] - delayed = pipeline_data["delayed"] - - for name in assembly.stories: - st = truth.stories[name] - - assert features[name].shape[0] == st.n_trs - assert features[name].shape[0] != st.n_words - - assert delayed[name].shape == (st.n_trs, N_FEATURES * len(FIR_DELAYS)) - - # The other order produces a word-length matrix that cannot pair with brain data. - fir_first = FIR.make_delayed(st.word_features, FIR_DELAYS) - assert fir_first.shape[0] == st.n_words - assert fir_first.shape[0] != assembly.story_data[name].brain_data.shape[0] - - -def test_trimming_config_pairs_features_with_past_tr_only(truth): - """The trimming offsets keep every predictor at or before its target's TR. - - Brain row j is paired with feature row j + 10, whose planted lags point at TRs - j + 8 and j + 7. Both precede the feature TR, so no target is predicted from - its own future. - """ - feature_offset = TRIMMING_CONFIG["train_features_start"] - target_offset = TRIMMING_CONFIG["train_targets_start"] - assert feature_offset - target_offset == BRAIN_TRIM_HEAD - - for lag in PLANTED_LAGS: - source_tr = feature_offset - lag - assert 0 <= source_tr < feature_offset, "predictor must come from a past TR" - - # The test split uses different offsets but must preserve the same relationship. - assert ( - TRIMMING_CONFIG["test_features_start"] - TRIMMING_CONFIG["test_targets_start"] - == BRAIN_TRIM_HEAD - ) - assert TRIMMING_CONFIG["train_features_end"] == -BRAIN_TRIM_TAIL - assert TRIMMING_CONFIG["test_features_end"] == -BRAIN_TRIM_TAIL - - def test_determinism(pipeline_data, monkeypatch): - """The same seed reproduces the correlation vector; a different fold seed does not. - - The second half is what stops this passing vacuously. Note it has to compare the - *correlation arrays*: changing the fold seed reshuffles which alpha each voxel - gets, but on this fixture it moves the median by only ~5e-6 and leaves - n_significant unchanged, so asserting on either of those would pass no matter - what the pipeline did. - - ``fit_predict`` exposes no seed argument -- ``_find_best_alphas`` calls - ``create_folds`` without one, so the fold seed is always the default 0. The - alternate seed is injected by patching that call site. - """ + """Compares correlation vectors because a different fold seed barely moves the + median (~5e-6) and leaves n_significant unchanged on this fixture.""" data = pipeline_data["data"] model = pipeline_data["trainer"].model @@ -638,38 +413,21 @@ def fit(): first, first_alphas = fit() second, second_alphas = fit() - # Same seed, same everything: reproducible. assert np.allclose(first, second, rtol=0, atol=1e-12) np.testing.assert_array_equal(first_alphas, second_alphas) - # Different fold seed: a genuinely different model. import encoding.models.nested_cv as nested_cv_mod from encoding.models.folding import create_folds as real_create_folds - def seeded_create_folds(n_samples, fold_type, n_folds, chunk_length=None, - trim_size=None, groups=None, seed=0): - return real_create_folds( - n_samples, fold_type, n_folds, chunk_length, trim_size, groups, seed=7 - ) - - monkeypatch.setattr(nested_cv_mod, "create_folds", seeded_create_folds) + # fit_predict takes no seed; _find_best_alphas calls create_folds with the default. + monkeypatch.setattr( + nested_cv_mod, + "create_folds", + lambda *a, **k: real_create_folds(*a, **{**k, "seed": 7}), + ) other, other_alphas = fit() assert not np.allclose(first, other, rtol=0, atol=1e-12), ( - "changing the inner-CV fold seed produced an identical correlation vector, " - "which means the seed is not reaching create_folds and the first half of " - "this test proves nothing" + "fold seed 7 gave the same correlations as seed 0" ) assert (first_alphas != other_alphas).any(), "no voxel changed its selected alpha" - - -def test_fixture_is_deterministic(): - """Same seed, same assembly -- so a failure is reproducible.""" - a = synthetic_assembly(n_stories=2, n_trs=(60, 60), n_vertices=64, seed=3) - b = synthetic_assembly(n_stories=2, n_trs=(60, 60), n_vertices=64, seed=3) - - for name in a.stories: - np.testing.assert_array_equal( - a.story_data[name].brain_data, b.story_data[name].brain_data - ) - assert a.story_data[name].split_indices == b.story_data[name].split_indices From ec31915a05daede3edfd31ae9966bec556e5c5a9 Mon Sep 17 00:00:00 2001 From: Aadhav Thaniga Date: Mon, 12 Oct 2026 18:31:32 -0400 Subject: [PATCH 6/9] make non-legacy downsampler test a strict xfail --- tests/test_pipeline_synthetic.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/tests/test_pipeline_synthetic.py b/tests/test_pipeline_synthetic.py index 90f9d14..a8cd327 100644 --- a/tests/test_pipeline_synthetic.py +++ b/tests/test_pipeline_synthetic.py @@ -166,8 +166,13 @@ def test_legacy_downsamplers_return_one_row_per_tr(assembly, truth, method): assert out.shape[0] == len(sd.split_indices) + 1 +@pytest.mark.xfail( + strict=True, + reason="non-legacy downsamplers read split_indices as per-word TR labels " + "and return ~n_words rows", +) @pytest.mark.parametrize("method", ["average", "sum", "last"]) -def test_nonlegacy_downsamplers_misread_split_indices(assembly, truth, method): +def test_nonlegacy_downsamplers_return_one_row_per_tr(assembly, truth, method): """Known bug: non-legacy methods read split_indices as per-word TR labels and return max(split_indices) + 1 rows (~n_words) instead of n_trs.""" ds = Downsampler() @@ -182,9 +187,7 @@ def test_nonlegacy_downsamplers_misread_split_indices(assembly, truth, method): method=method, split_indices=sd.split_indices, ) - assert out.shape[0] == max(sd.split_indices) + 1 - assert out.shape[0] != st.n_trs - assert out.shape[0] > st.n_trs + assert out.shape == (st.n_trs, N_FEATURES) @pytest.mark.parametrize( From 3b2640691c4981557fd0a756b11f781dc2d225a6 Mon Sep 17 00:00:00 2001 From: Aadhav Thaniga Date: Mon, 12 Oct 2026 18:35:30 -0400 Subject: [PATCH 7/9] regenerate golden metadata --- tests/fixtures/golden_lebel_uts03.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/fixtures/golden_lebel_uts03.json b/tests/fixtures/golden_lebel_uts03.json index b79c872..b55e1c2 100644 --- a/tests/fixtures/golden_lebel_uts03.json +++ b/tests/fixtures/golden_lebel_uts03.json @@ -6,8 +6,8 @@ "env_var": "LITCODER_LEBEL_ASSEMBLY" }, "run": { - "date": "2026-09-17", - "commit": "a53ee0f9d989e218b98b528b69588c2ce5497273", + "date": "2026-10-12", + "commit": "ec31915a05daede3edfd31ae9966bec556e5c5a9", "script": "train_simple.py", "machine": "macOS, Apple Silicon, MPS (linalg_svd falls back to CPU)", "env": "conda env 'litcoder'", @@ -153,5 +153,5 @@ "command": "LITCODER_LEBEL_ASSEMBLY=/path/to/assembly_lebel_uts03.pkl python tests/test_golden_lebel.py --update", "when": "Run this only when a change to the pipeline is intended. It rewrites metrics, quantiles, threshold_counts, shapes and the environment fingerprint from a fresh run, and leaves tolerances and notes alone. Review the diff: a change you did not expect is the test doing its job." }, - "notes": "Baseline generated locally rather than on PACE. An earlier run recorded on 2026-08 (median 0.043, 2853 significant voxels) is NOT comparable to this one and must not be used to justify a tolerance. That run predates commit 33e167b ('seed fold shuffling for reproducible splits'); before it, create_chunked_folds called bare random.shuffle() on the global unseeded RNG, so the inner-CV folds differed on every invocation and the fit was a different model each time. The gap between the two recorded numbers is therefore not evidence of environmental variance, and the August run is not reproducible by current code on any machine." + "notes": "Baseline generated locally rather than on PACE. An earlier run recorded on 2026-08 (median 0.043, 2853 significant voxels) is NOT comparable to this one and must not be used to justify a tolerance. That run predates the commit 'seed fold shuffling for reproducible splits'; before it, create_chunked_folds called bare random.shuffle() on the global unseeded RNG, so the inner-CV folds differed on every invocation and the fit was a different model each time. The gap between the two recorded numbers is therefore not evidence of environmental variance, and the August run is not reproducible by current code on any machine." } From 8a9ca6f0388a0ad3801ee7cca23c248b32569f52 Mon Sep 17 00:00:00 2001 From: Aadhav Thaniga Date: Tue, 3 Nov 2026 19:04:14 -0500 Subject: [PATCH 8/9] Add ECoG encoding and temporal validation support --- README.md | 89 ++++ encoding/assembly/__init__.py | 1 + encoding/assembly/assemblies.py | 17 +- encoding/assembly/assembly_generator.py | 56 +- encoding/assembly/base_processor.py | 116 +---- encoding/assembly/context.py | 128 +++++ encoding/assembly/ecog_processor.py | 365 +++++++++++++ encoding/assembly/story_data.py | 8 +- encoding/ecog_temporal.py | 449 ++++++++++++++++ encoding/features/embeddings.py | 19 +- encoding/features/factory.py | 41 +- encoding/models/estimator.py | 136 +++++ encoding/models/folding.py | 68 ++- encoding/models/nested_cv.py | 660 ++++++++++++++++++------ encoding/models/ridge_regression.py | 8 +- encoding/plotting/plotting_utils.py | 67 ++- encoding/trainer.py | 148 +++++- encoding/utils.py | 193 ++++--- tests/conftest.py | 3 + tests/test_ecog_assembly.py | 319 ++++++++++++ tests/test_ecog_end_to_end.py | 334 ++++++++++++ tests/test_ecog_temporal.py | 313 +++++++++++ tests/test_results_saving.py | 299 +++++++++++ tests/test_shared_fixes.py | 315 +++++++++++ tests/test_supplied_estimators.py | 166 ++++++ unified.py | 22 +- 26 files changed, 3879 insertions(+), 461 deletions(-) create mode 100644 encoding/assembly/context.py create mode 100644 encoding/assembly/ecog_processor.py create mode 100644 encoding/ecog_temporal.py create mode 100644 encoding/models/estimator.py create mode 100644 tests/test_ecog_assembly.py create mode 100644 tests/test_ecog_end_to_end.py create mode 100644 tests/test_ecog_temporal.py create mode 100644 tests/test_results_saving.py create mode 100644 tests/test_shared_fixes.py create mode 100644 tests/test_supplied_estimators.py diff --git a/README.md b/README.md index d159e4f..7809a2d 100644 --- a/README.md +++ b/README.md @@ -117,6 +117,95 @@ Tutorials from documentation: - [Embeddings](https://gt-lit-lab.github.io/litcoder_core/tutorial_embeddings.html) - [Speech](https://gt-lit-lab.github.io/litcoder_core/tutorial_speech.html) +### Supplied scikit-learn regressors + +```python +from sklearn.linear_model import Ridge +from sklearn.pipeline import make_pipeline +from sklearn.preprocessing import StandardScaler + +model = NestedCVModel( + "scaled_ridge", + estimator=make_pipeline(StandardScaler(), Ridge()), + param_grid={"ridge__alpha": [0.1, 1.0, 10.0]}, +) +``` + +Pass this model to `AbstractTrainer` or call `model.fit_predict` directly. +Omit `param_grid` to fit with the supplied parameters. Grid selection maximizes +mean finite Pearson correlation over inner validation folds and targets, using +one parameter setting for all targets. Ties use the first grid candidate. +Estimator fits, Pipeline transforms and optional LITCoder fold normalization +use the corresponding training subset. Legacy fMRI per-story standardization +is upstream of these fits. Pipeline caching must be disabled. +Use an explicit random seed for stochastic estimators. + +The CPU path accepts cloneable regressors that fit NumPy float32 arrays and +predict a finite numeric value per row and target. Native mode uses a 1-D +target for one eligible column and requires advertised multi-output support +for multiple eligible columns. Set `target_mode="per_target"` to fit a separate +clone to each eligible column with the same selected parameters. Invalid targets +retain their positions. Supply estimator parameters in their own units. +For Ridge parity, use LITCoder's effective squared penalty as sklearn's +`alpha` and match intercept, normalization, and singular-value settings. +The built-in ridge path retains its existing convention. + +Supplied estimators return `None` for the two ridge array summaries. Fitted +estimators and transforms are stored per fold and replayed with +`NestedCVModel.predict_fold` on the prepared design. Nested CV has no final +refit. Load pickle artifacts only from trusted sources with compatible +scikit-learn and custom estimator versions. The ECoG memory preflight uses +the existing design and ridge-workspace estimate. Estimator-specific memory +usage can exceed that estimate. + +### Continuous ECoG + +Use `ECoGAssemblyGenerator(data_dir).generate_assembly(subject)` with a version 1 +`ecog.json` manifest, or pass preprocessed recording mappings as `recordings=`. +Each recording supplies a uniform neural grid, sampling rate, signal and time +units, ordered electrodes, transcript onsets, clocks or an explicit affine +synchronization, and preprocessing provenance. Supply `valid_samples` for +assessed-valid rows and optional disjoint `unknown_samples` for unannotated rows. +Rows in neither mask are known-invalid. Keep original rows and clocks through +gaps. Recordings pooled together must have the same electrode order and units. + +Pass the assembly to `AbstractTrainer` with `fir_delays=None`, +`downsampler=None`, empty trimming and `ecog_temporal_config`. Supply one +`feature_specs` entry per extractor. Methods are `word_sum`, `word_mean`, +`word_last`, `words_per_bin`, `words_per_second`, and `speech_linear`. +Empty bins are zero. Declare missing stimulus intervals in neural seconds. +Speech needs mapped frame seconds, an origin and a maximum interpolation gap. +Interpolation can use future frames. Dependency intervals cover the known +context windows, carried-forward embeddings, and interpolation endpoints. +Stateful context resets conservatively depend on the preceding recording prefix. +Declare the full support of externally generated contexts, audio resampling +and other upstream operations. For speech, use identified immutable audio +because the cache keys by path. ECoG Lanczos, neural resampling and +event-aligned analysis are outside this path. + +Set `delays_s` explicitly. Positive delays use earlier stimulus features. +Rounding is to the nearest sample, with ties away from zero. Negative delays +require `retrospective=True`. Use a configurable `memory_budget_bytes` for +preflight. The estimate covers the expanded design and major ridge arrays, +with feature extraction and exact process peak usage outside its guarantee. + +For held-out descriptive Pearson scores, choose `protocol="blocked"` or +`"recording"` with an explicit embargo and justified neural preprocessing +support. Purges use original time coordinates. Dependency exclusion does not +establish independence. Inference is marked `not_assessed`. For an engineering +fit/replay check, choose `protocol="diagnostic_in_sample"` and supply one +positive built-in ridge alpha via `trainer.train(alphas=[...])`. This explicitly +admits finite unknown-quality rows while excluding known-invalid rows and +missing feature dependencies. Unknown neural preprocessing support is +preserved as unknown. The single diagnostic fit emits no held-out metrics +or significance outputs. + +Load trusted artifacts with `ModelSaver.load_encoding_result`. Replay an +identified fit with `NestedCVModel.predict_fold` on the same prepared design +in the recorded feature and sample order. Synthetic validation exercises +the encoding path. Real-data loading/alignment and diagnostic replay do not +establish independent predictive performance or exact paper replication. + ## 3) Quick tutorial: This library uses the same core modules across datasets, here's an example for Narratives: diff --git a/encoding/assembly/__init__.py b/encoding/assembly/__init__.py index 3531031..c6cf16b 100644 --- a/encoding/assembly/__init__.py +++ b/encoding/assembly/__init__.py @@ -1,2 +1,3 @@ from .assemblies import SimpleNeuroidAssembly from .assembly_loader import load_assembly, save_assembly, AssemblyLoader +from .ecog_processor import ECoGAssemblyGenerator diff --git a/encoding/assembly/assemblies.py b/encoding/assembly/assemblies.py index da9d367..bb83bf0 100644 --- a/encoding/assembly/assemblies.py +++ b/encoding/assembly/assemblies.py @@ -4,7 +4,7 @@ from typing import Dict, List, TYPE_CHECKING if TYPE_CHECKING: - from .assembly_generator import StoryData + from .story_data import StoryData class SimpleNeuroidAssembly: @@ -135,6 +135,21 @@ def get_word_rates(self) -> List[np.ndarray]: """ return [self.story_data[story].word_rates for story in self.stories] + def get_target_metadata(self): + """Ordered per-recording target metadata, or None for legacy assemblies.""" + return [getattr(self.story_data[story], "target_metadata", None) + for story in self.stories] + + def get_sample_metadata(self): + """Per-recording original identities/clocks/validity, without dropping rows.""" + return [getattr(self.story_data[story], "sample_metadata", None) + for story in self.stories] + + def get_provenance(self): + """Declared input provenance, or None if absent in an older assembly.""" + return [getattr(self.story_data[story], "provenance", None) + for story in self.stories] + def get_coord(self, name: str) -> np.ndarray: """Get coordinate values by name.""" return self.coords[name]["values"] diff --git a/encoding/assembly/assembly_generator.py b/encoding/assembly/assembly_generator.py index ea5aee1..a2962aa 100644 --- a/encoding/assembly/assembly_generator.py +++ b/encoding/assembly/assembly_generator.py @@ -1,18 +1,13 @@ """Assembly generator for brain data processing and organization.""" +from __future__ import annotations -from dataclasses import dataclass -from typing import List, Optional, Tuple -import numpy as np -import pandas as pd -import nibabel as nib -from nilearn import surface, datasets -from .base_processor import BaseAssemblyGenerator -from .narratives_processor import NarrativesAssemblyGenerator - -from .lpp_processor import LPPAssemblyGenerator -from .lebel_processor import LebelAssemblyGenerator +from typing import Optional, TYPE_CHECKING from .assemblies import SimpleNeuroidAssembly -from transformers import GPT2Tokenizer + +if TYPE_CHECKING: + from transformers import GPT2Tokenizer + from .base_processor import BaseAssemblyGenerator + from .ecog_processor import ECoGAssemblyGenerator class AssemblyGenerator: @@ -27,11 +22,11 @@ def create( mask_path: Optional[str] = None, analysis_mask_path: Optional[str] = None, tokenizer: Optional[GPT2Tokenizer] = None, - ) -> BaseAssemblyGenerator: + ) -> BaseAssemblyGenerator | ECoGAssemblyGenerator: """Create a dataset-specific assembly generator. Args: - dataset_type: Type of dataset ('narratives', 'lpp', or 'lebel') + dataset_type: 'narratives', 'lpp', 'lebel', or 'ecog' data_dir: Base directory containing subject data tr: TR value for timing calculations use_volume: Whether to use volume data instead of surface data @@ -39,15 +34,30 @@ def create( Returns: BaseAssemblyGenerator: Dataset-specific assembly generator """ + if dataset_type == "ecog": + if tr != 1.5: + raise ValueError("ECoG uses recording sampling_rate_hz, not the fMRI tr argument") + if use_volume or mask_path is not None or analysis_mask_path is not None: + raise ValueError("fMRI volume/mask options do not apply to ECoG") + from .ecog_processor import ECoGAssemblyGenerator + # tr is a legacy fMRI factory argument. ECoG always requires a + # declared sampling_rate_hz and timestamps in each recording. + return ECoGAssemblyGenerator(data_dir, tokenizer=tokenizer) + + if dataset_type not in {"narratives", "lpp", "lebel"}: + raise ValueError(f"Unsupported dataset type: {dataset_type}") + + # Do not force ECoG-only assembly loading through fMRI dependencies. + from .narratives_processor import NarrativesAssemblyGenerator + from .lpp_processor import LPPAssemblyGenerator + from .lebel_processor import LebelAssemblyGenerator + generators = { "narratives": NarrativesAssemblyGenerator, "lpp": LPPAssemblyGenerator, "lebel": LebelAssemblyGenerator, } - if dataset_type not in generators: - raise ValueError(f"Unsupported dataset type: {dataset_type}") - return generators[dataset_type]( data_dir, dataset_type, @@ -72,11 +82,12 @@ def generate_assembly( generate_temporal_baseline: bool = False, analysis_mask_path: Optional[str] = None, tokenizer: Optional[GPT2Tokenizer] = None, + recordings=None, ) -> SimpleNeuroidAssembly: """Generate assembly for a subject using the appropriate dataset processor. Args: - dataset_type: Type of dataset ('narratives', 'lpp', or 'lebel') + dataset_type: 'narratives', 'lpp', 'lebel', or 'ecog' data_dir: Base directory containing subject data subject: Subject identifier tr: TR value for timing calculations @@ -86,10 +97,14 @@ def generate_assembly( use_volume: Whether to use volume data instead of surface data mask_path: Path to mask file for volume data tokenizer: Tokenizer for encoding and decoding text (default: GPT2Tokenizer) + recordings: Explicit preprocessed ECoG recording mappings, instead + of a data_dir manifest. Not supported for fMRI datasets. Returns: SimpleNeuroidAssembly: Generated assembly """ + if recordings is not None and dataset_type != "ecog": + raise ValueError("recordings is supported only for ECoG") generator = AssemblyGenerator.create( dataset_type, data_dir, @@ -99,6 +114,11 @@ def generate_assembly( analysis_mask_path, tokenizer, ) + if dataset_type == "ecog": + return generator.generate_assembly( + subject, lookback, context_type, correlation_length, + generate_temporal_baseline, recordings=recordings, + ) return generator.generate_assembly( subject, lookback, diff --git a/encoding/assembly/base_processor.py b/encoding/assembly/base_processor.py index de09078..224f415 100644 --- a/encoding/assembly/base_processor.py +++ b/encoding/assembly/base_processor.py @@ -15,12 +15,13 @@ VolumeProcessor, ) from .story_data import StoryData +from .context import StimulusContextMixin from .assemblies import SimpleNeuroidAssembly import pickle import logging -class BaseAssemblyGenerator(ABC): +class BaseAssemblyGenerator(StimulusContextMixin, ABC): """Abstract base class for assembly generation.""" def __init__( @@ -103,119 +104,6 @@ def _process_single_story( """ pass - def generate_stimuli_with_context( - self, transcript: pd.DataFrame, lookback: int - ) -> List[str]: - """Generate stimuli with token-based context window.""" - if self.context_type == "fullcontext": - return self._process_fullcontext(transcript, lookback) - elif self.context_type == "nocontext": - return self._process_nocontext(transcript, lookback) - elif self.context_type == "halfcontext": - return self._process_halfcontext(transcript, lookback) - else: - raise ValueError(f"Invalid context type: {self.context_type}") - - def _process_fullcontext( - self, transcript: pd.DataFrame, lookback: int - ) -> List[str]: - """Process story with full context window. - - Args: - transcript: DataFrame containing transcript data - lookback: Number of tokens to look back - - Returns: - List of processed stimuli with full context - """ - total_len = len(transcript["word_orig"]) - ds_data = transcript["word_orig"].astype(str) - stimuli = [] - print(f"this is the lookback: {lookback}") - print(f"heloo") - - for i, w in enumerate(ds_data): - if w != "": - text = " ".join(ds_data[max(0, i - lookback) : min(i + 1, total_len)]) - tokens = self.tokenizer.encode(text, add_special_tokens=False) - if len(tokens) > lookback: - tokens = tokens[-lookback:] - text = self.tokenizer.decode(tokens) - stimuli.append(text.strip()) - else: - stimuli.append("") - - return stimuli - - def _process_nocontext(self, transcript: pd.DataFrame, lookback: int) -> List[str]: - """Process story with no context window. - - Args: - transcript: DataFrame containing transcript data - lookback: Number of tokens to look back - - Returns: - List of processed stimuli with no context - """ - total_len = len(transcript["word_orig"]) - ds_data = transcript["word_orig"] - stimuli = [] - start_idx = 0 # Track where we start accumulating from - - for i, w in enumerate(ds_data): - if w != "": - # Get text from start_idx to current point - text = " ".join(ds_data[start_idx : i + 1]) - tokens = self.tokenizer.encode(text, add_special_tokens=False) - - if len(tokens) >= lookback: - # We've hit lookback, use current context and reset start_idx - stimuli.append(text.strip()) - start_idx = i + 1 # Start fresh from next word - else: - # Not enough tokens yet, use current context - stimuli.append(text.strip()) - else: - stimuli.append("") - - return stimuli - - def _process_halfcontext( - self, transcript: pd.DataFrame, lookback: int - ) -> List[str]: - """Process story with half context window using a sliding window approach. - - Args: - transcript: DataFrame containing transcript data - lookback: Number of tokens to look back - - Returns: - List of processed stimuli with half context window - """ - ds_data = transcript["word_orig"] - stimuli = [] - start = 0 - i = 0 - half_lookback = lookback // 2 - - while i < len(ds_data): - if ds_data[i] != "": - # Build text window from current start to i (inclusive) - text = " ".join(ds_data[start : i + 1]) - tokens = self.tokenizer.encode(text, add_special_tokens=False) - - # If token count exceeds lookback, reset window start - if len(tokens) > lookback: - start += half_lookback - continue - - stimuli.append(text.strip()) - else: - stimuli.append("") - i += 1 - - return stimuli - def apply_analysis_mask( self, brain_data: np.ndarray ) -> tuple[np.ndarray, np.ndarray]: diff --git a/encoding/assembly/context.py b/encoding/assembly/context.py new file mode 100644 index 0000000..daf4799 --- /dev/null +++ b/encoding/assembly/context.py @@ -0,0 +1,128 @@ +"""Shared stimulus context policies, without neural-data or model setup. + +The policies intentionally retain existing fMRI semantics. Tokenizer and +context_type must be provided by the caller; no tokenizer is downloaded here. +""" +from __future__ import annotations + +from typing import List, TYPE_CHECKING + +if TYPE_CHECKING: + import pandas as pd + + +class StimulusContextMixin: + def generate_stimuli_with_context( + self, transcript: pd.DataFrame, lookback: int, *, source_starts=None + ) -> List[str]: + """Generate stimuli with token-based context window.""" + if self.context_type == "fullcontext": + return self._process_fullcontext(transcript, lookback, source_starts=source_starts) + elif self.context_type == "nocontext": + return self._process_nocontext(transcript, lookback) + elif self.context_type == "halfcontext": + return self._process_halfcontext(transcript, lookback) + else: + raise ValueError(f"Invalid context type: {self.context_type}") + + def _process_fullcontext( + self, transcript: pd.DataFrame, lookback: int, *, source_starts=None + ) -> List[str]: + """Process story with full context window. + + Args: + transcript: DataFrame containing transcript data + lookback: Number of tokens to look back + + Returns: + List of processed stimuli with full context + """ + total_len = len(transcript["word_orig"]) + ds_data = transcript["word_orig"].astype(str) + stimuli = [] + print(f"this is the lookback: {lookback}") + print(f"heloo") + + for i, w in enumerate(ds_data): + if source_starts is not None: + source_starts.append(max(0, i - lookback) if w else i) + if w != "": + text = " ".join(ds_data[max(0, i - lookback) : min(i + 1, total_len)]) + tokens = self.tokenizer.encode(text, add_special_tokens=False) + if len(tokens) > lookback: + tokens = tokens[-lookback:] + text = self.tokenizer.decode(tokens) + stimuli.append(text.strip()) + else: + stimuli.append("") + + return stimuli + + def _process_nocontext(self, transcript: pd.DataFrame, lookback: int) -> List[str]: + """Process story with no context window. + + Args: + transcript: DataFrame containing transcript data + lookback: Number of tokens to look back + + Returns: + List of processed stimuli with no context + """ + total_len = len(transcript["word_orig"]) + ds_data = transcript["word_orig"] + stimuli = [] + start_idx = 0 # Track where we start accumulating from + + for i, w in enumerate(ds_data): + if w != "": + # Get text from start_idx to current point + text = " ".join(ds_data[start_idx : i + 1]) + tokens = self.tokenizer.encode(text, add_special_tokens=False) + + if len(tokens) >= lookback: + # We've hit lookback, use current context and reset start_idx + stimuli.append(text.strip()) + start_idx = i + 1 # Start fresh from next word + else: + # Not enough tokens yet, use current context + stimuli.append(text.strip()) + else: + stimuli.append("") + + return stimuli + + def _process_halfcontext( + self, transcript: pd.DataFrame, lookback: int + ) -> List[str]: + """Process story with half context window using a sliding window approach. + + Args: + transcript: DataFrame containing transcript data + lookback: Number of tokens to look back + + Returns: + List of processed stimuli with half context window + """ + ds_data = transcript["word_orig"] + stimuli = [] + start = 0 + i = 0 + half_lookback = lookback // 2 + + while i < len(ds_data): + if ds_data[i] != "": + # Build text window from current start to i (inclusive) + text = " ".join(ds_data[start : i + 1]) + tokens = self.tokenizer.encode(text, add_special_tokens=False) + + # If token count exceeds lookback, reset window start + if len(tokens) > lookback: + start += half_lookback + continue + + stimuli.append(text.strip()) + else: + stimuli.append("") + i += 1 + + return stimuli diff --git a/encoding/assembly/ecog_processor.py b/encoding/assembly/ecog_processor.py new file mode 100644 index 0000000..e4410ac --- /dev/null +++ b/encoding/assembly/ecog_processor.py @@ -0,0 +1,365 @@ +"""Load preprocessed continuous ECoG into the existing assembly interface. + +Input is a sequence of recording mappings, or ``ecog.json`` in data_dir (a JSON +manifest with schema_version=1 and recordings). Array fields in a manifest may +be JSON arrays or {"npy": "relative/path.npy"}; object/pickle arrays are not read. +There is no dataset-specific file discovery, preprocessing or resampling. + +Required recording fields: + recording_id, subject_id, brain_data [T,E], neural_times [T], sampling_rate_hz, + neural_time_unit, stimulus_time_unit (s/ms/us), neural_clock, stimulus_clock, + words, word_ids, stimulus_times [N], electrodes [E] (each has electrode_id), + signal_units, valid_samples [T] (boolean), provenance (source/preprocessing). +Optional unknown_samples [T] is a boolean mask disjoint from valid_samples. +Rows in neither mask are known-invalid. +Provide stimuli [N] and provenance.stimulus_context, or supply a tokenizer to +reuse the existing configurable context policies. No tokenizer is downloaded. + +Distinct clocks require synchronization={source_clock, target_clock, scale, +offset_s, provenance}: neural_seconds = scale * stimulus_seconds + offset_s. +Invalid intervals, if supplied, use start/stop in the declared neural clock/unit +and a reason; they must already agree with valid_samples. Invalid rows and +native times are retained. Gaps must be explicit invalid grid slots, not omitted +rows. The final bin is [last_time, last_time + 1/rate); all bins are half-open. +Only transcript bin boundaries and count/rate baselines are built here: no +feature alignment, delay expansion, exclusion dilation, or encoding integration. +""" +from copy import deepcopy +from pathlib import Path +import json +from collections.abc import Mapping + +import numpy as np + +from .assemblies import SimpleNeuroidAssembly +from .context import StimulusContextMixin +from .story_data import StoryData + + +_TIME_UNITS = {"s": 1.0, "ms": 1e-3, "us": 1e-6} +_ARRAY_FIELDS = ("brain_data", "neural_times", "stimulus_times", "valid_samples", "unknown_samples", "sample_ids") + + +def _text(value, field): + if not isinstance(value, str) or not value.strip(): + raise ValueError(f"{field} must be a non-empty string") + return value + + +def _number(value, field, positive=False): + if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, float, np.number)): + raise ValueError(f"{field} must be a finite real number") + if not np.isrealobj(value) or not np.isfinite(value) or (positive and value <= 0): + raise ValueError(f"{field} must be finite" + (" and positive" if positive else "")) + return float(value) + + +def _real_array(value, field, ndim): + try: + array = np.asarray(value) + except (TypeError, ValueError) as error: + raise ValueError(f"{field} must be a rectangular numeric array") from error + if array.ndim != ndim or array.dtype.kind not in "iuf": + raise ValueError(f"{field} must be a real numeric {ndim}-D array") + return array.copy() + + +def _ids(value, count, field): + array = np.asarray(value) + if array.ndim != 1 or len(array) != count: + raise ValueError(f"{field} must contain one ID per row ({count})") + # Do not stringify mixed IDs, merge numeric/string identities, or sort them. + values = list(value) + if any(not isinstance(x, (str, int, np.integer)) or isinstance(x, (bool, np.bool_)) + or (isinstance(x, str) and not x.strip()) for x in values): + raise ValueError(f"{field} IDs must be non-empty strings or integers") + if len(set(values)) != len(values): + raise ValueError(f"{field} must contain unique IDs") + return deepcopy(values) + + +class ECoGAssemblyGenerator(StimulusContextMixin): + """Small explicit input adapter; does not inherit fMRI setup/constructors.""" + + def __init__(self, data_dir=None, tokenizer=None): + self.data_dir = None if data_dir is None else Path(data_dir) + self.tokenizer = tokenizer + + def _read_manifest(self): + if self.data_dir is None: + raise ValueError("Supply recordings or an ECoG manifest data_dir") + path = self.data_dir / "ecog.json" if self.data_dir.is_dir() else self.data_dir + with path.open() as handle: + manifest = json.load(handle) + if (not isinstance(manifest, dict) or type(manifest.get("schema_version")) is not int + or manifest["schema_version"] != 1): + raise ValueError("ECoG manifest requires schema_version=1") + records = manifest.get("recordings") + if not isinstance(records, list): + raise ValueError("ECoG manifest recordings must be a list") + resolved = [] + for record in records: + if not isinstance(record, dict): + raise ValueError("Each recording must be a mapping") + record = deepcopy(record) + for field in _ARRAY_FIELDS: + value = record.get(field) + if isinstance(value, dict): + if set(value) != {"npy"}: + raise ValueError(f"{field} file reference must contain only 'npy'") + filename = _text(value["npy"], f"{field}.npy") + if Path(filename).suffix.lower() != ".npy": + raise ValueError(f"{field} file reference must be a .npy array") + loaded = np.load(path.parent / filename, allow_pickle=False) + if not isinstance(loaded, np.ndarray): + loaded.close() + raise ValueError(f"{field} must reference one .npy array") + record[field] = loaded + resolved.append(record) + return resolved + + def generate_assembly(self, subject, lookback=256, context_type="fullcontext", + correlation_length=100, generate_temporal_baseline=False, + *, recordings=None): + """Create one StoryData per recording; no rows are removed or reordered. + + Common factory arguments are retained; correlation_length is unused and + generating synthetic temporal baselines is not supported for ECoG. + Validation is not an assertion of safe temporal CV or preprocessing. + """ + _text(subject, "subject") + if generate_temporal_baseline: + raise ValueError("ECoG temporal baseline generation is outside assembly loading") + if context_type not in {"fullcontext", "nocontext", "halfcontext"}: + raise ValueError(f"Invalid context type: {context_type}") + if (isinstance(lookback, bool) or not isinstance(lookback, (int, np.integer)) + or lookback < (2 if context_type == "halfcontext" else 1)): + raise ValueError("lookback must be positive (at least 2 for halfcontext)") + self.context_type = context_type + records = self._read_manifest() if recordings is None else recordings + if not isinstance(records, (list, tuple)) or not records: + raise ValueError("recordings must be a non-empty list or tuple") + stories, names, electrode_order = [], set(), None + for record in records: + if not isinstance(record, Mapping): + raise ValueError("Each recording must be a mapping") + name = record.get("recording_id", "") + try: + story = self._recording(record, subject, lookback) + except (ValueError, KeyError, TypeError) as error: + raise ValueError(f"Recording {name!r}: {error}") from error + if story.name in names: + raise ValueError(f"Duplicate recording_id: {story.name}") + names.add(story.name) + current_order = [item["electrode_id"] for item in story.target_metadata] + if electrode_order is not None and current_order != electrode_order: + raise ValueError("Recordings must have identical electrode IDs/order; no implicit reordering") + if stories and story.brain_data.dtype != stories[0].brain_data.dtype: + raise ValueError("Recordings must use the same neural dtype; no implicit precision conversion") + if stories and story.sample_metadata["signal_units"] != stories[0].sample_metadata["signal_units"]: + raise ValueError("Recordings must use matching signal units") + electrode_order = current_order + stories.append(story) + assembly = SimpleNeuroidAssembly(stories, validation_method="unconfigured") + assembly.modality = "ecog" + assembly.recording_slices = {} + position = 0 + for story in stories: + assembly.recording_slices[story.name] = (position, position + len(story.brain_data)) + position += len(story.brain_data) + # ECoG sample coordinates are neural-grid rows, never transcript-word rows. + recording_ids = np.concatenate([np.repeat(story.name, len(story.brain_data)) for story in stories]) + assembly.coords = { + "story_id": {"dim": "presentation", "values": recording_ids}, + "recording_id": {"dim": "presentation", "values": recording_ids.copy()}, + "sample_index": {"dim": "presentation", "values": np.concatenate([ + np.arange(len(story.brain_data)) for story in stories])}, + "sample_id": {"dim": "presentation", "values": np.concatenate([ + np.asarray(story.sample_metadata["sample_ids"], dtype=object) + for story in stories])}, + "sample_time_s": {"dim": "presentation", "values": np.concatenate([ + story.tr_times for story in stories])}, + "valid_sample": {"dim": "presentation", "values": np.concatenate([ + story.sample_metadata["valid_samples"] for story in stories])}, + "unknown_sample": {"dim": "presentation", "values": np.concatenate([ + story.sample_metadata["unknown_samples"] for story in stories])}, + "electrode_id": {"dim": "neuroid", "values": np.asarray(electrode_order)}, + } + return assembly + + def _recording(self, record, subject, lookback): + name = _text(record["recording_id"], "recording_id") + if _text(record["subject_id"], "subject_id") != subject: + raise ValueError("subject_id must match the requested subject") + if "run_id" in record: + _text(record["run_id"], "run_id") + brain = _real_array(record["brain_data"], "brain_data", 2) + if brain.shape[0] < 2 or brain.shape[1] == 0: + raise ValueError("brain_data needs at least two samples and one electrode") + rate = _number(record["sampling_rate_hz"], "sampling_rate_hz", positive=True) + signal_units = _text(record["signal_units"], "signal_units") + neural_unit, stimulus_unit = record["neural_time_unit"], record["stimulus_time_unit"] + if neural_unit not in _TIME_UNITS or stimulus_unit not in _TIME_UNITS: + raise ValueError("Time units must be declared as s, ms, or us") + neural_clock = _text(record["neural_clock"], "neural_clock") + stimulus_clock = _text(record["stimulus_clock"], "stimulus_clock") + raw_grid = _real_array(record["neural_times"], "neural_times", 1) + grid = raw_grid.astype(float) * _TIME_UNITS[neural_unit] + if len(grid) != len(brain) or not np.isfinite(grid).all(): + raise ValueError("neural_times must be finite and match brain_data rows") + period = 1.0 / rate + grid_atol = min(1e-9, period * 1e-6) + if (np.any(np.diff(grid) <= 0) + or not np.isfinite(period) + or not np.allclose(np.diff(grid), period, rtol=1e-6, atol=grid_atol)): + raise ValueError("neural_times must be strictly increasing and uniform at sampling_rate_hz; retain missing slots") + end = grid[-1] + period + if not np.isfinite(end) or end <= grid[-1]: + raise ValueError("Recording end must be finite and representable at the declared rate") + valid = np.asarray(record["valid_samples"]) + if valid.dtype.kind != "b" or valid.shape != (len(brain),): + raise ValueError("valid_samples must be a boolean vector matching neural rows") + valid = valid.copy() + unknown = np.asarray(record.get("unknown_samples", np.zeros(len(brain), dtype=bool))) + if unknown.dtype.kind != "b" or unknown.shape != valid.shape or np.any(valid & unknown): + raise ValueError("unknown_samples must be boolean, match neural rows and be disjoint from valid_samples") + unknown = unknown.copy() + if not np.isfinite(brain[valid]).all(): + raise ValueError("Non-finite neural values require explicitly invalid samples") + reasons = deepcopy(record.get("invalid_sample_reasons")) + if reasons is not None: + if (not isinstance(reasons, (list, tuple)) or len(reasons) != len(brain) + or any(reason is not None and (not isinstance(reason, str) or not reason.strip()) + for reason in reasons)): + raise ValueError("invalid_sample_reasons must contain a reason or None for each neural row") + if any(reason is not None and good for reason, good in zip(reasons, valid | unknown)): + raise ValueError("invalid_sample_reasons must agree with valid_samples") + recording_metadata = deepcopy(record.get("recording_metadata", {})) + if not isinstance(recording_metadata, dict): + raise ValueError("recording_metadata must be a mapping") + provenance = deepcopy(record["provenance"]) + if not isinstance(provenance, dict): + raise ValueError("provenance must be a mapping with source and preprocessing") + _text(provenance.get("source"), "provenance.source") + if not isinstance(provenance.get("preprocessing"), dict) or not provenance["preprocessing"]: + raise ValueError("provenance.preprocessing must be a non-empty mapping") + electrodes = deepcopy(record["electrodes"]) + if not isinstance(electrodes, list) or len(electrodes) != brain.shape[1]: + raise ValueError("electrodes must match brain_data columns") + if any(not isinstance(item, dict) for item in electrodes): + raise ValueError("electrodes entries must be metadata mappings") + electrode_ids = [_text(item.get("electrode_id"), "electrode_id") for item in electrodes] + if len(set(electrode_ids)) != len(electrode_ids): + raise ValueError("electrode_id values must be unique") + for item in electrodes: + if "coordinates" in item: + xyz = _real_array(item["coordinates"], "electrode coordinates", 1) + if xyz.shape != (3,) or not np.isfinite(xyz).all(): + raise ValueError("electrode coordinates must contain three finite values") + _text(item.get("coordinate_space"), "coordinate_space") + _text(item.get("coordinate_units"), "coordinate_units") + words = record["words"] + if not isinstance(words, (list, tuple)) or any(not isinstance(w, str) for w in words): + raise ValueError("words must be a sequence of strings (including explicit empty events)") + words = list(words) + word_ids = _ids(record["word_ids"], len(words), "word_ids") + raw_onsets = _real_array(record["stimulus_times"], "stimulus_times", 1) + if len(raw_onsets) != len(words) or not np.isfinite(raw_onsets).all(): + raise ValueError("stimulus_times must be finite and match words") + onsets = raw_onsets.astype(float) * _TIME_UNITS[stimulus_unit] + sync = deepcopy(record.get("synchronization")) + if neural_clock == stimulus_clock: + if sync is not None: + raise ValueError("A common clock must not also specify synchronization") + else: + if not isinstance(sync, dict): + raise ValueError("Distinct clocks require an explicit synchronization mapping") + if sync.get("source_clock") != stimulus_clock or sync.get("target_clock") != neural_clock: + raise ValueError("synchronization source_clock/target_clock do not match declared clocks") + scale = _number(sync.get("scale"), "synchronization.scale", positive=True) + offset = _number(sync.get("offset_s"), "synchronization.offset_s") + if not isinstance(sync.get("provenance"), dict) or not sync["provenance"]: + raise ValueError("synchronization.provenance must be a non-empty mapping") + onsets = onsets * scale + offset + if (not np.isfinite(onsets).all() or np.any(np.diff(onsets) < 0) + or np.any(onsets < grid[0]) or np.any(onsets >= end)): + raise ValueError("stimulus_times must be ordered and inside the half-open recording interval after synchronization") + stimuli, context_metadata, context_sources = self._stimuli(record, words, provenance, lookback) + if record.get("audio_path") is not None: + _text(record["audio_path"], "audio_path") + intervals = deepcopy(record.get("invalid_intervals", [])) + if not isinstance(intervals, list): + raise ValueError("invalid_intervals must be a list") + canonical_intervals = [] + for interval in intervals: + if not isinstance(interval, dict): + raise ValueError("invalid_intervals entries must be mappings") + start = _number(interval.get("start"), "invalid interval start") * _TIME_UNITS[neural_unit] + stop = _number(interval.get("stop"), "invalid interval stop") * _TIME_UNITS[neural_unit] + _text(interval.get("reason"), "invalid interval reason") + if not (grid[0] <= start < stop <= end): + raise ValueError("invalid interval must lie inside the recording and have positive duration") + if (valid | unknown)[(grid >= start) & (grid < stop)].any(): + raise ValueError("invalid_intervals must agree with valid_samples; no automatic masking") + canonical_intervals.append({"start_s": start, "stop_s": stop, "reason": interval["reason"]}) + sample_ids = _ids(record.get("sample_ids", np.arange(len(brain))), len(brain), "sample_ids") + # searchsorted yields T-1 cut points, including repeats for empty bins. + cuts = np.searchsorted(onsets, grid[1:], side="left") + counts = np.array([sum(bool(word.strip()) for word in chunk) + for chunk in np.split(np.asarray(words), cuts)], dtype=float).reshape(-1, 1) + metadata = { + "schema_version": 1, "recording_id": name, "subject_id": subject, + "run_id": record.get("run_id"), "signal_units": signal_units, + "sampling_rate_hz": rate, "timestamp_unit": "s", "clock": neural_clock, + "neural_times_native": raw_grid, "neural_time_unit": neural_unit, + "stimulus_times_native": raw_onsets, "stimulus_time_unit": stimulus_unit, + "stimulus_clock": stimulus_clock, "synchronization": sync, + "sample_ids": sample_ids, + "sample_identity_kind": "supplied" if "sample_ids" in record else "positional_within_recording", + "word_ids": word_ids, "valid_samples": valid, "unknown_samples": unknown, + "invalid_sample_reasons": reasons, "recording_metadata": recording_metadata, + "invalid_intervals_native": intervals, "invalid_intervals": canonical_intervals, + "recording_interval_s": (float(grid[0]), float(end)), + "word_rates_units": "words/bin", "words_per_second": counts * rate, + "bin_convention": "[grid[i], grid[i+1]); last stop = grid[-1] + 1/rate", + "grid_validation": {"rtol": 1e-6, "atol_s": grid_atol}, + "validity_applied": False, + "stimulus_context": context_metadata, "context_source_indices": context_sources, + } + return StoryData(name=name, brain_data=brain, stimuli=stimuli, + split_indices=cuts.tolist(), tr_times=grid, data_times=onsets, + word_rates=counts, words=words, target_metadata=electrodes, + provenance=provenance, sample_metadata=metadata, + audio_path=record.get("audio_path")) + + def _stimuli(self, record, words, provenance, lookback): + if "stimuli" in record: + stimuli = record["stimuli"] + if (not isinstance(stimuli, (list, tuple)) or len(stimuli) != len(words) + or any(not isinstance(s, str) for s in stimuli)): + raise ValueError("stimuli must be strings matching transcript rows") + if not isinstance(provenance.get("stimulus_context"), dict) or not provenance["stimulus_context"]: + raise ValueError("Supplied stimuli require provenance.stimulus_context") + return list(stimuli), deepcopy(provenance["stimulus_context"]), None + if self.tokenizer is None: + raise ValueError("Supply stimuli with context provenance or an explicit tokenizer") + if not all(callable(getattr(self.tokenizer, method, None)) for method in ("encode", "decode")): + raise ValueError("The explicit tokenizer must provide encode and decode methods") + if self.context_type == "halfcontext" and any( + len(self.tokenizer.encode(word, add_special_tokens=False)) > lookback for word in words + ): + raise ValueError("halfcontext cannot accept a word longer than lookback tokens") + import pandas as pd + source_starts = [] + stimuli = self.generate_stimuli_with_context( + pd.DataFrame({"word_orig": words}), lookback, source_starts=source_starts, + ) + if self.context_type != "fullcontext": + # Window resets depend on earlier token counts in these stateful policies. + source_starts = [0 if word else i for i, word in enumerate(words)] + context_metadata = { + "context_type": self.context_type, "lookback": int(lookback), + "tokenizer": getattr(self.tokenizer, "name_or_path", type(self.tokenizer).__name__), + "implementation": "shared StimulusContextMixin", + } + return stimuli, context_metadata, np.asarray(source_starts, dtype=int) diff --git a/encoding/assembly/story_data.py b/encoding/assembly/story_data.py index 5bd2e51..bc655aa 100644 --- a/encoding/assembly/story_data.py +++ b/encoding/assembly/story_data.py @@ -1,5 +1,5 @@ from dataclasses import dataclass -from typing import List, Optional +from typing import Any, Dict, List, Optional import numpy as np @@ -32,3 +32,9 @@ class StoryData: words: Optional[List[str]] = None mask_indices: Optional[np.ndarray] = None audio_path: Optional[str] = None + # Optional additions: old constructors and fMRI pickles keep their behavior. + target_metadata: Optional[List[Dict[str, Any]]] = None + provenance: Optional[Dict[str, Any]] = None + # Recording/sample clocks, original IDs, validity and acquisition metadata. + # Invalid rows remain present; this is not a training/exclusion mask API. + sample_metadata: Optional[Dict[str, Any]] = None diff --git a/encoding/ecog_temporal.py b/encoding/ecog_temporal.py new file mode 100644 index 0000000..392eec5 --- /dev/null +++ b/encoding/ecog_temporal.py @@ -0,0 +1,449 @@ +"""Recording-local ECoG preparation and support-aware nested evaluation.""" +from decimal import Decimal, ROUND_HALF_UP, localcontext +from numbers import Real + +import numpy as np +from sklearn.model_selection import GroupKFold + + +def _number(value, name, minimum=None): + if isinstance(value, bool) or not isinstance(value, Real) or not np.isfinite(value): + raise ValueError(f"{name} must be a finite number") + if minimum is not None and value < minimum: + raise ValueError(f"{name} must be at least {minimum}") + return float(value) + + +def delay_offsets(delays_s, rate): + """Round decimal seconds × Hz to the nearest integer, ties away from zero.""" + if delays_s is None or not len(delays_s): + raise ValueError("ECoG requires explicit nonempty delays_s") + rate = _number(rate, "sampling rate") + if rate <= 0: + raise ValueError("sampling rate must be positive") + requested = [_number(d, "delay") for d in delays_s] + with localcontext() as context: + context.prec = 40 + offsets = [ + int((Decimal(str(d)) * Decimal(str(rate))).to_integral_value(rounding=ROUND_HALF_UP)) + for d in requested + ] + if len(set(offsets)) != len(offsets): + raise ValueError("Duplicate realized ECoG delay offsets") + return dict(requested_s=requested, sample_offsets=offsets, + realized_s=[offset / rate for offset in offsets]) + + +def _support(declaration, name): + if not isinstance(declaration, (list, tuple)) or len(declaration) != 2: + raise ValueError(f"{name} requires known [before, after] seconds") + return tuple(_number(v, name, 0) for v in declaration) + + +def _intervals(values): + intervals = np.asarray(values, dtype=float) + if intervals.shape == (0,): + return intervals.reshape(0, 2) + if (intervals.ndim != 2 or intervals.shape[1] != 2 + or not np.isfinite(intervals).all() or np.any(intervals[:, 0] >= intervals[:, 1])): + raise ValueError("Missing intervals require finite start < stop") + return intervals + + +def _overlaps(bounds, intervals, *, closed): + """Query interval overlap using sorted starts and cumulative maximum ends.""" + if not len(intervals): + return np.zeros(len(bounds), dtype=bool) + ordered = intervals[np.argsort(intervals[:, 0])] + indices = np.searchsorted(ordered[:, 0], bounds[:, 1], side="right") - 1 + ends = np.maximum.accumulate(ordered[:, 1])[np.maximum(indices, 0)] + return (indices >= 0) & ((ends >= bounds[:, 0]) if closed else (ends > bounds[:, 0])) + + +def align_features(story, raw, spec, *, event_sources=None): + """Return aligned values, validity and closed dependency bounds in neural seconds.""" + grid = story.tr_times + meta = story.sample_metadata + start, stop = meta["recording_interval_s"] + edges = np.r_[grid, stop] + method = spec["method"] + before, after = _support(spec.get("support_s"), "feature support_s") + if method == "speech_linear": + if not isinstance(raw, tuple) or len(raw) != 2: + raise ValueError("speech_linear requires (features, frame_seconds)") + values, times = map(np.asarray, raw) + if values.dtype.kind != "f" or times.dtype.kind not in "iuf": + raise ValueError("Speech features and frame timestamps must be real numeric arrays") + origin = _number(spec.get("frame_origin_s"), "frame_origin_s") + max_gap = _number(spec.get("max_gap_s"), "max_gap_s", 0) + scale = _number(spec.get("frame_scale", 1), "frame_scale") + if scale <= 0: + raise ValueError("frame_scale must be positive") + times = times * scale + origin + if (values.ndim != 2 or times.ndim != 1 or len(times) != len(values) + or not len(times) or not np.isfinite(times).all() + or np.any(np.diff(times) <= 0)): + raise ValueError("Speech frames require finite strictly increasing timestamps and matching rows") + right = np.searchsorted(times, grid) + right = np.minimum(right, len(times) - 1) + left = np.maximum(right - 1, 0) + left[times[right] == grid] = right[times[right] == grid] + gap = times[right] - times[left] + fraction = np.divide(grid - times[left], gap, out=np.zeros_like(grid), where=gap > 0) + valid = (grid >= times[0]) & (grid <= times[-1]) & (gap <= max_gap) + valid &= np.isfinite(values[left]).all(axis=1) & np.isfinite(values[right]).all(axis=1) + aligned = values[left] * (1 - fraction[:, None]) + values[right] * fraction[:, None] + bounds = np.column_stack((times[left] - before, times[right] + after)) + else: + bounds = np.column_stack((edges[:-1] - before, + np.nextafter(edges[1:] + after, -np.inf))) + valid = np.ones(len(grid), dtype=bool) + if method in {"words_per_bin", "words_per_second"}: + aligned = story.word_rates if method == "words_per_bin" else meta["words_per_second"] + elif method in {"word_sum", "word_mean", "word_last"}: + values = np.asarray(raw) + if (values.ndim != 2 or values.dtype.kind != "f" + or len(values) != len(story.data_times)): + raise ValueError("Word features must supply one row per original event") + aligned = np.zeros((len(grid), values.shape[1]), dtype=values.dtype) + if event_sources is not None: + source_times = story.data_times[event_sources] + source_bins = np.searchsorted(grid, source_times, side="right") - 1 + source_starts = np.split(grid[source_bins], story.split_indices) + for i, chunk in enumerate(np.split(values, story.split_indices)): + if not len(chunk): + continue + if event_sources is not None: + # Include all inspected events, including rows checked for finiteness. + bounds[i, 0] = min(bounds[i, 0], source_starts[i].min() - before) + valid[i] = np.isfinite(chunk).all() + if valid[i]: + if method == "word_last": + aligned[i] = chunk[-1] + elif method == "word_sum": + aligned[i] = chunk.sum(axis=0) + else: + aligned[i] = chunk.mean(axis=0) + else: + raise ValueError(f"Unsupported ECoG alignment method: {method}") + valid &= (bounds[:, 0] >= start) & (bounds[:, 1] <= stop) + valid &= np.isfinite(aligned).all(axis=1) + valid &= ~_overlaps(bounds, _intervals(spec.get("missing_intervals_s", [])), closed=False) + return aligned, valid, bounds + + +def _shift(rows, offset): + """Return matching destination/source slices for a signed delay.""" + if offset >= 0: + return slice(offset, rows), slice(0, rows - offset) + return slice(0, rows + offset), slice(-offset, rows) + + +def expand_recording(story, aligned, delays, preprocessing_support_s, *, diagnostic=False): + """Expand on the full grid, then select rows with complete temporal support.""" + grid = story.tr_times + meta = story.sample_metadata + n = len(grid) + start, stop = meta["recording_interval_s"] + known_valid = meta["valid_samples"] + unknown = meta.get("unknown_samples", np.zeros(n, dtype=bool)) + known_bad = ~(known_valid | unknown) | ~np.isfinite(story.brain_data).all(axis=1) + valid = (known_valid | (unknown & diagnostic)) & ~known_bad + if preprocessing_support_s is None: + if not diagnostic: + raise ValueError("Held-out evaluation requires known preprocessing support") + bounds = np.column_stack((grid, grid)) + else: + before, after = _support(preprocessing_support_s, "preprocessing support") + bounds = np.column_stack((grid - before, grid + after)) + valid &= (bounds[:, 0] >= start) & (bounds[:, 1] < stop) + bad_points = grid[known_bad if diagnostic else (known_bad | unknown)] + valid &= ~_overlaps(bounds, np.column_stack((bad_points, bad_points)), closed=True) + intervals = [(x["start_s"], x["stop_s"]) for x in meta["invalid_intervals"]] + valid &= ~_overlaps(bounds, _intervals(intervals), closed=False) + reasons = np.full(n, "", dtype=object) + reasons[~valid] = "invalid neural row or preprocessing support" + if not diagnostic: + reasons[unknown & ~known_bad] = "unknown neural validity" + reasons[~np.isfinite(story.brain_data).all(axis=1)] = "nonfinite neural row" + width = sum(values.shape[1] for values, _, _ in aligned) + offsets = delays["sample_offsets"] + if any(abs(offset) >= n for offset in offsets): + raise ValueError(f"{story.name}: delay leaves no supported rows") + design = np.empty((n, width * len(offsets)), + dtype=np.result_type(*(values.dtype for values, _, _ in aligned))) + column = 0 + for offset in offsets: + dst, src = _shift(n, offset) + supported = np.zeros(n, dtype=bool) + supported[dst] = True + for values, feature_valid, feature_bounds in aligned: + supported[dst] &= feature_valid[src] + design[dst, column:column + values.shape[1]] = values[src] + column += values.shape[1] + bounds[dst, 0] = np.minimum(bounds[dst, 0], feature_bounds[src, 0]) + bounds[dst, 1] = np.maximum(bounds[dst, 1], feature_bounds[src, 1]) + reasons[valid & ~supported] = "missing delayed feature support or recording edge" + valid &= supported + rows = np.flatnonzero(valid) + if not len(rows): + raise ValueError(f"{story.name}: no rows with complete temporal support") + return design[rows], story.brain_data[rows], rows, bounds[rows], reasons + + +def memory_preflight(rows, columns, targets, design_itemsize, outer, alpha_count, + budget, *, resident_bytes=0): + """Conservative array/workspace model, not an exact process peak guarantee.""" + if isinstance(budget, bool) or not isinstance(budget, (int, np.integer)) or budget <= 0: + raise ValueError("memory_budget_bytes must be a positive integer") + rank = min(rows, columns) + # NumPy full expansion, selected rows and concatenated design; Torch uses float32. + design = 3 * rows * columns * design_itemsize + # Input tensors, indexed and normalized inner/outer copies and predictions. + tensors = 4 * (8 * rows * (columns + targets) + 8 * rows * targets) + # Economy SVD factors, workspace/fallback copies and explicit diag(D). + solver = 4 * (4 * rows * columns + 4 * rank * (rows + columns + rank) + + 4 * rank * targets + 4 * alpha_count * targets) + # Fold weights, stacking/averaging copies, retained predictions and scores. + retained = 8 * (4 * outer * columns * targets + 8 * rows * targets + + 8 * outer * targets) + estimate = dict(resident=int(resident_bytes), design=int(design), tensors=int(tensors), + solver=int(solver), retained=int(retained)) + estimate["estimated_bytes"] = sum(estimate.values()) + estimate["budget_bytes"] = int(budget) + if estimate["estimated_bytes"] > budget: + raise MemoryError(f"ECoG memory preflight estimates {estimate['estimated_bytes']} bytes " + f"against budget {budget}; breakdown={estimate}") + return estimate + + +def temporal_splits(recordings, bounds, outer, inner, protocol, embargo_s): + """Return outer indices and inner positions into each purged training set.""" + embargo = _number(embargo_s, "embargo_s", 0) + recordings = np.asarray(recordings) + bounds = np.asarray(bounds, dtype=float) + if (recordings.ndim != 1 or bounds.shape != (len(recordings), 2) + or not np.isfinite(bounds).all() or np.any(bounds[:, 0] > bounds[:, 1])): + raise ValueError("Temporal support bounds must match the original retained rows") + + def split(rows, count): + if not isinstance(count, (int, np.integer)) or count < 2 or len(rows) < 2 * count: + raise ValueError("Too few supported rows for requested temporal folds") + if protocol == "recording": + candidates = ((rows[a], rows[b]) for a, b in + GroupKFold(count).split(rows, groups=recordings[rows])) + elif protocol == "blocked": + # Balance retained rows in recording/grid order. Purge using original + # seconds, so neither gaps nor nested selection compress support. + candidates = ((np.setdiff1d(rows, test), test) for test in np.array_split(rows, count)) + else: + raise ValueError("ECoG protocol must be blocked or recording") + for train, test in candidates: + keep = np.ones(len(train), dtype=bool) + for recording in np.unique(recordings[test]): + same = recordings[train] == recording + test_bounds = bounds[test[recordings[test] == recording]] + [-embargo, embargo] + keep[same] = ~_overlaps(bounds[train[same]], test_bounds, closed=True) + train = train[keep] + if min(len(train), len(test)) < 2: + raise ValueError("Temporal exclusion leaves fewer than two train or test rows") + yield train, test + + result = [] + for train, test in split(np.arange(len(recordings)), outer): + nested = [(np.searchsorted(train, a), np.searchsorted(train, b)) + for a, b in split(train, inner)] + result.append((train, test, nested)) + return result + + +def prepare_ecog(trainer, config, fit_options): + """Prepare the continuous ECoG inputs for the existing ridge trainer.""" + if trainer.fir_delays is not None or trainer.trimming_config or trainer.use_train_test_split: + raise ValueError("ECoG requires delays_s and an explicit nested temporal protocol") + if trainer.downsample_config: + raise ValueError("ECoG alignment must be declared in feature_specs") + if set(fit_options) & {"groups", "folding_type", "chunk_length", "trim_size", "temporal_cv"}: + raise ValueError("ECoG uses its declared temporal protocol, not legacy fold options") + unknown = set(config) - { + "delays_s", "feature_specs", "protocol", "embargo_s", "memory_budget_bytes", "retrospective", + } + if unknown: + raise ValueError(f"Unknown ECoG temporal settings: {sorted(unknown)}") + specs = config.get("feature_specs", []) + if not specs or len(specs) != len(trainer.feature_extractors): + raise ValueError("ECoG requires one feature_specs declaration per extractor") + from encoding.features.simple_features import WordRateFeatureExtractor + + rate_methods = {"words_per_bin", "words_per_second"} + for extractor, spec in zip(trainer.feature_extractors, specs): + method = spec.get("method") + if method not in rate_methods | {"word_sum", "word_mean", "word_last", "speech_linear"}: + raise ValueError(f"Unsupported ECoG alignment method: {method}") + if (method in rate_methods) != isinstance(extractor, WordRateFeatureExtractor): + raise ValueError("WordRateFeatureExtractor requires an explicit word-rate unit") + allowed = {"method", "support_s", "missing_intervals_s"} + if method == "speech_linear": + allowed |= {"frame_origin_s", "frame_scale", "max_gap_s"} + if set(spec) - allowed: + raise ValueError(f"Unsupported options for ECoG alignment method {method}") + _support(spec.get("support_s"), "feature support_s") + names = trainer.stories_to_process + if not names or len(set(names)) != len(names): + raise ValueError("ECoG requires distinct selected recordings") + protocol = config.get("protocol") + diagnostic = protocol == "diagnostic_in_sample" + if diagnostic and ({"n_outer_folds", "n_inner_folds"} & fit_options.keys()): + raise ValueError("In-sample diagnostics do not use CV fold counts") + outer = 1 if diagnostic else fit_options.get("n_outer_folds", 5) + inner = fit_options.get("n_inner_folds", 5) + for count in (() if diagnostic else (outer, inner)): + if isinstance(count, bool) or not isinstance(count, (int, np.integer)) or count < 2: + raise ValueError("ECoG requires at least two inner and outer folds") + if protocol not in {"blocked", "recording", "diagnostic_in_sample"}: + raise ValueError("ECoG requires protocol=blocked, recording or diagnostic_in_sample") + embargo = _number(config.get("embargo_s", 0 if diagnostic else None), "embargo_s", 0) + if diagnostic and embargo: + raise ValueError("In-sample diagnostics do not use an embargo") + budget = config.get("memory_budget_bytes") + memory_preflight(0, 0, 0, 0, 0, 0, budget) + stories = [trainer.assembly.story_data[name] for name in names] + delays = [delay_offsets(config.get("delays_s"), s.sample_metadata["sampling_rate_hz"]) + for s in stories] + retrospective = config.get("retrospective", False) + if not isinstance(retrospective, bool): + raise ValueError("retrospective must be boolean") + if any(d < 0 for d in delays[0]["requested_s"]) and not retrospective: + raise ValueError("Negative ECoG delays require retrospective=True") + for story, delay in zip(stories, delays): + if any(abs(offset) >= len(story.tr_times) for offset in delay["sample_offsets"]): + raise ValueError(f"{story.name}: delay leaves no supported rows") + supports = [] + for story in stories: + preprocessing = story.provenance["preprocessing"] + support = preprocessing.get("support_s") + if preprocessing.get("support_status") in {"unknown", "unresolved"}: + if support is not None: + raise ValueError("Unknown preprocessing support cannot include a numeric bound") + supports.append(None if diagnostic and support is None else + _support(support, f"{story.name} preprocessing support_s")) + + from encoding.features.embeddings import StaticEmbeddingFeatureExtractor + from encoding.features.language_model import LanguageModelFeatureExtractor + from encoding.features.speech_model import SpeechFeatureExtractor + + raw_by_story = [] + widths = [] + itemsize = 0 + resident = trainer.assembly.data.nbytes + resident += sum(s.brain_data.nbytes for s in trainer.assembly.story_data.values()) + for story in stories: + index = trainer.assembly.stories.index(story.name) + raw_features = [] + dimensions = [] + for extractor, spec in zip(trainer.feature_extractors, specs): + method = spec["method"] + sources = None + if isinstance(extractor, StaticEmbeddingFeatureExtractor): + raw, sources = extractor.extract_features(story.words, return_source_indices=True) + else: + raw = trainer._extract_single_features(extractor, story.name, index) + if isinstance(extractor, LanguageModelFeatureExtractor): + sources = story.sample_metadata.get("context_source_indices") + values = np.asarray(raw[0] if isinstance(raw, tuple) else raw) + if values.ndim != 2 or not values.shape[1] or values.dtype.kind != "f": + raise ValueError("ECoG features must be nonempty floating-point columns") + dimensions.append(values.shape[1]) + itemsize = max(itemsize, values.dtype.itemsize, 8 if method == "speech_linear" else 0) + resident += values.nbytes + if isinstance(raw, tuple): + resident += np.asarray(raw[1]).nbytes + raw_features.append((raw, sources)) + widths.append(tuple(dimensions)) + raw_by_story.append(raw_features) + if len(set(widths)) != 1: + raise ValueError("ECoG recordings must have matching feature widths") + + width = sum(widths[0]) + rows = sum(len(s.tr_times) for s in stories) + alphas = fit_options.get("alphas") + alpha_count = 10 if alphas is None else len(alphas) + # Include aligned features, bounds, masks, sample metadata and nested indices. + resident += 3 * sum(s.brain_data.nbytes for s in stories) + resident += rows * (6 * width * itemsize + 512 + 32 * outer * (inner + 1)) + estimate = memory_preflight(rows, width * len(delays[0]["sample_offsets"]), + stories[0].brain_data.shape[1], itemsize, outer, + alpha_count, budget, resident_bytes=resident) + features, targets, coordinates, support_bounds, exclusions = [], [], [], [], [] + records = {} + for story, raw_features, delay, support in zip(stories, raw_by_story, delays, supports): + local_specs = [] + for extractor, spec in zip(trainer.feature_extractors, specs): + local = dict(spec) + for field in ("frame_origin_s", "frame_scale", "missing_intervals_s"): + if isinstance(local.get(field), dict): + if story.name not in local[field]: + raise ValueError(f"{field} must explicitly cover recording {story.name}") + local[field] = local[field][story.name] + if isinstance(extractor, SpeechFeatureExtractor) and local["method"] == "speech_linear": + rate = extractor.target_sample_rate + window_s = int(extractor.context_size * rate) / rate + scale = _number(local.get("frame_scale", 1), "frame_scale") + before, after = local["support_s"] + local["support_s"] = [max(before, window_s * scale), after] + local_specs.append(local) + aligned = [align_features(story, raw, spec, event_sources=sources) + for (raw, sources), spec in zip(raw_features, local_specs)] + x, y, selected, bounds, reasons = expand_recording(story, aligned, delay, support, diagnostic=diagnostic) + features.append(x) + targets.append(y) + support_bounds.append(bounds) + meta = story.sample_metadata + known_valid = meta["valid_samples"] + unknown = meta.get("unknown_samples", np.zeros(len(known_valid), dtype=bool)) + records[story.name] = dict(delays=delay, sampling_rate_hz=meta["sampling_rate_hz"], + clock=meta["clock"], provenance=story.provenance, + target_metadata=story.target_metadata, + preprocessing_support_s=support, + recording_interval_s=meta["recording_interval_s"], + invalid_intervals=meta["invalid_intervals"], + grid_count=len(story.tr_times), effective_feature_specs=local_specs, + **{key: meta[key] for key in ( + "signal_units", "run_id", "neural_time_unit", "stimulus_time_unit", + "stimulus_clock", "synchronization", "stimulus_context", + "recording_metadata", "bin_convention", "grid_validation", + )}) + for i, (time, sample) in enumerate(zip(story.tr_times, meta["sample_ids"])): + row = dict(recording_id=story.name, source_index=i, sample_id=sample, + time_s=float(time), validity=( + "unknown" if unknown[i] else "assessed_valid" if known_valid[i] else "known_invalid" + )) + if reasons[i]: + original_reasons = meta["invalid_sample_reasons"] + exclusions.append(dict(row, reason=reasons[i], original_reason=( + None if original_reasons is None else original_reasons[i] + ))) + else: + coordinates.append(row) + support_bounds = np.concatenate(support_bounds).tolist() + recordings = [row["recording_id"] for row in coordinates] + metadata = dict(target_metadata=stories[0].target_metadata, target_space="ecog", + sample_ids=[(r["recording_id"], r["sample_id"]) for r in coordinates], + temporal=dict(rows=coordinates, support_bounds_s=support_bounds, + validity_applied=True, + validity_policy=("allow_finite_unknown_in_sample" if diagnostic else + "assessed_valid_only"), + support_bounds_scope=( + "known dependencies only; neural preprocessing support unknown" + if any(support is None for support in supports) + else "known and declared feature and neural dependencies" + ), + exclusions=exclusions, recordings=records, + protocol=protocol, embargo_s=embargo, + retrospective=retrospective, + feature_specs=specs, feature_widths=widths[0], + design_order="delay, extractor, feature", + memory_preflight=estimate)) + cv = dict(recordings=recordings, bounds=support_bounds, protocol=protocol, + embargo_s=embargo, memory_budget_bytes=budget) + return {"X": np.concatenate(features), "Y": np.concatenate(targets)}, metadata, cv diff --git a/encoding/features/embeddings.py b/encoding/features/embeddings.py index 3ff62dc..2f0ac29 100644 --- a/encoding/features/embeddings.py +++ b/encoding/features/embeddings.py @@ -96,7 +96,7 @@ def __init__(self, config: Dict[str, Any]): def extract_features( self, stimuli: Union[str, List[str]], - **kwargs, + *, return_source_indices=False, **kwargs, ) -> np.ndarray: """ Tokens -> [N, D], one row per input token. If `stimuli` is a string, it is tokenized. @@ -120,16 +120,20 @@ def extract_features( N = len(tokens) if N == 0: - return np.zeros((0, self.dim), dtype=np.float32) + empty = np.zeros((0, self.dim), dtype=np.float32) + return (empty, np.empty(0, dtype=int)) if return_source_indices else empty iterator: Iterable[str] = ( tqdm(tokens, desc="Embedding tokens", total=N) if self.use_tqdm else tokens ) vecs: List[np.ndarray] = [] + sources = [] + last_source = None last_valid: Optional[np.ndarray] = None # for copy_prev for i, tok in enumerate(iterator): + source = i v: Optional[np.ndarray] = None if not isinstance(tok, str): @@ -139,6 +143,7 @@ def extract_features( # Skip may shrink length continue elif self.oov_handling == "copy_prev": + source = i if last_source is None else last_source v = ( last_valid.copy() if last_valid is not None @@ -152,6 +157,7 @@ def extract_features( v = self.kv.get_vector(tok).astype(np.float32, copy=False) # only update last_valid when we have a real vector last_valid = v.copy() + last_source = i else: # OOV handling if self.oov_handling == "error": @@ -159,6 +165,7 @@ def extract_features( elif self.oov_handling == "skip": continue # WARNING: length may shrink elif self.oov_handling == "copy_prev": + source = i if last_source is None else last_source v = ( last_valid.copy() if last_valid is not None @@ -174,11 +181,15 @@ def extract_features( v = v / n vecs.append(v) + if return_source_indices: + sources.append(source) if not vecs: - return np.zeros((0, self.dim), dtype=np.float32) + empty = np.zeros((0, self.dim), dtype=np.float32) + return (empty, np.empty(0, dtype=int)) if return_source_indices else empty - return np.stack([np.asarray(v, dtype=np.float32) for v in vecs], axis=0) + values = np.stack([np.asarray(v, dtype=np.float32) for v in vecs], axis=0) + return (values, np.asarray(sources, dtype=int)) if return_source_indices else values def _load_local_vectors(self, path: str) -> KeyedVectors: ext = path.lower() diff --git a/encoding/features/factory.py b/encoding/features/factory.py index 537300a..fba924c 100644 --- a/encoding/features/factory.py +++ b/encoding/features/factory.py @@ -1,4 +1,6 @@ from typing import Dict, Any, Union, Optional, Tuple +import hashlib +import json import numpy as np from datetime import datetime from .base import BaseFeatureExtractor @@ -146,15 +148,26 @@ def _extract_language_model_features( """Extract language model features with caching.""" texts = assembly.get_stimuli()[idx] + # Identity of the cached activations: the stimulus strings themselves + # (which encode the assembly's context policy and lookback) plus every + # extraction setting that changes the values. + identity = { + "model_name": extractor.model_name, + "story": story, + "context_type": getattr(extractor, "context_type", "fullcontext"), + "hook_type": extractor.hook_type, + "last_token": getattr(extractor, "last_token", False), + "dataset_type": dataset_type, + "stimuli_sha256": hashlib.sha256( + json.dumps(list(texts)).encode() + ).hexdigest(), + } + # Try to load cached activations cache_key = extractor.activation_cache._get_cache_key( - story=story, - lookback=lookback, # You can make this configurable - model_name=extractor.model_name, - context_type=getattr(extractor, "context_type", "fullcontext"), - last_token=getattr(extractor, "last_token", False), - dataset_type=dataset_type, + lookback=lookback, raw=True, + **identity, ) print(f"this is the last token: {getattr(extractor, 'last_token', False)}") print(f"this is the lookback: {lookback}") @@ -163,6 +176,15 @@ def _extract_language_model_features( lazy_cache = extractor.activation_cache.load_multi_layer_activations(cache_key) if lazy_cache is not None: + cached = lazy_cache.get_metadata() + mismatched = { + k: (cached.get(k), v) for k, v in identity.items() if cached.get(k) != v + } + if mismatched: + raise ValueError( + f"Cached activations {cache_key} do not match the request " + f"(cached, requested): {mismatched}" + ) return lazy_cache.get_layer(layer_idx) else: # Compute and cache features @@ -170,13 +192,8 @@ def _extract_language_model_features( # Create metadata for caching metadata = { - "model_name": extractor.model_name, - "story": story, + **identity, "lookback": lookback, - "context_type": getattr(extractor, "context_type", "fullcontext"), - "hook_type": extractor.hook_type, - "last_token": getattr(extractor, "last_token", False), - "dataset_type": dataset_type, "available_layers": list(all_features.keys()), "created_at": datetime.now().isoformat(), } diff --git a/encoding/models/estimator.py b/encoding/models/estimator.py new file mode 100644 index 0000000..89a765e --- /dev/null +++ b/encoding/models/estimator.py @@ -0,0 +1,136 @@ +"""Fold-local fitting and replay for supplied scikit-learn regressors.""" + +import numpy as np +from sklearn.base import clone, is_regressor +from sklearn.model_selection import ParameterGrid +from sklearn.pipeline import Pipeline + +from encoding.models.ridge_utils import DataNormalizer + + +def validate_estimator(estimator, param_grid, target_mode): + if target_mode not in ("native", "per_target"): + raise ValueError("target_mode must be 'native' or 'per_target'") + if (isinstance(estimator, type) or not is_regressor(estimator) + or not callable(getattr(estimator, "predict", None))): + raise ValueError("estimator must be a scikit-learn regressor instance or regression Pipeline") + try: + template = clone(estimator) + grid = ParameterGrid(param_grid if param_grid is not None else {}) + if not len(grid): + raise ValueError("param_grid must contain at least one candidate") + for params in grid: + candidate = clone(template).set_params(**params) + if not is_regressor(candidate): + raise ValueError("Each grid candidate must be a regressor") + components = [candidate, *candidate.get_params(deep=True).values()] + if any(isinstance(part, Pipeline) and part.memory is not None + for part in components): + raise ValueError("Pipeline caching must be disabled for fold-local fitting") + except (TypeError, ValueError, RuntimeError) as exc: + raise ValueError(f"Cannot clone or configure supplied regressor: {exc}") from exc + + +def _supports_multi_output(estimator): + # Pipeline's target tags do not always expose its final step's capabilities. + while isinstance(estimator, Pipeline): + estimator = estimator.steps[-1][1] + if hasattr(estimator, "__sklearn_tags__"): + return estimator.__sklearn_tags__().target_tags.multi_output + return estimator._get_tags().get("multioutput", False) + + +def predict_estimator(state, features): + columns = state["target_indices"] + predictions = np.full((len(features), state["target_count"]), np.nan, dtype=np.float32) + if not len(columns): + return predictions + models = state["models"] + if state["target_mode"] == "per_target": + outputs = [_checked_prediction(model, features, 1) for model in models] + predictions[:, columns] = np.concatenate(outputs, axis=1) + else: + predictions[:, columns] = _checked_prediction(models[0], features, len(columns)) + return predictions + + +def _checked_prediction(model, features, width): + output = np.asarray(model.predict(features.copy())) + if width == 1 and output.shape == (len(features),): + output = output[:, None] + if output.shape != (len(features), width): + raise ValueError( + f"Regressor prediction shape {output.shape} must match {(len(features), width)}" + ) + if output.dtype.kind not in "fiu": + raise ValueError("Regressor predictions must be real numeric values") + output = output.astype(np.float32, copy=False) + if not np.isfinite(output).all(): + raise ValueError("Regressor predictions must be finite in float32") + return output + + +def _fit(estimator, params, target_mode, X, y, columns): + models = [] + target_sets = [[column] for column in columns] if target_mode == "per_target" else [columns] + for indices in target_sets: + if not len(indices): + continue + # Clone after applying parameters too, including estimator-valued grid entries. + model = clone(clone(estimator).set_params(**params)) + if not is_regressor(model): + raise ValueError("Each grid candidate must be a regressor") + if len(indices) > 1 and not _supports_multi_output(model): + raise ValueError("Regressor lacks native multi-output support; explicitly choose target_mode='per_target'") + values = y[:, indices] + try: + model.fit(X.copy(), values[:, 0] if len(indices) == 1 else values) + except (TypeError, ValueError) as exc: + raise ValueError(f"Supplied regressor fit failed: {exc}") from exc + models.append(model) + return { + "models": models, "target_indices": columns, + "target_count": y.shape[1], "target_mode": target_mode, + } + + +def fit_estimator_fold(estimator, param_grid, target_mode, X_train, y_train, + X_test, y_test, splits, normalize_features, normalize_targets): + from encoding.models.nested_cv import _calculate_correlations_pvalues, _valid_training_targets + + def fit_and_predict(params, X, y, X_eval, y_eval): + columns = np.flatnonzero(_valid_training_targets(y).numpy()) + normalizer = None + if normalize_features or normalize_targets: + normalizer = DataNormalizer(normalize_features, normalize_targets) + X, y = normalizer.fit_transform(X, y) + X_eval, y_eval = normalizer.transform(X_eval, y_eval) + state = _fit(estimator, params, target_mode, X.numpy(), y.numpy(), columns) + return state, normalizer, predict_estimator(state, X_eval.numpy()), y_eval.numpy() + + selected = {} + best_score = None + if param_grid is not None: + for params in ParameterGrid(param_grid): + scores = [] + for train, validation in splits: + _, _, predictions, targets = fit_and_predict( + params, X_train[train], y_train[train], X_train[validation], y_train[validation] + ) + correlations, _ = _calculate_correlations_pvalues(targets, predictions) + scores.extend(value for value in correlations if np.isfinite(value)) + if scores: + score = float(np.mean(scores)) + if best_score is None or score > best_score: + selected, best_score = params, score + if best_score is None: + raise ValueError("Estimator grid search found no valid inner-validation correlations") + + state, normalizer, predictions, targets = fit_and_predict( + selected, X_train, y_train, X_test, y_test + ) + return None, None, normalizer, predictions, targets, { + "estimator_state": state, + "selected_params": selected, + "inner_selection_score": best_score, + } diff --git a/encoding/models/folding.py b/encoding/models/folding.py index 60c27f1..80b2588 100644 --- a/encoding/models/folding.py +++ b/encoding/models/folding.py @@ -31,6 +31,25 @@ def create_folds( List of (train_indices, test_indices) tuples """ print(f"THIS IS THE FOLDING TYPE: {fold_type} inside folding.py") + if trim_size is not None and ( + not isinstance(trim_size, (int, np.integer)) or trim_size < 0 + ): + raise TypeError( + f"trim_size must be a non-negative int, got {type(trim_size).__name__}; " + "pass groups by keyword (groups=...)" + ) + splits = _create_folds(n_samples, fold_type, n_folds, chunk_length, trim_size, groups, seed) + for i, (train_idx, test_idx) in enumerate(splits): + if len(train_idx) == 0 or len(test_idx) == 0: + raise ValueError( + f"{fold_type} fold {i} has {len(train_idx)} train and {len(test_idx)} test " + f"samples (n_samples={n_samples}, n_folds={n_folds}, " + f"chunk_length={chunk_length}, trim_size={trim_size})" + ) + return splits + + +def _create_folds(n_samples, fold_type, n_folds, chunk_length, trim_size, groups, seed): if fold_type == "chunked": # Current chunked implementation with random shuffling return create_chunked_folds( @@ -70,6 +89,23 @@ def create_folds( raise ValueError(f"Unknown folding type: {fold_type}") +def _chunks_per_fold(n_samples: int, n_folds: int, chunk_length: int) -> int: + """Chunks per fold; raises instead of falling back to sample-level KFold.""" + n_complete_chunks = n_samples // chunk_length + if n_complete_chunks < n_folds: + raise ValueError( + f"{n_samples} samples give {n_complete_chunks} chunks of {chunk_length}, " + f"fewer than n_folds={n_folds}; use fewer folds or shorter chunks" + ) + dropped = n_samples - n_complete_chunks * chunk_length + if dropped: + logging.warning( + f"Chunked folds drop the last {dropped} of {n_samples} samples " + f"(not a multiple of chunk_length={chunk_length})" + ) + return n_complete_chunks // n_folds + + def create_chunked_folds( n_samples: int, n_folds: int, @@ -96,17 +132,7 @@ def create_chunked_folds( if shuffle: random.Random(seed).shuffle(chunk_indices) - # Divide chunks evenly into n_folds - chunks_per_fold = n_complete_chunks // n_folds - if chunks_per_fold == 0: - # Not enough chunks for the requested folds, fall back to regular KFold - logging.warning( - "Not enough chunks for the requested folds, falling back to regular KFold" - ) - kf = KFold( - n_splits=n_folds, shuffle=shuffle, random_state=seed if shuffle else None - ) - return list(kf.split(range(n_samples))) + chunks_per_fold = _chunks_per_fold(n_samples, n_folds, chunk_length) # Create exactly n_folds splits splits = [] @@ -170,14 +196,7 @@ def create_chunked_folds_trimmed( if shuffle: random.Random(seed).shuffle(chunk_indices) - # Divide chunks evenly into n_folds - chunks_per_fold = n_complete_chunks // n_folds - if chunks_per_fold == 0: - logging.warning( - "Not enough chunks for the requested folds, falling back to regular KFold" - ) - kf = KFold(n_splits=n_folds, shuffle=False) - return list(kf.split(range(n_samples))) + chunks_per_fold = _chunks_per_fold(n_samples, n_folds, chunk_length) # Create exactly n_folds splits splits = [] @@ -254,15 +273,12 @@ def create_kfold_trimmed( test_indices = list(test_indices) # Trim the test set - remove first and last trim_size samples - if len(test_indices) > 2 * trim_size: - trimmed_test = test_indices[trim_size:-trim_size] - else: - # If test fold is too small to trim, keep original - logging.warning( + if len(test_indices) <= 2 * trim_size: + raise ValueError( f"Test fold too small ({len(test_indices)} samples) to trim {trim_size} " - f"from each end, keeping original test set" + "from each end; use fewer folds or a smaller trim_size" ) - trimmed_test = test_indices + trimmed_test = test_indices[trim_size : len(test_indices) - trim_size] # Training set remains unchanged trimmed_splits.append((train_indices, trimmed_test)) diff --git a/encoding/models/nested_cv.py b/encoding/models/nested_cv.py index 0d38fac..2b8179d 100644 --- a/encoding/models/nested_cv.py +++ b/encoding/models/nested_cv.py @@ -3,6 +3,7 @@ from scipy.stats import pearsonr, combine_pvalues from statsmodels.stats.multitest import fdrcorrection import logging +from copy import deepcopy from typing import Dict, Optional, List, Tuple, Union from encoding.models.ridge_regression import ridge_torch, ridge_corr_torch from encoding.models.folding import create_folds @@ -12,8 +13,19 @@ class NestedCVModel(BasePredictivityModel): - def __init__(self, model_name: str): + def __init__(self, model_name: str, *, estimator=None, param_grid=None, + target_mode="native"): super().__init__(model_name) + self.estimator = estimator + self.param_grid = param_grid + self.target_mode = target_mode + if estimator is None: + if param_grid is not None or target_mode != "native": + raise ValueError("param_grid and target_mode require a supplied estimator") + else: + from encoding.models.estimator import validate_estimator + + validate_estimator(estimator, param_grid, target_mode) def fit_predict( self, @@ -35,10 +47,13 @@ def fit_predict( normalize_features: bool = False, normalize_targets: bool = False, singcutoff: float = 1e-10, + trim_size: Optional[int] = None, + result_metadata: Optional[Dict[str, Any]] = None, + temporal_cv: Optional[Dict[str, Any]] = None, ) -> Tuple[ Dict[str, Union[float, List[float], List[bool]]], - np.ndarray, - np.ndarray, + Optional[np.ndarray], + Optional[np.ndarray], ]: """ Fit model with nested cross-validation, chunking, per-voxel or single alpha optimization, and FDR correction. @@ -62,12 +77,26 @@ def fit_predict( normalize_features: If True, z-score normalize features using training statistics normalize_targets: If True, z-score normalize targets using training statistics singcutoff: Singularity cutoff for ridge_corr + trim_size: Samples trimmed from each end of test chunks/folds for the + "chunked_trimmed" and "kfold_trimmed" folding types + result_metadata: Optional ordered target_metadata, sample_ids, + test_sample_ids and provenance for persistence. Missing IDs are + explicitly positional. Does not affect fitting or splitting. + + Normalization statistics are fit on training rows only, at both CV levels: + each inner fold fits its own normalizer, and the final model refits on the + full (outer) training set. + + Constant or non-finite targets in a test set get NaN correlation/p-value, + are excluded from summary statistics and FDR, and are counted in + ``n_invalid_targets``. Returns: Tuple of (metrics, weights, best_alphas) - metrics: Dictionary of evaluation metrics - weights: Model weights (n_features, n_targets) - best_alphas: Best alpha values for each target + Supplied estimators return None for weights and best_alphas. """ # Set up logging logging.basicConfig( @@ -75,14 +104,26 @@ def fit_predict( format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", ) logger = logging.getLogger(__name__) + # A failed fit must not leave a previous successful result available. + self.results_ = None # Set default alphas if not provided + supplied = self.estimator is not None + ecog = temporal_cv is not None + diagnostic = ecog and temporal_cv["protocol"] == "diagnostic_in_sample" + if diagnostic and len(features) < 2: + raise ValueError("In-sample diagnostics require at least two eligible samples") + if diagnostic and (supplied or alphas is None or len(alphas) != 1 + or not np.isfinite(alphas[0]) or alphas[0] <= 0): + raise ValueError("In-sample diagnostics require one fixed positive built-in ridge alpha") + if supplied and (alphas is not None or not use_corr): + raise ValueError("Supplied estimators use estimator parameters and Pearson selection") if alphas is None: alphas = np.logspace(-1, 8, 10) # Determine device - use GPU if available and requested - if use_gpu: + if use_gpu and not supplied: if torch.backends.mps.is_available(): device = "mps:0" elif torch.cuda.is_available(): @@ -93,7 +134,27 @@ def fit_predict( else: device = "cpu" logger.info(f"Using device: {device}") - logger.info(f"Folding type: {folding_type}") + protocol = folding_type if temporal_cv is None else temporal_cv["protocol"] + logger.info(f"Folding type: {protocol}") + + temporal_folds = None + if temporal_cv is not None: + from encoding.ecog_temporal import memory_preflight, temporal_splits + + if X_test is not None or y_test is not None or groups is not None: + raise ValueError("Temporal CV requires one continuous prepared dataset") + if len(temporal_cv["recordings"]) != len(features): + raise ValueError("Temporal coordinates must match feature rows") + memory_preflight( + len(features), features.shape[1], targets.shape[1], features.dtype.itemsize, + 1 if diagnostic else n_outer_folds, len(alphas), temporal_cv["memory_budget_bytes"], + resident_bytes=features.nbytes + targets.nbytes, + ) + if not diagnostic: + temporal_folds = temporal_splits( + temporal_cv["recordings"], temporal_cv["bounds"], + n_outer_folds, n_inner_folds, temporal_cv["protocol"], temporal_cv["embargo_s"], + ) # Convert inputs to PyTorch tensors features_torch = torch.tensor(features, dtype=torch.float32, device=device) @@ -101,61 +162,146 @@ def fit_predict( # Check if we're in train-test mode or full CV mode train_test_mode = X_test is not None and y_test is not None + metadata = deepcopy(result_metadata or {}) + metadata.setdefault("target_metadata", [ + {"target_index": i, "identity_kind": "positional"} + for i in range(targets.shape[1]) + ]) + metadata.setdefault("sample_identity_kind", ( + "supplied" if "sample_ids" in metadata else "positional" + )) + metadata.setdefault("sample_ids", np.arange(len(features))) + if len(metadata["target_metadata"]) != targets.shape[1]: + raise ValueError("target_metadata must match target column order/count") + if len(metadata["sample_ids"]) != len(features): + raise ValueError("sample_ids must match training input rows") + if train_test_mode: + metadata.setdefault("test_sample_identity_kind", ( + "supplied" if "test_sample_ids" in metadata else "positional" + )) + metadata.setdefault("test_sample_ids", np.arange(len(X_test))) + if len(metadata["test_sample_ids"]) != len(X_test): + raise ValueError("test_sample_ids must match test input rows") + result = { + "schema_version": 2, + "mode": "train_test" if train_test_mode else "nested_cv", + "metadata": metadata, + "configuration": { + "model_name": self.model_name, + "folding_type": protocol, "n_outer_folds": n_outer_folds, + "n_inner_folds": n_inner_folds, "chunk_length": chunk_length, + "trim_size": trim_size, "alphas": np.asarray(alphas).copy(), + "single_alpha": single_alpha, "normalpha": normalpha, + "use_corr": use_corr, "normalize_features": normalize_features, + "normalize_targets": normalize_targets, "singcutoff": singcutoff, + "alpha_fdr": alpha_fdr, "device": device, + "dtype": "float32", "groups": deepcopy(groups), + }, + "folds": [], + "final_refit": None, + "returned_weights_role": ( + "training_fit" if train_test_mode else "descriptive_fold_mean" + ), + "returned_alphas_role": ( + "selected_training_alphas" if train_test_mode else "descriptive_fold_mean" + ), + "prediction_input": "prepared feature design before fold normalization", + "prediction_units": "model-input target units (before fold normalization)", + "software": {"numpy": np.__version__, "torch": str(torch.__version__)}, + } + + if supplied: + import sklearn + + result["configuration"].update( + estimator_type=type(self.estimator).__qualname__, + param_grid=deepcopy(self.param_grid), + target_mode=self.target_mode, + selection_metric="mean_inner_pearson", + parameter_scope="shared_across_targets", + ) + for key in ("alphas", "single_alpha", "normalpha", "singcutoff"): + result["configuration"].pop(key) + result["software"]["sklearn"] = sklearn.__version__ + result["returned_weights_role"] = "fitted_estimators_in_folds" + result["returned_alphas_role"] = "not_applicable" + + def fit_fold(X_train, y_train, X_eval, y_eval, splits): + if supplied: + from encoding.models.estimator import fit_estimator_fold + + return fit_estimator_fold( + self.estimator, self.param_grid, self.target_mode, + X_train, y_train, X_eval, y_eval, splits, + normalize_features, normalize_targets, + ) + + if diagnostic: + selected = torch.full((y_train.shape[1],), float(alphas[0]), device=device) + else: + selected = _find_best_alphas( + X_train, y_train, fold_splits=splits, alphas=alphas, + single_alpha=single_alpha, normalpha=normalpha, use_corr=use_corr, + logger=logger, singcutoff=singcutoff, + normalize_features=normalize_features, normalize_targets=normalize_targets, + ) + valid = _valid_training_targets(y_train) + normalizer = None + if normalize_features or normalize_targets: + normalizer = DataNormalizer(normalize_features, normalize_targets) + X_train, y_train = normalizer.fit_transform(X_train, y_train) + X_eval, y_eval = normalizer.transform(X_eval, y_eval) + weights, info = ridge_torch( + X_train, y_train, selected, normalpha=normalpha, + singcutoff=singcutoff, return_info=True, + ) + weights[:, ~valid] = float("nan") + predictions = (X_eval @ weights).cpu().numpy() + return weights, selected, normalizer, predictions, y_eval.cpu().numpy(), info + + if ecog: + result["inference_status"] = "not_assessed" + if diagnostic: + rows = np.arange(len(features)) + wt, selected, normalizer, predictions, observed, info = fit_fold( + features_torch, targets_torch, features_torch, targets_torch, [] + ) + fit = _fold_result( + 0, rows, np.empty(0, dtype=int), [], wt, selected, normalizer, + predictions, observed, None, info, + ) + fit.update(model_role="in_sample_diagnostic", prediction_indices=rows) + fit.pop("test_indices") + fit["index_space"] = {"train": "training_input", "prediction": "training_input"} + result.update(mode="diagnostic_in_sample", returned_weights_role="in_sample_diagnostic", + returned_alphas_role="fixed_diagnostic_alpha") + result["configuration"].update(n_outer_folds=0, n_inner_folds=0, selection="fixed") + result["folds"].append(fit) + self.results_ = result + return { + "evaluation": "in_sample_diagnostic", + "inference_status": "not_assessed", + "n_fit_samples": len(rows), + }, wt.cpu().numpy(), selected.cpu().numpy() if train_test_mode: logger.info("Running in train-test mode with provided test set") X_test_torch = torch.tensor(X_test, dtype=torch.float32, device=device) y_test_torch = torch.tensor(y_test, dtype=torch.float32, device=device) - # Normalize data if requested - if normalize_features or normalize_targets: - logger.info( - f"Normalizing data using training statistics (features: {normalize_features}, targets: {normalize_targets})" - ) - normalizer = DataNormalizer( - normalize_features=normalize_features, - normalize_targets=normalize_targets, - ) - features_torch, targets_torch = normalizer.fit_transform( - features_torch, targets_torch - ) - X_test_torch, y_test_torch = normalizer.transform( - X_test_torch, y_test_torch - ) - - # Find best alphas using inner CV on training data only - best_valphas = _find_best_alphas( - features_torch, - targets_torch, - fold_splits=create_folds( - len(features), folding_type, n_inner_folds, chunk_length, groups - ), - alphas=alphas, - single_alpha=single_alpha, - normalpha=normalpha, - use_corr=use_corr, - logger=logger, - singcutoff=singcutoff, + inner_splits = create_folds( + len(features), folding_type, n_inner_folds, + chunk_length=chunk_length, trim_size=trim_size, groups=groups, ) - - # Compute weights with the best alphas - wt = ridge_torch( - features_torch, - targets_torch, - best_valphas, - normalpha=normalpha, - singcutoff=singcutoff, + wt, best_valphas, normalizer, y_pred, y_test_np, fit_info = fit_fold( + features_torch, targets_torch, X_test_torch, y_test_torch, inner_splits ) - # Predict on test set - y_pred = torch.matmul(X_test_torch, wt).cpu().numpy() - y_test_np = y_test_torch.cpu().numpy() - # Calculate correlations and p-values correlations, pvalues = _calculate_correlations_pvalues(y_test_np, y_pred) # Apply FDR correction - significant, corrected_pvals = fdrcorrection(pvalues, alpha=alpha_fdr) + significant, corrected_pvals = _fdr_valid(pvalues, alpha_fdr) n_significant = np.sum(significant) # Put results in a dictionary @@ -164,17 +310,30 @@ def fit_predict( pvalues, corrected_pvals, significant, - best_valphas.cpu().numpy(), + None if supplied else best_valphas.cpu().numpy(), n_significant, ) + result["folds"].append(_fold_result( + 0, np.arange(len(features)), np.arange(len(X_test)), + inner_splits, wt, best_valphas, normalizer, + y_pred, y_test_np, correlations, fit_info, + separate_test=True, + )) + result["final_refit"] = {"fold_id": 0, "scope": "provided_training_set_only"} + self.results_ = result + + if supplied: + return metrics, None, None return metrics, wt.cpu().numpy(), best_valphas.cpu().numpy() else: logger.info("Running in full nested CV mode") # Set up CV splits - if groups is not None and folding_type == "group": + if temporal_folds is not None: + outer_splits = [(a, b) for a, b, _ in temporal_folds] + elif groups is not None and folding_type == "group": # Use group-based folding outer_splits = create_folds( len(features), "group", n_outer_folds, groups=groups @@ -182,7 +341,12 @@ def fit_predict( else: # Use specified folding type outer_splits = create_folds( - len(features), folding_type, n_outer_folds, chunk_length, groups + len(features), + folding_type, + n_outer_folds, + chunk_length=chunk_length, + trim_size=trim_size, + groups=groups, ) # Store results from each fold @@ -200,112 +364,101 @@ def fit_predict( X_train, X_test = features_torch[train_idx], features_torch[test_idx] y_train, y_test = targets_torch[train_idx], targets_torch[test_idx] - # Normalize data if requested - if normalize_features or normalize_targets: - logger.info( - f"Normalizing data for fold {fold_idx+1} (features: {normalize_features}, targets: {normalize_targets})" - ) - normalizer = DataNormalizer( - normalize_features=normalize_features, - normalize_targets=normalize_targets, - ) - X_train, y_train = normalizer.fit_transform(X_train, y_train) - X_test, y_test = normalizer.transform(X_test, y_test) - - # Inner CV to find the best alpha for each voxel - if groups is not None and folding_type == "group": + # Build inner splits within this outer training subset + if temporal_folds is not None: + inner_splits = temporal_folds[fold_idx][2] + elif groups is not None and folding_type == "group": inner_groups = [groups[i] for i in train_idx] inner_splits = create_folds( len(train_idx), "group", n_inner_folds, groups=inner_groups ) else: inner_splits = create_folds( - len(train_idx), folding_type, n_inner_folds, chunk_length + len(train_idx), + folding_type, + n_inner_folds, + chunk_length=chunk_length, + trim_size=trim_size, ) - # Find best alphas for this fold - best_valphas = _find_best_alphas( - X_train, - y_train, - fold_splits=inner_splits, - alphas=alphas, - single_alpha=single_alpha, - normalpha=normalpha, - use_corr=use_corr, - logger=logger, - singcutoff=singcutoff, + wt, best_valphas, normalizer, y_pred, y_test_np, fit_info = fit_fold( + X_train, y_train, X_test, y_test, inner_splits ) - - fold_valphas.append(best_valphas.cpu().numpy()) - - # Apply the best alphas to the entire training set and evaluate on test set - wt = ridge_torch( - X_train, - y_train, - best_valphas, - normalpha=normalpha, - singcutoff=singcutoff, - ) - fold_weights.append(wt.cpu().numpy()) - - y_pred = torch.matmul(X_test, wt).cpu().numpy() - y_test_np = y_test.cpu().numpy() + if not supplied: + fold_valphas.append(best_valphas.cpu().numpy()) + fold_weights.append(wt.cpu().numpy()) # Calculate correlations and p-values correlations, pvalues = _calculate_correlations_pvalues( - y_test_np, y_pred + y_test_np, y_pred, inference=not ecog ) fold_scores.append(correlations) fold_pvalues.append(pvalues) + result["folds"].append(_fold_result( + fold_idx, train_idx, test_idx, inner_splits, wt, + best_valphas, normalizer, y_pred, y_test_np, + correlations, fit_info, + )) + + if temporal_folds is not None: + fold = result["folds"][-1] + fold["purged_indices"] = np.setdiff1d( + np.arange(len(features)), np.r_[train_idx, test_idx] + ) + for split in fold["inner_splits"]: + split["purged_indices"] = np.setdiff1d( + train_idx, np.r_[split["train_indices"], split["validation_indices"]] + ) + + median_corr = _nanmedian(correlations) + logger.info("Fold %d/%d - Median correlation: %.3f", fold_idx + 1, n_outer_folds, median_corr) + if not ecog: + significant, _ = _fdr_valid(pvalues, alpha_fdr) + fold_significant_masks.append(significant) + logger.info("Fold %d/%d - Significant voxels: %d/%d", + fold_idx + 1, n_outer_folds, np.sum(significant), len(significant)) + + # Preserve target positions and fold-level exclusions. + # Compute final metrics across folds: mean over the folds in which + # each target was valid (NaN if it was never valid) + fold_scores_arr = np.asarray(fold_scores, dtype=float) + n_valid_folds = np.isfinite(fold_scores_arr).sum(axis=0) + all_correlations = np.where( + n_valid_folds > 0, + np.nansum(fold_scores_arr, axis=0) / np.maximum(n_valid_folds, 1), + np.nan, + ) - # Apply FDR correction for this fold - significant, corrected_pvals = fdrcorrection(pvalues, alpha=alpha_fdr) - fold_significant_masks.append(significant) - n_significant = np.sum(significant) - - median_corr = np.median(correlations) - logger.info( - f"Fold {fold_idx+1}/{n_outer_folds} - Median correlation: {median_corr:.3f}" - ) - logger.info( - f"Fold {fold_idx+1}/{n_outer_folds} - Significant voxels: {n_significant}/{len(significant)}" + mean_valphas = None if supplied else np.mean(fold_valphas, axis=0) + mean_weights = None if supplied else np.mean(fold_weights, axis=0) + if ecog: + metrics = { + **_summary_scores(all_correlations), + "correlations": all_correlations.tolist(), + "best_alphas": None if supplied else mean_valphas.tolist(), + "inference_status": "not_assessed", + } + logger.info("ECoG inference not assessed. Median descriptive correlation: %.3f", + metrics["median_score"]) + else: + all_pvalues = _combine_pvalues_across_folds(fold_pvalues, logger) + significant_mask, corrected_pvalues = _fdr_valid(all_pvalues, alpha_fdr) + n_significant = np.sum(significant_mask) + significance_counts = np.sum(fold_significant_masks, axis=0) + majority_significant_mask = significance_counts >= (n_outer_folds // 2 + 1) + n_majority_significant = np.sum(majority_significant_mask) + metrics = _create_full_cv_metrics_dict( + all_correlations, all_pvalues, corrected_pvalues, significant_mask, + majority_significant_mask, mean_valphas, n_significant, n_majority_significant, ) - # Compute final metrics across folds - all_correlations = np.mean(fold_scores, axis=0) # average across folds - - # Use Fisher's method to combine p-values across folds for each voxel - all_pvalues = _combine_pvalues_across_folds(fold_pvalues, logger) + metrics["fold_invalid_target_masks"] = (~np.isfinite(fold_scores_arr)).tolist() + metrics["n_valid_folds_per_target"] = n_valid_folds.tolist() + self.results_ = result - # Apply FDR correction to the combined p-values - significant_mask, corrected_pvalues = fdrcorrection( - all_pvalues, alpha=alpha_fdr - ) - n_significant = np.sum(significant_mask) - - # Alternative: Count how many times each voxel was significant across folds - significance_counts = np.sum(fold_significant_masks, axis=0) - majority_significant_mask = significance_counts >= (n_outer_folds // 2 + 1) - n_majority_significant = np.sum(majority_significant_mask) - - # Compute average best alpha for each voxel - mean_valphas = np.mean(fold_valphas, axis=0) - - # Compute average weights across folds - mean_weights = np.mean(fold_weights, axis=0) - - # Create metrics dictionary with all results - metrics = _create_full_cv_metrics_dict( - all_correlations, - all_pvalues, - corrected_pvalues, - significant_mask, - majority_significant_mask, - mean_valphas, - n_significant, - n_majority_significant, - ) + if ecog: + return metrics, mean_weights, mean_valphas # Print final results logger.info("\nFinal Results:") @@ -330,6 +483,92 @@ def fit_predict( return metrics, mean_weights, mean_valphas + @staticmethod + def predict_fold(fold: Dict[str, Any], features: np.ndarray, + original_units: bool = True) -> np.ndarray: + """Replay one persisted fold on a prepared design, never on mean weights. + + CPU float32 replay can differ slightly from GPU matrix multiplication. + Feature extraction, FIR and legacy per-story preprocessing are upstream. + original_units means model-input target units, not raw recording units + when the supplied targets already underwent upstream preprocessing. + """ + if "weights" not in fold and "estimator_state" not in fold: + raise ValueError("Fold fitted state was omitted; prediction replay is unavailable") + X = torch.as_tensor(np.asarray(features), dtype=torch.float32) + state = fold["transform"] + if state["normalize_features"]: + X = (X - torch.as_tensor(state["feature_means"])) / ( + torch.as_tensor(state["feature_stds"]) + state["eps"] + ) + if "estimator_state" in fold: + from encoding.models.estimator import predict_estimator + + prediction = torch.from_numpy(predict_estimator(fold["estimator_state"], X.numpy())) + else: + prediction = X @ torch.as_tensor(fold["weights"]) + if original_units and state["normalize_targets"]: + prediction = prediction * ( + torch.as_tensor(state["target_stds"]) + state["eps"] + ) + torch.as_tensor(state["target_means"]) + return prediction.numpy() + + +def _fold_result(fold_id, train_idx, test_idx, inner_splits, weights, alphas, + normalizer, predictions, targets, correlations, + fit_info, separate_test=False): + """CPU-only fitted state and coordinates, independent of live model objects.""" + state = {"normalize_features": False, "normalize_targets": False, "eps": 1e-8} + if normalizer is not None: + state.update( + normalize_features=normalizer.normalize_features, + normalize_targets=normalizer.normalize_targets, eps=normalizer.eps, + ) + for key in ("feature_means", "feature_stds", "target_means", "target_stds"): + value = getattr(normalizer, key) + state[key] = None if value is None else value.detach().cpu().numpy().copy() + pred_original, targets_original = predictions.copy(), targets.copy() + if state["normalize_targets"]: + scale = state["target_stds"] + state["eps"] + pred_original = pred_original * scale + state["target_means"] + targets_original = targets_original * scale + state["target_means"] + train_idx = np.asarray(train_idx, dtype=int) + fitted = fit_info if weights is None else { + "weights": weights.detach().cpu().numpy().copy(), + "selected_alphas": alphas.detach().cpu().numpy().copy(), + "effective_penalties": fit_info["effective_penalties"], + } + scores = {} if correlations is None else { + "correlations": np.asarray(correlations), + "invalid_target_mask": ~np.isfinite(correlations), + } + return { + **fitted, + **scores, + "fold_id": fold_id, + "model_role": "training_fit" if separate_test else "outer_fold", + "train_indices": train_idx, + "test_indices": np.asarray(test_idx, dtype=int), + "index_space": {"train": "training_input", "test": ( + "provided_test_input" if separate_test else "training_input" + )}, + "inner_splits": [ + {"train_indices": train_idx[np.asarray(a, dtype=int)], + "validation_indices": train_idx[np.asarray(b, dtype=int)]} + for a, b in inner_splits + ], + "transform": state, + "predictions": pred_original, "targets": targets_original, + "predictions_scaled": predictions.copy(), "targets_scaled": targets.copy(), + } + + +def _valid_training_targets(targets): + return ( + torch.isfinite(targets).all(dim=0) + & (targets.max(dim=0).values > targets.min(dim=0).values) + ) + def _find_best_alphas( X_train: torch.Tensor, @@ -341,8 +580,14 @@ def _find_best_alphas( use_corr: bool = True, logger: Optional[logging.Logger] = None, singcutoff: float = 1e-10, + normalize_features: bool = False, + normalize_targets: bool = False, ) -> torch.Tensor: - """Find the best alpha(s) using inner cross-validation + """Find the best alpha(s) using inner cross-validation. + + If normalization is requested, a separate normalizer is fit on each inner + training subset and applied to its validation subset, so validation rows never + influence the statistics. Args: X_train: Training features tensor @@ -373,6 +618,24 @@ def _find_best_alphas( X_inner_val = X_train[inner_val_idx] y_inner_val = y_train[inner_val_idx] + valid_targets = ( + torch.isfinite(y_inner_train).all(dim=0) + & torch.isfinite(y_inner_val).all(dim=0) + & (y_inner_train.max(dim=0).values > y_inner_train.min(dim=0).values) + & (y_inner_val.max(dim=0).values > y_inner_val.min(dim=0).values) + ) + if normalize_features or normalize_targets: + inner_normalizer = DataNormalizer( + normalize_features=normalize_features, + normalize_targets=normalize_targets, + ) + X_inner_train, y_inner_train = inner_normalizer.fit_transform( + X_inner_train, y_inner_train + ) + X_inner_val, y_inner_val = inner_normalizer.transform( + X_inner_val, y_inner_val + ) + # Compute correlations for each alpha using ridge_corr corrs = ridge_corr_torch( X_inner_train, @@ -385,17 +648,27 @@ def _find_best_alphas( normalpha=normalpha, logger=logger, ) + corrs[:, ~valid_targets] = float("nan") inner_fold_corrs.append(corrs) # Average correlations across inner folds - mean_inner_corrs = torch.stack(inner_fold_corrs).mean( + mean_inner_corrs = torch.stack(inner_fold_corrs).nanmean( dim=0 ) # Shape: (n_alphas, n_voxels) + unselected = ~torch.isfinite(mean_inner_corrs).any(dim=0) + if unselected.any() and logger: + logger.warning( + "Targets without valid inner folds (first alpha is a placeholder): %s", + torch.where(unselected)[0].tolist(), + ) + # Find the best alpha if single_alpha: # Find single best alpha across all voxels - mean_across_voxels = mean_inner_corrs.mean(dim=1) # Shape: (n_alphas,) + mean_across_voxels = mean_inner_corrs.nanmean(dim=1) # Shape: (n_alphas,) + if not torch.isfinite(mean_across_voxels).any(): + raise ValueError("No valid targets for inner-CV alpha selection") best_alpha_idx = torch.argmax(mean_across_voxels) best_alpha = alphas[best_alpha_idx] best_valphas = torch.tensor( @@ -405,7 +678,7 @@ def _find_best_alphas( logger.info(f" Found best single alpha = {best_alpha:.3f} for all voxels") else: # Find the best alpha for each voxel - best_alpha_idx = torch.argmax(mean_inner_corrs, dim=0) # Shape: (n_voxels,) + best_alpha_idx = torch.argmax(torch.nan_to_num(mean_inner_corrs, nan=-float("inf")), dim=0) # Shape: (n_voxels,) best_valphas = torch.tensor( [alphas[i] for i in best_alpha_idx], device=X_train.device, dtype=torch.float32 ) @@ -416,10 +689,14 @@ def _find_best_alphas( def _calculate_correlations_pvalues( - y_true: np.ndarray, y_pred: np.ndarray + y_true: np.ndarray, y_pred: np.ndarray, *, inference: bool = True ) -> Tuple[List[float], List[float]]: """Calculate correlations and p-values between true and predicted values + A target that is constant or non-finite in this test set is invalid: its + correlation and p-value are NaN. A valid target with a constant prediction + keeps the previous convention (r=0, p=1). + Args: y_true: True target values (n_samples, n_targets) y_pred: Predicted target values (n_samples, n_targets) @@ -427,17 +704,58 @@ def _calculate_correlations_pvalues( Returns: Tuple of (correlations, p-values) lists """ + invalid = ( + ~np.isfinite(y_true).all(axis=0) + | ~np.isfinite(y_pred).all(axis=0) + | (np.ptp(y_true, axis=0) == 0) + ) + if invalid.any(): + logging.getLogger(__name__).warning( + f"{int(invalid.sum())}/{y_true.shape[1]} targets are constant or non-finite " + "or have non-finite predictions; reporting NaN and excluding them from summaries" + ) + correlations = [] pvalues = [] for i in range(y_true.shape[1]): - corr, pval = pearsonr(y_true[:, i], y_pred[:, i]) + if invalid[i]: + correlations.append(np.nan) + pvalues.append(np.nan) + continue + if inference: + corr, pval = pearsonr(y_true[:, i], y_pred[:, i]) + else: + estimate = y_pred[:, i].astype(np.float64) + actual = y_true[:, i].astype(np.float64) + estimate -= estimate.mean() + actual -= actual.mean() + norm = np.linalg.norm(estimate) * np.linalg.norm(actual) + corr = np.clip((estimate @ actual) / norm, -1, 1) if norm else 0.0 + pval = np.nan correlations.append(0.0 if np.isnan(corr) else corr) - pvalues.append(1.0 if np.isnan(pval) else pval) + pvalues.append((1.0 if np.isnan(pval) else pval) if inference else np.nan) return correlations, pvalues +def _fdr_valid(pvalues, alpha: float) -> Tuple[np.ndarray, np.ndarray]: + """FDR over finite p-values only; invalid targets are never significant.""" + pvalues = np.asarray(pvalues, dtype=float) + valid = np.isfinite(pvalues) + significant = np.zeros(pvalues.shape, dtype=bool) + corrected = np.full(pvalues.shape, np.nan) + if valid.any(): + significant[valid], corrected[valid] = fdrcorrection(pvalues[valid], alpha=alpha) + return significant, corrected + + +def _nanmedian(values) -> float: + values = np.asarray(values, dtype=float) + values = values[np.isfinite(values)] + return float(np.median(values)) if values.size else float("nan") + + def _combine_pvalues_across_folds( fold_pvalues: List[List[float]], logger: Optional[logging.Logger] = None ) -> np.ndarray: @@ -453,12 +771,14 @@ def _combine_pvalues_across_folds( all_pvalues = [] for i in range(len(fold_pvalues[0])): # For each voxel - # Get p-values from all folds for this voxel - voxel_pvals = [fold[i] for fold in fold_pvalues] + # Get p-values from the folds in which this voxel was a valid target + voxel_pvals = [fold[i] for fold in fold_pvalues if np.isfinite(fold[i])] + if not voxel_pvals: + all_pvalues.append(np.nan) # Some voxels might have all p-values as 1.0, which causes a warning # Handle this special case - if all(p == 1.0 for p in voxel_pvals): + elif all(p == 1.0 for p in voxel_pvals): all_pvalues.append(1.0) else: # Use Fisher's method to combine p-values across folds @@ -477,6 +797,25 @@ def _combine_pvalues_across_folds( return np.array(all_pvalues) +def _summary_scores(correlations) -> Dict[str, Union[float, int, List[bool]]]: + """Summary statistics over valid (finite) targets; NaN targets are counted.""" + correlations = np.asarray(correlations, dtype=float) + valid = np.isfinite(correlations) + if not valid.any(): + raise ValueError("No valid targets: every target is constant or non-finite") + scores = correlations[valid] + return { + "median_score": float(np.median(scores)), + "mean_score": float(np.mean(scores)), + "std_score": float(np.std(scores)), + "min_score": float(np.min(scores)), + "max_score": float(np.max(scores)), + "n_valid_targets": int(valid.sum()), + "n_invalid_targets": int((~valid).sum()), + "invalid_target_mask": (~valid).tolist(), + } + + def _create_metrics_dict( correlations: List[float], pvalues: List[float], @@ -499,19 +838,17 @@ def _create_metrics_dict( Dictionary of evaluation metrics """ metrics = { - "median_score": float(np.median(correlations)), - "mean_score": float(np.mean(correlations)), - "std_score": float(np.std(correlations)), - "min_score": float(np.min(correlations)), - "max_score": float(np.max(correlations)), - "best_alphas": best_alphas.tolist(), + **_summary_scores(correlations), + "best_alphas": None if best_alphas is None else best_alphas.tolist(), "correlations": correlations, "p_values": pvalues, "corrected_p_values": corrected_pvalues.tolist(), "significant_mask": significant_mask.tolist(), "n_significant": int(n_significant), - "percent_significant": float(n_significant / len(correlations) * 100), } + metrics["percent_significant"] = float( + n_significant / metrics["n_valid_targets"] * 100 + ) # Add metrics for significant voxels if there are any sig_correlations = ( @@ -556,12 +893,8 @@ def _create_full_cv_metrics_dict( Dictionary of evaluation metrics """ metrics = { - "median_score": float(np.median(all_correlations)), - "mean_score": float(np.mean(all_correlations)), - "std_score": float(np.std(all_correlations)), - "min_score": float(np.min(all_correlations)), - "max_score": float(np.max(all_correlations)), - "best_alphas": mean_valphas.tolist(), + **_summary_scores(all_correlations), + "best_alphas": None if mean_valphas is None else mean_valphas.tolist(), "correlations": all_correlations.tolist(), "p_values": all_pvalues.tolist(), "corrected_p_values": corrected_pvalues.tolist(), @@ -569,11 +902,12 @@ def _create_full_cv_metrics_dict( "majority_significant_mask": majority_significant_mask.tolist(), "n_significant": int(n_significant), "n_majority_significant": int(n_majority_significant), - "percent_significant": float(n_significant / len(all_correlations) * 100), - "percent_majority_significant": float( - n_majority_significant / len(all_correlations) * 100 - ), } + n_valid = metrics["n_valid_targets"] + metrics["percent_significant"] = float(n_significant / n_valid * 100) + metrics["percent_majority_significant"] = float( + n_majority_significant / n_valid * 100 + ) # Add metrics for Fisher's method significant voxels if there are any sig_correlations = ( diff --git a/encoding/models/ridge_regression.py b/encoding/models/ridge_regression.py index 16c5987..5c61e80 100644 --- a/encoding/models/ridge_regression.py +++ b/encoding/models/ridge_regression.py @@ -1,5 +1,5 @@ import torch -from typing import List, Union, Optional +from typing import List, Union, Optional, Tuple import logging from encoding.models.ridge_utils import svd_wrapper, mult_diag, z_score @@ -12,7 +12,8 @@ def ridge_torch( alphas: Union[float, torch.Tensor], singcutoff: float = 1e-30, normalpha: bool = False, -) -> torch.Tensor: + return_info: bool = False, +) -> Union[torch.Tensor, Tuple[torch.Tensor, dict]]: """PyTorch version of ridge function for computing weights Args: @@ -21,6 +22,7 @@ def ridge_torch( alphas: Ridge parameters (single float or per-voxel tensor) singcutoff: Cutoff for small singular values normalpha: Whether to normalize alpha by largest singular value + return_info: Also return effective fitted penalties for persistence. Returns: wt: Ridge regression weights (n_features, n_voxels) @@ -60,6 +62,8 @@ def ridge_torch( awt = torch.matmul(Vh_D, UR[:, selvox]) wt[:, selvox] = awt + if return_info: + return wt, {"effective_penalties": (nalphas ** 2).detach().cpu().numpy().copy()} return wt diff --git a/encoding/plotting/plotting_utils.py b/encoding/plotting/plotting_utils.py index 2021006..09991ad 100644 --- a/encoding/plotting/plotting_utils.py +++ b/encoding/plotting/plotting_utils.py @@ -235,13 +235,13 @@ def plot_all_correlations_histogram( """Plot histogram of all correlations.""" fig = plt.figure(figsize=(10, 6)) sns.set_theme(style="whitegrid") - valid_correlations = correlations[~np.isnan(correlations)] + valid_correlations = correlations[np.isfinite(correlations)] sns.histplot( valid_correlations, bins=100, color="blue", label="All", - kde=True, + kde=bool(valid_correlations.size > 1 and np.ptp(valid_correlations) > 0), stat="density", ) plt.legend() @@ -260,14 +260,14 @@ def plot_significant_correlations_histogram( fig = plt.figure(figsize=(10, 6)) sns.set_theme(style="whitegrid") sig_correlations = correlations[significant_mask] - valid_sig_correlations = sig_correlations[~np.isnan(sig_correlations)] + valid_sig_correlations = sig_correlations[np.isfinite(sig_correlations)] sns.histplot( valid_sig_correlations, bins=100, color="green", label="Significant", - kde=True, + kde=bool(valid_sig_correlations.size > 1 and np.ptp(valid_sig_correlations) > 0), stat="density", ) plt.legend() @@ -276,6 +276,16 @@ def plot_significant_correlations_histogram( plt.title(title) return fig + def log_descriptive_correlations(self, correlations): + """Report ECoG scores without a significance classification.""" + figure = self.plot_all_correlations_histogram( + correlations, title="Descriptive Pearson correlations (inference not assessed)" + ) + try: + self.logger.log_image("descriptive_correlation_histogram", figure) + finally: + plt.close(figure) + def log_plots( self, correlations: np.ndarray, @@ -285,18 +295,22 @@ def log_plots( is_volume: bool = False, language_mask: Optional[np.ndarray] = None, roi_masks: Optional[Dict[str, np.ndarray]] = None, + surface: Optional[bool] = None, ): """ Log brain surface plots and correlation histograms using the configured logger. Args: - correlations: (20484,) correlations for fsaverage5 surface (L then R) - significant_mask: (20484,) boolean mask of significant vertices + correlations: One-dimensional scores in target order. Only fsaverage5 + length (20484) is eligible for the legacy surface path. + significant_mask: Boolean mask matching the target scores prefix: optional namespace for log keys step: optional step number for logging is_volume: skip surface plotting if True language_mask: (20484,) optional boolean mask for language network roi_masks: optional dict[str, np.ndarray] of additional ROI masks + surface: False explicitly disables surfaces even for 20484 generic + targets; None preserves legacy fsaverage5 length detection. """ def _sanitize(name: str) -> str: @@ -311,25 +325,27 @@ def _sanitize(name: str) -> str: correlations = np.asarray(correlations) significant_mask = np.asarray(significant_mask, dtype=bool) - if not is_volume: - if correlations.shape[0] != full_len: - raise ValueError( - f"`correlations` must be length {full_len}, got {correlations.shape}" - ) - - if significant_mask.shape[0] != correlations.shape[0]: + if correlations.ndim != 1 or significant_mask.shape != correlations.shape: raise ValueError( - f"`significant_mask` must match correlations length, got {significant_mask.shape} vs {correlations.shape}" + "correlations must be one-dimensional and significant_mask must " + f"match its shape, got {correlations.shape} and {significant_mask.shape}" ) + # Generic target counts get histograms, without a surface download. + is_volume = is_volume or surface is False or len(correlations) != full_len + + def _log_image(name, figure, step=None): + try: + self.logger.log_image(name, figure, step) + finally: + plt.close(figure) # All correlations histogram fig_all = self.plot_all_correlations_histogram( correlations, title="All Correlations Distribution" ) - self.logger.log_image(f"{prefix}correlation_histogram_all", fig_all, step) - plt.close(fig_all) + _log_image(f"{prefix}correlation_histogram_all", fig_all, step) - valid_correlations = correlations[~np.isnan(correlations)] + valid_correlations = correlations[np.isfinite(correlations)] self.logger.log_histogram( f"{prefix}correlation_histogram_data_all", valid_correlations, step ) @@ -344,10 +360,9 @@ def _sanitize(name: str) -> str: is_volume=is_volume, ) if fig_significant is not None: - self.logger.log_image( + _log_image( f"{prefix}brain_surface_significant", fig_significant, step ) - plt.close(fig_significant) fig_all_surface = self.plot_surface_correlations( correlations, @@ -357,10 +372,9 @@ def _sanitize(name: str) -> str: is_volume=is_volume, ) if fig_all_surface is not None: - self.logger.log_image( + _log_image( f"{prefix}brain_surface_all", fig_all_surface, step ) - plt.close(fig_all_surface) # Significant correlations histogram fig_sig = self.plot_significant_correlations_histogram( @@ -368,13 +382,12 @@ def _sanitize(name: str) -> str: significant_mask, title="Significant Correlations Distribution", ) - self.logger.log_image( + _log_image( f"{prefix}correlation_histogram_significant", fig_sig, step ) - plt.close(fig_sig) sig_correlations = correlations[significant_mask] - valid_sig_correlations = sig_correlations[~np.isnan(sig_correlations)] + valid_sig_correlations = sig_correlations[np.isfinite(sig_correlations)] self.logger.log_histogram( f"{prefix}correlation_histogram_data_significant", valid_sig_correlations, @@ -409,8 +422,7 @@ def _sanitize(name: str) -> str: is_volume=is_volume, ) if fig_lang is not None: - self.logger.log_image(f"{prefix}lanA_surface", fig_lang, step) - plt.close(fig_lang) + _log_image(f"{prefix}lanA_surface", fig_lang, step) # ROI analysis if roi_masks: @@ -447,5 +459,4 @@ def _sanitize(name: str) -> str: is_volume=is_volume, ) if fig_roi is not None: - self.logger.log_image(f"{prefix}{key}_surface", fig_roi, step) - plt.close(fig_roi) + _log_image(f"{prefix}{key}_surface", fig_roi, step) diff --git a/encoding/trainer.py b/encoding/trainer.py index dc8a4b7..be69869 100644 --- a/encoding/trainer.py +++ b/encoding/trainer.py @@ -4,6 +4,7 @@ """ import logging +from copy import deepcopy from typing import Dict, List, Union, Any, Optional import numpy as np from datetime import datetime @@ -29,7 +30,7 @@ def __init__( feature_extractors: List[Any], # List of feature extractors downsampler: Any, # Downsampling component model: Any, # Training model - fir_delays: List[int], # FIR delay parameters + fir_delays: Optional[List[int]], # FIR delay parameters trimming_config: Dict, # Trimming configuration use_train_test_split: bool = False, # Data structuring mode # Feature extraction parameters @@ -44,6 +45,8 @@ def __init__( # Processing parameters downsample_config: Optional[Dict] = None, story_selection: Optional[List[str]] = None, + result_metadata: Optional[Dict[str, Any]] = None, + ecog_temporal_config: Optional[Dict[str, Any]] = None, ): """ Initialize with all components as dependencies. @@ -53,7 +56,8 @@ def __init__( feature_extractors: List of feature extraction components downsampler: Downsampling component model: Model with fit_predict() method - fir_delays: List of FIR delays to apply + fir_delays: Sample delays for fMRI. Pass None for ECoG. + ecog_temporal_config: ECoG delays, alignment, exclusion and memory declarations. trimming_config: Dict specifying how to trim data use_train_test_split: Whether to use train/test split vs concatenation layer_idx: Layer index for feature extraction @@ -65,6 +69,8 @@ def __init__( run_name: Custom run name downsample_config: Downsampling parameters story_selection: Specific stories to process (None = all) + result_metadata: Ordered target/sample metadata and provenance to + preserve. Missing target identities remain explicitly positional. """ self.assembly = assembly self.feature_extractors = feature_extractors @@ -74,6 +80,8 @@ def __init__( self.trimming_config = trimming_config self.use_train_test_split = use_train_test_split self.downsample_config = downsample_config or {} + self.result_metadata = deepcopy(result_metadata or {}) + self.ecog_temporal_config = deepcopy(ecog_temporal_config) # Feature extraction parameters self.layer_idx = layer_idx @@ -144,9 +152,13 @@ def extract_and_downsample_features(self) -> Dict[str, np.ndarray]: # Concatenate features from multiple extractors if len(story_features) > 1: - # Align timepoints - min_length = min(feat.shape[0] for feat in story_features) - story_features = [feat[:min_length] for feat in story_features] + lengths = [feat.shape[0] for feat in story_features] + if len(set(lengths)) > 1: + names = [type(e).__name__ for e in self.feature_extractors] + raise ValueError( + f"Story {story}: feature families have different row counts " + f"{dict(zip(names, lengths))}; refusing to truncate" + ) combined = np.concatenate(story_features, axis=1) else: combined = story_features[0] @@ -215,10 +227,53 @@ def structure_data(self, features: Dict[str, np.ndarray]) -> Dict[str, np.ndarra idx = self.assembly.stories.index(story) brain_data[story] = self.assembly.get_brain_data()[idx] + self.preparation_metadata_ = self._preparation_metadata(features, brain_data) if self.use_train_test_split: return self._create_train_test_split(features, brain_data) else: return self._create_concatenated_data(features, brain_data) + + def _preparation_metadata(self, features, brain_data): + """Describe existing slicing/preprocessing without changing alignment. + + Feature and neural source rows are separate: legacy trims can differ. + These coordinates describe what was fitted, not a temporal-safety claim. + """ + metadata = {"partitions": {}, "upstream_transforms": []} + stories = list(features) if self.use_train_test_split else self.stories_to_process + if self.use_train_test_split: + partitions = [("train", stories[:-1]), ("test", stories[-1:])] + else: + partitions = [("train", stories)] + for partition, names in partitions: + coordinates = {} + for domain, source in (("features", features), ("targets", brain_data)): + prefix = f"{partition}_" if self.use_train_test_split else "" + start = self.trimming_config.get(f"{prefix}{domain}_start", 0) + end = self.trimming_config.get(f"{prefix}{domain}_end", None) + rows = [] + for story in names: + indices = np.arange(len(source[story])) + if self.use_train_test_split: + indices = indices[start:end] + selected = source[story][indices] + metadata["upstream_transforms"].append({ + "kind": "legacy_per_story_zscore", "partition": partition, + "story": story, "domain": domain, "ddof": 0, + "mean": selected.mean(axis=0), "std": selected.std(axis=0), + "zero_std_policy": "demean_only", + "nan_to_num_after": domain == "features", + }) + rows.extend({"story": story, "source_index": int(i)} for i in indices) + if not self.use_train_test_split: + rows = rows[start:end] + coordinates[domain] = rows + metadata["partitions"][partition] = coordinates + metadata["prediction_input_units"] = ( + "legacy per-story standardized targets" if self.use_train_test_split + else "supplied neural target units" + ) + return metadata def _create_train_test_split(self, features: Dict, brain_data: Dict) -> Dict[str, np.ndarray]: """Create train/test split (Lebel style).""" @@ -283,14 +338,36 @@ def _create_concatenated_data(self, features: Dict, brain_data: Dict) -> Dict[st def train(self, **model_kwargs) -> Dict[str, Any]: """Run the complete training pipeline.""" - # Step 1: Extract and downsample features - features = self.extract_and_downsample_features() + self.last_run_dir_ = None + self.reporting_error_ = None + metadata = deepcopy(getattr(self, "result_metadata", {})) + metadata.update(deepcopy(model_kwargs.pop("result_metadata", {}))) + fit_options = dict(model_kwargs) + if getattr(self.assembly, "modality", None) == "ecog": + from encoding.ecog_temporal import prepare_ecog + from encoding.models.nested_cv import NestedCVModel + + if not isinstance(self.model, NestedCVModel): + raise ValueError("ECoG temporal fitting requires NestedCVModel") + data, temporal_metadata, cv = prepare_ecog( + self, getattr(self, "ecog_temporal_config", None) or {}, fit_options + ) + metadata.update(temporal_metadata) + fit_options["temporal_cv"] = cv + else: + # Step 1: Extract and downsample features + features = self.extract_and_downsample_features() - # Step 2: Apply FIR delays - delayed_features = self.apply_fir_delays(features) + # Step 2: Apply FIR delays + delayed_features = self.apply_fir_delays(features) - # Step 3: Structure data for training - data = self.structure_data(delayed_features) + # Step 3: Structure data for training + data = self.structure_data(delayed_features) + metadata["preparation"] = self.preparation_metadata_ + for partition, key in (("train", "sample_ids"), ("test", "test_sample_ids")): + if partition in self.preparation_metadata_["partitions"]: + rows = self.preparation_metadata_["partitions"][partition]["targets"] + metadata.setdefault(key, [f"{row['story']}:{row['source_index']}" for row in rows]) # Step 4: Train model logger.info("Starting model training...") @@ -301,26 +378,44 @@ def train(self, **model_kwargs) -> Dict[str, Any]: targets=data["Rresp"], X_test=data["Pstim"], y_test=data["Presp"], - **model_kwargs + result_metadata=metadata, + **fit_options ) else: # Cross-validation metrics, weights, best_alphas = self.model.fit_predict( features=data["X"], targets=data["Y"], - **model_kwargs + result_metadata=metadata, + **fit_options ) - # Step 5: Log and save results - self.log_metrics(metrics) - self.save_model(weights, best_alphas, metrics, model_kwargs) + # Core fitting/persistence failures propagate. Optional reporting runs + # only after the fitted results are safely published. + self.last_run_dir_ = self.save_model(weights, best_alphas, metrics, model_kwargs) + self.reporting_error_ = None + try: + self.log_metrics(metrics) + except Exception as error: + self.reporting_error_ = f"{type(error).__name__}: {error}" + logger.warning( + "Optional result reporting failed; fitted results are saved at %s: %s", + self.last_run_dir_, self.reporting_error_, exc_info=True, + ) - logger.info(f"Training complete. Median correlation: {metrics['median_score']:.4f}") + if metrics.get("evaluation") == "in_sample_diagnostic": + logger.info("In-sample diagnostic fit saved. Inference not assessed.") + else: + logger.info(f"Training complete. Median correlation: {metrics['median_score']:.4f}") return metrics def log_metrics(self, metrics: Dict): """Log metrics to configured backend.""" + if metrics.get("inference_status") == "not_assessed": + if "correlations" not in metrics: + return + self.brain_plotter.log_descriptive_correlations(np.asarray(metrics["correlations"])) self.experiment_logger.log_scalar("median_correlation", float(metrics["median_score"])) self.experiment_logger.log_scalar("mean_correlation", float(metrics["mean_score"])) self.experiment_logger.log_scalar("std_correlation", float(metrics["std_score"])) @@ -328,7 +423,13 @@ def log_metrics(self, metrics: Dict): if "correlations" in metrics and "significant_mask" in metrics: correlations = np.array(metrics["correlations"]) significant_mask = np.array(metrics["significant_mask"], dtype=bool) - self.brain_plotter.log_plots(correlations, significant_mask, "", False) + target_space = (getattr(self.model, "results_", None) or {}).get( + "metadata", {} + ).get("target_space") + self.brain_plotter.log_plots( + correlations, significant_mask, prefix="", is_volume=False, + surface=None if target_space is None else target_space == "fsaverage5", + ) if "best_alpha" in metrics: self.experiment_logger.log_scalar("best_alpha", float(metrics["best_alpha"])) @@ -346,13 +447,22 @@ def save_model(self, weights, best_alphas, metrics, model_kwargs): "lookback": self.lookback, "dataset_type": self.dataset_type, "stories_processed": len(self.stories_to_process), + "story_order": list(self.stories_to_process), + "feature_extractors": [ + {"class": type(extractor).__name__, **{ + key: getattr(extractor, key) for key in + ("model_name", "hook_type", "context_type", "last_token") + if hasattr(extractor, key) + }} for extractor in self.feature_extractors + ], **model_kwargs } - self.model_saver.save_encoding_model( + return self.model_saver.save_encoding_model( weights=weights, best_alphas=best_alphas, hyperparams=hyperparams, metrics=metrics, + results=getattr(self.model, "results_", None), ) diff --git a/encoding/utils.py b/encoding/utils.py index 0d3a2be..82f4159 100644 --- a/encoding/utils.py +++ b/encoding/utils.py @@ -199,6 +199,8 @@ def _get_cache_key( last_token: bool, dataset_type: str, raw: bool, + hook_type: str, + stimuli_sha256: str, ) -> str: """Generate a unique cache key for the given parameters. @@ -209,6 +211,8 @@ def _get_cache_key( context_type: Type of context (fullcontext, nocontext, halfcontext) last_token: Whether to use only the last token dataset_type: Type of dataset + hook_type: TransformerLens hook the activations were read from + stimuli_sha256: Hash of the exact stimulus strings fed to the model Returns: Cache key string @@ -221,6 +225,8 @@ def _get_cache_key( "last_token": last_token, "dataset_type": dataset_type, "raw": raw, + "hook_type": hook_type, + "stimuli_sha256": stimuli_sha256, } # Create a deterministic hash of the parameters key = hashlib.md5(json.dumps(params, sort_keys=True).encode()).hexdigest() @@ -297,87 +303,138 @@ def __init__(self, base_dir: str = "results"): self.base_dir = Path(base_dir) self.base_dir.mkdir(parents=True, exist_ok=True) - def _create_run_dir(self, hyperparams: Dict[str, Any]) -> Path: - """Create a unique directory for this run based on hyperparameters. - - Args: - hyperparams: Dictionary of hyperparameters - - Returns: - Path to the run directory - """ - # Create a unique hash of the hyperparameters - hyperparams_str = json.dumps(hyperparams, sort_keys=True) - run_hash = hashlib.md5(hyperparams_str.encode()).hexdigest()[:8] - - # Create directory with timestamp and hash - timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") - run_dir = self.base_dir / f"run_{timestamp}_{run_hash}" - run_dir.mkdir(parents=True, exist_ok=True) - - # Save hyperparameters - with open(run_dir / "hyperparams.json", "w") as f: - json.dump(hyperparams, f, indent=2) - - return run_dir + @staticmethod + def _json_value(value): + """Allow scientific configuration values without silently stringifying them.""" + if isinstance(value, np.ndarray): + return value.tolist() + if isinstance(value, np.generic): + return value.item() + if isinstance(value, Path): + return str(value) + raise TypeError(f"Cannot serialize configuration value {type(value).__name__}") def save_encoding_model( self, - weights: np.ndarray, - best_alphas: np.ndarray, + weights: Optional[np.ndarray], + best_alphas: Optional[np.ndarray], hyperparams: Dict[str, Any], metrics: Dict[str, Any], - save_weights: bool = False, + save_weights: bool = True, + results: Optional[Dict[str, Any]] = None, ) -> Path: - """Save encoding model weights and hyperparameters. - - Args: - weights: Model weights (n_features, n_targets) - best_alphas: Best alpha values for each target - hyperparams: Dictionary of hyperparameters - metrics: Dictionary of evaluation metrics + """Publish a complete, uniquely named version-2 run. - Returns: - Path to the run directory + Returned ridge arrays and fitted folds are saved when available. + With save_weights=False fitted state is omitted and stored predictions + and metadata remain available. + Pickle artifacts, including legacy metrics, must come from trusted sources. """ - # Create run directory - run_dir = self._create_run_dir(hyperparams) - - # Save weights and alphas - if save_weights: - np.save(run_dir / "weights.npy", weights) - - # Save metrics using pickle instead of JSON - with open(run_dir / "metrics.pkl", "wb") as f: - pickle.dump(metrics, f) - - return run_dir - - def load_encoding_model( - self, - run_dir: Union[str, Path], - ) -> Tuple[np.ndarray, np.ndarray, Dict[str, Any], Dict[str, Any]]: - """Load encoding model weights and hyperparameters. - - Args: - run_dir: Path to the run directory - - Returns: - Tuple of (weights, best_alphas, hyperparams, metrics) + import tempfile + from uuid import uuid4 + + # Validate configuration serialization before creating any output. + hyperparams_json = json.dumps(hyperparams, sort_keys=True, indent=2, + default=self._json_value) + run_hash = hashlib.md5(hyperparams_json.encode()).hexdigest()[:8] + stamp = datetime.now().strftime("%Y%m%d_%H%M%S") + destination = self.base_dir / f"run_{stamp}_{run_hash}_{uuid4().hex[:12]}" + with tempfile.TemporaryDirectory(prefix=".saving_", dir=self.base_dir) as tmp: + staging = Path(tmp) + (staging / "hyperparams.json").write_text(hyperparams_json) + if best_alphas is not None: + np.save(staging / "best_alphas.npy", best_alphas) + weights_saved = save_weights and weights is not None + if weights_saved: + np.save(staging / "weights.npy", weights) + with open(staging / "metrics.pkl", "wb") as f: + pickle.dump(metrics, f, protocol=pickle.HIGHEST_PROTOCOL) + payload = results + if results is not None and not save_weights: + payload = { + **results, + "folds": [ + {key: value for key, value in fold.items() + if key not in ("weights", "estimator_state")} + for fold in results.get("folds", []) + ], + } + if payload is not None: + with open(staging / "results.pkl", "wb") as f: + pickle.dump(payload, f, protocol=pickle.HIGHEST_PROTOCOL) + manifest = { + "format_version": 2, + "weights_saved": weights_saved, + "alphas_saved": best_alphas is not None, + "results_saved": payload is not None, + "replay_available": any( + "weights" in fold or "estimator_state" in fold + for fold in (payload or {}).get("folds", []) + ), + "returned_weights_role": ( + results["returned_weights_role"] if results else "caller_supplied_unspecified" + ), + "returned_alphas_role": ( + results["returned_alphas_role"] if results else "caller_supplied_unspecified" + ), + } + (staging / "manifest.json").write_text(json.dumps(manifest, indent=2)) + # Rename only after all files have been written. A failure is raised, + # never reported as a successful run or confused with plotting errors. + staging.replace(destination) + return destination + + def load_encoding_result(self, run_dir: Union[str, Path]) -> Dict[str, Any]: + """Load a trusted run, including fitted folds and metadata when available. + + Versionless legacy runs may lack weights/alphas. Return None for absent + weights and recover alphas only from recorded metrics, with an explicit + warning. Never invent a reproducible legacy model. """ run_dir = Path(run_dir) - - # Load weights and alphas - weights = np.load(run_dir / "weights.npy") - best_alphas = np.load(run_dir / "best_alphas.npy") - - # Load hyperparameters and metrics - with open(run_dir / "hyperparams.json", "r") as f: - hyperparams = json.load(f) + manifest_path = run_dir / "manifest.json" + manifest = json.loads(manifest_path.read_text()) if manifest_path.exists() else None + if manifest is not None and manifest.get("format_version") != 2: + raise ValueError(f"Unsupported encoding result format: {manifest.get('format_version')}") with open(run_dir / "metrics.pkl", "rb") as f: metrics = pickle.load(f) + hyperparams = json.loads((run_dir / "hyperparams.json").read_text()) + if manifest is not None: + weights = np.load(run_dir / "weights.npy", allow_pickle=False) if manifest["weights_saved"] else None + alphas = (np.load(run_dir / "best_alphas.npy", allow_pickle=False) + if manifest.get("alphas_saved", True) else None) + if manifest["results_saved"]: + with open(run_dir / "results.pkl", "rb") as f: + results = pickle.load(f) + else: + results = None + else: + weights_path = run_dir / "weights.npy" + alphas_path = run_dir / "best_alphas.npy" + weights = np.load(weights_path, allow_pickle=False) if weights_path.exists() else None + recorded = metrics.get("best_alphas") + alphas = (np.load(alphas_path, allow_pickle=False) if alphas_path.exists() + else np.asarray(recorded) if recorded is not None else None) + results = None + logger.warning( + "Legacy run has no fitted-fold/transform provenance; replay is unverified " + "(weights present: %s, alphas present: %s)", weights is not None, alphas is not None, + ) + return {"format_version": manifest["format_version"] if manifest else 1, + "manifest": manifest, "weights": weights, "best_alphas": alphas, + "hyperparams": hyperparams, "metrics": metrics, "results": results} - return weights, best_alphas, hyperparams, metrics + def load_encoding_model( + self, run_dir: Union[str, Path], + ) -> Tuple[Optional[np.ndarray], Optional[np.ndarray], Dict[str, Any], Dict[str, Any]]: + """Compatibility four-tuple loader; use load_encoding_result for folds. + + In nested CV, returned weights/alphas are descriptive fold means, not a + fitted full-data model. Replay an identified fold from results instead. + """ + loaded = self.load_encoding_result(run_dir) + return (loaded["weights"], loaded["best_alphas"], + loaded["hyperparams"], loaded["metrics"]) def list_runs(self) -> List[Dict[str, Any]]: """List all saved runs with their hyperparameters and metrics. diff --git a/tests/conftest.py b/tests/conftest.py index 2f6e689..37e6b78 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -273,6 +273,9 @@ def __init__(self, logger=None): def log_plots(self, *args, **kwargs): self.calls += 1 + def log_descriptive_correlations(self, *args, **kwargs): + self.calls += 1 + @pytest.fixture(autouse=True) def _no_external_side_effects(monkeypatch): diff --git a/tests/test_ecog_assembly.py b/tests/test_ecog_assembly.py new file mode 100644 index 0000000..479da33 --- /dev/null +++ b/tests/test_ecog_assembly.py @@ -0,0 +1,319 @@ +"""M3 assembly-only acceptance: clocks, identity, validity and legacy loading.""" +from copy import deepcopy +import json +from pathlib import Path +import subprocess +import sys + +import numpy as np +import pytest + +from encoding.assembly import ECoGAssemblyGenerator, load_assembly, save_assembly +from encoding.assembly.assemblies import SimpleNeuroidAssembly +from encoding.assembly.assembly_generator import AssemblyGenerator +from encoding.assembly.story_data import StoryData + + +def recording(name='run-A', origin=10.): + # A deliberately non-anatomical order must be kept exactly as supplied. + return { + 'recording_id': name, 'subject_id': 'S1', 'run_id': name, + 'brain_data': np.arange(16, dtype=np.float32).reshape(8, 2), + 'neural_times': origin + np.arange(8) / 4, + 'sampling_rate_hz': 4., 'neural_time_unit': 's', + 'stimulus_time_unit': 's', 'neural_clock': 'recording', + 'stimulus_clock': 'recording', + 'stimulus_times': origin + np.array([0., .25, .25, 1., 1.999]), + 'words': ['one', '', 'two', 'three', 'four'], + 'word_ids': ['w0', 'empty', 'w2', 'w3', 'w4'], + 'stimuli': ['one', '', 'one two', 'two three', 'three four'], + 'electrodes': [{'electrode_id': 'E9', 'label': 'first supplied channel'}, + {'electrode_id': 'E1', 'quality': 'synthetic'}], + 'signal_units': 'fixture units', 'valid_samples': np.ones(8, dtype=bool), + 'provenance': {'source': 'synthetic M3 fixture', + 'preprocessing': {'description': 'already supplied synthetic trace', + 'filter_support': 'not applicable'}, + 'stimulus_context': {'policy': 'precomputed fixture strings'}}, + } + + +def generate(*records, **kwargs): + return ECoGAssemblyGenerator().generate_assembly('S1', recordings=list(records), **kwargs) + + +def test_bins_empty_events_and_explicit_count_rate_units(): + r = recording() + assembly = generate(r) + story = assembly.story_data['run-A'] + assert len(story.split_indices) == len(story.tr_times) - 1 + assert story.split_indices == [1, 3, 3, 3, 4, 4, 4] + np.testing.assert_array_equal(story.word_rates[:, 0], [1, 1, 0, 0, 1, 0, 0, 1]) + assert story.sample_metadata['word_rates_units'] == 'words/bin' + np.testing.assert_array_equal(story.sample_metadata['words_per_second'], story.word_rates * 4) + assert story.words == r['words'] and story.stimuli == r['stimuli'] + assert story.sample_metadata['word_ids'] == r['word_ids'] + # At an edge the event belongs to the next bin; even the immediately + # preceding representable float remains in the previous bin (no snapping). + r['stimulus_times'][0] = np.nextafter(r['neural_times'][1], -np.inf) + edge = generate(r).story_data['run-A'] + assert edge.split_indices[0] == 1 + + +def test_invalid_rows_and_recording_gaps_keep_positions_and_order(): + first, second = recording(), recording('run-B', origin=100.) + first['valid_samples'][2:4] = False + first['brain_data'][2:4] = np.nan + first['sample_ids'] = [f'original-{i}' for i in range(8)] + first['invalid_sample_reasons'] = [None, None, 'missing slot', 'artifact', None, None, None, None] + first['invalid_intervals'] = [{'start': 10.5, 'stop': 11., 'reason': 'gap and artifact'}] + first['recording_metadata'] = {'session': 'synthetic session'} + original = deepcopy(first) + assembly = generate(first, second) + assert assembly.shape == (16, 2) + assert assembly.stories == ['run-A', 'run-B'] + assert assembly.recording_slices == {'run-A': (0, 8), 'run-B': (8, 16)} + assert assembly.validation_method == 'unconfigured' + np.testing.assert_array_equal(assembly.get_tr_times()[0], original['neural_times']) + np.testing.assert_array_equal(assembly.get_tr_times()[1], second['neural_times']) + np.testing.assert_array_equal(assembly.get_brain_data()[0], original['brain_data']) + assert assembly.get_brain_data()[0].dtype == np.float32 + assert len(assembly.get_coord('recording_id')) == 16 # neural, not word rows + assert assembly.get_coord('sample_time_s')[8] == 100. + assert assembly.get_coord('sample_id')[2] == 'original-2' + assert assembly.get_coord('sample_index')[8] == 0 + assert assembly.get_coord('electrode_id').tolist() == ['E9', 'E1'] + assert not assembly.get_coord('valid_sample')[2:4].any() + metadata = assembly.get_sample_metadata()[0] + assert metadata['invalid_intervals_native'] == original['invalid_intervals'] + assert metadata['invalid_sample_reasons'][2] == 'missing slot' + assert metadata['recording_metadata'] == first['recording_metadata'] + assert metadata['validity_applied'] is False + np.testing.assert_array_equal(first['brain_data'], original['brain_data']) + first['brain_data'][0] = 999 + assert assembly.get_brain_data()[0][0, 0] == 0 # owns its input snapshot + + +def test_units_common_clock_and_explicit_affine_synchronization(): + r = recording() + r['neural_times'] *= 1000 + r['neural_time_unit'] = 'ms' + r['stimulus_clock'] = 'audio' + r['stimulus_time_unit'] = 'us' + expected = r['stimulus_times'].copy() + # Explicit mapping with a declared scale and offset, not a fitted alignment. + r['stimulus_times'] = (expected - 10.) / 2 * 1e6 + r['synchronization'] = {'source_clock': 'audio', 'target_clock': 'recording', + 'scale': 2., 'offset_s': 10., + 'provenance': {'source': 'synthetic fixed transform'}} + assembly = generate(r) + story = assembly.story_data['run-A'] + np.testing.assert_allclose(story.data_times, expected, atol=0, rtol=0) + np.testing.assert_array_equal(story.tr_times, recording()['neural_times']) + np.testing.assert_array_equal(story.sample_metadata['neural_times_native'], r['neural_times']) + np.testing.assert_array_equal(story.sample_metadata['stimulus_times_native'], r['stimulus_times']) + assert story.sample_metadata['synchronization'] == r['synchronization'] + common = recording() + common['stimulus_times'] *= 1000 + common['stimulus_time_unit'] = 'ms' + np.testing.assert_allclose(generate(common).get_data_times()[0], recording()['stimulus_times']) + + +@pytest.mark.parametrize('change,match', [ + ({'sampling_rate_hz': 0}, 'sampling_rate_hz'), + ({'sampling_rate_hz': -4}, 'sampling_rate_hz'), + ({'sampling_rate_hz': np.nan}, 'sampling_rate_hz'), + ({'sampling_rate_hz': True}, 'sampling_rate_hz'), + ({'sampling_rate_hz': 10}, 'uniform'), + ({'neural_times': [10, 10.25, 10.25, 10.75, 11, 11.25, 11.5, 11.75]}, 'strictly increasing'), + ({'neural_times': [10, 10.25, 10.75, 11, 11.25, 11.5, 11.75, 12]}, 'retain missing slots'), + ({'neural_times': [10, 10.25]}, 'match brain_data'), + ({'neural_times': [10, 10.25, 10.5, np.nan, 11, 11.25, 11.5, 11.75]}, 'finite'), + ({'neural_time_unit': 'unknown'}, 'Time units'), + ({'stimulus_time_unit': 'samples'}, 'Time units'), + ({'stimulus_clock': 'different'}, 'synchronization'), + ({'neural_clock': ''}, 'neural_clock'), + ({'stimulus_times': [10, 10.5, 10.25, 11, 11.9]}, 'ordered'), + ({'stimulus_times': [10, 10.25, 10.25, 11, 12.]}, 'half-open'), + ({'stimulus_times': [9, 10.25, 10.25, 11, 11.9]}, 'inside'), + ({'stimulus_times': [10, 10.25]}, 'match words'), + ({'word_ids': ['a'] * 5}, 'unique IDs'), + ({'word_ids': ['a']}, 'per row'), + ({'sample_ids': ['s'] * 8}, 'unique IDs'), + ({'words': ['one', 'two', 3, 'four', 'five']}, 'strings'), + ({'stimuli': ['only one']}, 'matching transcript'), + ({'electrodes': [{'electrode_id': 'E1'}, {'electrode_id': 'E1'}]}, 'unique'), + ({'electrodes': [{'electrode_id': 'E1'}]}, 'columns'), + ({'brain_data': np.zeros((8, 3))}, 'columns'), + ({'brain_data': np.zeros((8, 2), dtype=complex)}, 'real numeric'), + ({'brain_data': np.full((8, 2), np.nan)}, 'explicitly invalid'), + ({'valid_samples': [1] * 8}, 'boolean'), + ({'valid_samples': [True] * 7}, 'matching neural rows'), + ({'provenance': {}}, 'provenance.source'), + ({'provenance': {'source': 'x', 'preprocessing': {}}}, 'preprocessing'), + ({'signal_units': ''}, 'signal_units'), + ({'subject_id': 'other subject'}, 'requested subject'), + ({'invalid_intervals': [{'start': 10.5, 'stop': 10.5, 'reason': 'x'}]}, 'positive duration'), + ({'invalid_intervals': [{'start': 9, 'stop': 10.5, 'reason': 'x'}]}, 'inside'), + ({'invalid_intervals': [{'start': 10, 'stop': 10.5, 'reason': 'x'}]}, 'agree'), + ({'invalid_sample_reasons': ['artifact'] * 8}, 'agree'), + ({'recording_metadata': []}, 'recording_metadata'), +]) +def test_malformed_recordings_fail_without_repair(change, match): + r = recording() + r.update(change) + with pytest.raises(ValueError, match=match): + generate(r) + + +def test_duplicate_recordings_or_changed_electrode_order_are_not_merged(): + with pytest.raises(ValueError, match='Duplicate recording_id'): + generate(recording(), recording()) + second = recording('run-B', origin=100.) + second['electrodes'].reverse() + with pytest.raises(ValueError, match='identical electrode IDs/order'): + generate(recording(), second) + second = recording('run-B', origin=100.) + second['brain_data'] = second['brain_data'].astype(np.float64) + with pytest.raises(ValueError, match='no implicit precision conversion'): + generate(recording(), second) + + +@pytest.mark.parametrize('sync', [ + {'scale': -1., 'offset_s': 0., 'source_clock': 'audio', 'target_clock': 'recording', 'provenance': {'source': 'x'}}, + {'scale': 1., 'offset_s': np.inf, 'source_clock': 'audio', 'target_clock': 'recording', 'provenance': {'source': 'x'}}, + {'scale': 1., 'offset_s': 0., 'source_clock': 'wrong', 'target_clock': 'recording', 'provenance': {'source': 'x'}}, + {'scale': 1., 'offset_s': 0., 'source_clock': 'audio', 'target_clock': 'recording', 'provenance': {}}, +]) +def test_malformed_synchronization_is_rejected(sync): + r = recording(); r['stimulus_clock'] = 'audio'; r['synchronization'] = sync + with pytest.raises(ValueError, match='synchronization'): + generate(r) + + +def test_metadata_round_trip_and_optional_coordinate_space(tmp_path): + r = recording() + r['valid_samples'][1] = False + r['brain_data'][1] = np.nan + r['sample_ids'] = [f'source-{i}' for i in range(8)] + r['invalid_intervals'] = [{'start': 10.25, 'stop': 10.5, 'reason': 'synthetic missing slot'}] + r['electrodes'][0].update(coordinates=[1., 2., 3.], coordinate_space='fixture space', coordinate_units='mm') + assembly = generate(r) + path = tmp_path / 'ecog.pkl' + save_assembly(assembly, path) + loaded = load_assembly(path) + assert loaded.get_target_metadata() == assembly.get_target_metadata() + assert loaded.get_provenance() == [r['provenance']] + assert loaded.recording_slices == assembly.recording_slices + np.testing.assert_array_equal(loaded.get_brain_data()[0], r['brain_data']) + assert loaded.get_sample_metadata()[0]['sample_ids'] == r['sample_ids'] + assert loaded.get_sample_metadata()[0]['invalid_intervals_native'] == r['invalid_intervals'] + for key in ['valid_samples', 'neural_times_native', 'stimulus_times_native', 'words_per_second']: + np.testing.assert_array_equal(loaded.get_sample_metadata()[0][key], assembly.get_sample_metadata()[0][key]) + del r['electrodes'][0]['coordinate_space'] + with pytest.raises(ValueError, match='coordinate_space'): + generate(r) + + +def write_manifest(tmp_path): + r = recording() + for field in ['brain_data', 'neural_times', 'stimulus_times', 'valid_samples']: + np.save(tmp_path / f'{field}.npy', r[field]) + r[field] = {'npy': f'{field}.npy'} + path = tmp_path / 'ecog.json' + path.write_text(json.dumps({'schema_version': 1, 'recordings': [r]})) + return path + + +def test_manifest_factory_and_no_fmri_imports_or_downloads(tmp_path): + manifest = write_manifest(tmp_path) + assembly = AssemblyGenerator.generate_assembly('ecog', str(tmp_path), 'S1') + np.testing.assert_array_equal(assembly.get_brain_data()[0], recording()['brain_data']) + script = ''' +import sys +class BlockSetupImports: + def find_spec(self, fullname, path=None, target=None): + if fullname.split('.')[0] in {'nibabel', 'nilearn', 'transformers', 'torch'} or fullname in { + 'encoding.assembly.base_processor', 'encoding.brain_projection'}: + raise AssertionError('ECoG assembly imported setup dependency: ' + fullname) +sys.meta_path.insert(0, BlockSetupImports()) +from encoding.assembly.assembly_generator import AssemblyGenerator +a = AssemblyGenerator.generate_assembly('ecog', sys.argv[1], 'S1') +assert a.shape == (8, 2) +assert a.validation_method == 'unconfigured' +''' + completed = subprocess.run([sys.executable, '-c', script, str(manifest)], + cwd=Path(__file__).resolve().parents[1], capture_output=True, text=True) + assert completed.returncode == 0, completed.stdout + completed.stderr + with pytest.raises(ValueError, match='fMRI volume/mask'): + AssemblyGenerator.create('ecog', None, use_volume=True) + with pytest.raises(ValueError, match='sampling_rate_hz'): + AssemblyGenerator.create('ecog', None, tr=2.) + with pytest.raises(ValueError, match='only for ECoG'): + AssemblyGenerator.generate_assembly('lebel', None, 'S1', recordings=[recording()]) + + +def test_manifest_does_not_load_pickle_arrays_or_unknown_schema(tmp_path): + manifest = write_manifest(tmp_path) + obj = json.loads(manifest.read_text()) + obj['schema_version'] = 2 + manifest.write_text(json.dumps(obj)) + with pytest.raises(ValueError, match='schema_version'): + ECoGAssemblyGenerator(tmp_path).generate_assembly('S1') + obj['schema_version'] = 1 + np.save(tmp_path / 'object.npy', np.array([{'not': 'numeric data'}], dtype=object)) + obj['recordings'][0]['brain_data'] = {'npy': 'object.npy'} + manifest.write_text(json.dumps(obj)) + with pytest.raises(ValueError, match='allow_pickle=False'): + ECoGAssemblyGenerator(tmp_path).generate_assembly('S1') + + +class WordTokenizer: + name_or_path = 'synthetic token fixture' + + def encode(self, text, add_special_tokens=False): + return text.split() + + def decode(self, tokens): + return ' '.join(tokens) + + +@pytest.mark.parametrize('policy,expected', [ + ('fullcontext', ['one', '', 'one two', 'two three', 'three four']), + ('nocontext', ['one', '', 'one two', 'three', 'three four']), + ('halfcontext', ['one', '', 'one two', 'two three', 'three four']), +]) +def test_shared_context_policies_with_explicit_tokenizer(policy, expected): + r = recording(); del r['stimuli'] + original_provenance = deepcopy(r['provenance']) + assembly = ECoGAssemblyGenerator(tokenizer=WordTokenizer()).generate_assembly( + 'S1', recordings=[r], context_type=policy, lookback=2) + story = assembly.story_data['run-A'] + assert story.stimuli == expected + assert story.provenance == original_provenance + assert story.sample_metadata['stimulus_context']['context_type'] == policy + assert story.sample_metadata['stimulus_context']['lookback'] == 2 + expected_sources = [0, 1, 0, 1, 2] if policy == 'fullcontext' else [0, 1, 0, 0, 0] + np.testing.assert_array_equal(story.sample_metadata['context_source_indices'], expected_sources) + with pytest.raises(ValueError, match='explicit tokenizer'): + generate(r) + + +def test_empty_transcript_and_legacy_fmri_state_remain_supported(tmp_path): + r = recording(); r.update(words=[], word_ids=[], stimulus_times=[], stimuli=[]) + silent = generate(r).story_data['run-A'] + assert silent.stimuli == [] and silent.data_times.size == 0 + np.testing.assert_array_equal(silent.word_rates, np.zeros((8, 1))) + legacy = StoryData('fmri', np.ones((3, 2)), ['word'], [1, 1], np.arange(3.), np.array([0.])) + for key in ['target_metadata', 'sample_metadata', 'provenance']: + del legacy.__dict__[key] # emulate fields absent from an older pickle + assembly = SimpleNeuroidAssembly([legacy], validation_method='outer') + original_coords = deepcopy(assembly.coords) + path = tmp_path / 'old.pkl'; save_assembly(assembly, path) + loaded = load_assembly(path) + assert loaded.get_target_metadata() == [None] + assert loaded.get_sample_metadata() == [None] + assert loaded.get_provenance() == [None] + np.testing.assert_array_equal(loaded.get_brain_data()[0], assembly.get_brain_data()[0]) + assert loaded.get_validation_method() == 'outer' + for key, coord in original_coords.items(): + np.testing.assert_array_equal(loaded.get_coord(key), coord['values']) diff --git a/tests/test_ecog_end_to_end.py b/tests/test_ecog_end_to_end.py new file mode 100644 index 0000000..defbfda --- /dev/null +++ b/tests/test_ecog_end_to_end.py @@ -0,0 +1,334 @@ +"""M5 public pipeline acceptance, with an independent synthetic oracle. + +Frozen acceptance design: three 512-row recordings, AR(1) coefficient .65, two +electrodes, 12 null seeds 100–111, seed 29 for signal, and the gates below. +Null gates are on per-seed averages over electrodes and held-out blocks. +They are engineering checks for gross bias, not calibrated significance tests. +""" +import numpy as np +import pytest +from scipy.signal import lfilter + +from encoding.assembly import ECoGAssemblyGenerator +from encoding.features.embeddings import StaticEmbeddingFeatureExtractor +from encoding.features.language_model import LanguageModelFeatureExtractor +from encoding.features.simple_features import WordRateFeatureExtractor +from encoding.features.speech_model import SpeechFeatureExtractor +from encoding.models import nested_cv +from encoding.trainer import AbstractTrainer +from encoding.utils import ActivationCache, SpeechActivationCache +from test_ecog_assembly import recording + +N = 512 +OFFSETS = (0, 1, 3) +REQUESTED = [0., .24, .74] +ALPHAS = [1e-4, .01, .1] +CUTOFF = 1e-5 +KERNEL = np.array([ + [.5, -.4], [.2, .1], [-.3, .2], [.4, -.2], + [-.6, .3], [.1, -.3], [.4, .1], [-.1, .5], + [.2, -.2], [-.2, .6], [.1, -.3], [.3, .3], +], dtype=np.float32) +NULL_SEEDS = range(100, 112) +SIGNAL_R_MIN = .995 +KERNEL_RELATIVE_MAX = .06 +CONDITION_MAX = 12 +NULL_BIAS_MAX = .06 +NULL_MEAN_ABS_MAX = .08 +NULL_MAX_ABS = .25 +REFERENCE_ATOL = 3e-5 +REPLAY_ATOL = 2e-6 +INNER_SCORE_ATOL = 2e-6 + + +def ar(rng, count): + # Burn-in avoids a deterministic transient shared between streams. + return lfilter([np.sqrt(1 - .65**2)], [1, -.65], rng.normal(size=count + 64))[64:] + + +def fixture(seed, signal): + records, frames, activations, expected = [], {}, {}, {} + for run, streams in enumerate(np.random.SeedSequence(seed).spawn(3)): + srng, yrng = [np.random.default_rng(s) for s in streams.spawn(2)] + name, origin = f"run-{run}", float(100 * run) + rec = recording(name, origin) + rec["neural_times"] = origin + np.arange(N) / 4 + rec["valid_samples"] = np.ones(N, dtype=bool) + rec["valid_samples"][83:89] = False + rec["invalid_intervals"] = [ + dict(start=origin + 83 / 4, stop=origin + 89 / 4, reason="neural gap") + ] + rec["sample_ids"] = [f"{name}:sample:{i}" for i in range(N)] + rec["audio_path"] = f"{name}.wav" # mock consumes the identifier, no file read + rec["provenance"]["preprocessing"]["support_s"] = [0, 0] + rec["words"], rec["stimuli"], rec["word_ids"], rec["stimulus_times"] = [], [], [], [] + counts = (ar(srng, N) > 0).astype(int) * 2 + signs = np.where(ar(srng, N * 2).reshape(N, 2) > 0, 1, -1) + language = ar(srng, N).astype(np.float32) + speech = ar(srng, N // 2).astype(np.float32) + even = np.arange(0, N, 2) + base = np.zeros((N, 4), dtype=np.float64) + for i in range(N): + for event in range(counts[i]): + ident = f"{name}:{i}:{event}" + rec["words"].append("plus" if signs[i, event] > 0 else "minus") + rec["stimuli"].append(ident) + rec["word_ids"].append(ident) + rec["stimulus_times"].append(origin + i / 4 + event / 16) + activations[ident] = language[i] / 2 + if counts[i]: + base[i, 0] = language[i] + base[i, 1] = signs[i].sum() + base[i, 2] = 4 * counts[i] + if i % 2 == 0: + base[i, 3] = speech[i // 2] + elif i < N - 1: + base[i, 3] = (float(speech[i // 2]) + float(speech[i // 2 + 1])) / 2 + observed = speech.copy() + observed[100] = np.nan + frames[rec["audio_path"]] = ({0: observed[:, None]}, even / 4) + noise = np.column_stack([ar(yrng, N), ar(yrng, N)]) + response = noise * (.015 if signal else 1.) + for i in range(N): + if signal: + for lag_index, lag in enumerate(OFFSETS): + if i >= lag: + response[i] += base[i - lag] @ KERNEL[4 * lag_index:4 * (lag_index + 1)] + rec["brain_data"] = (response + [2., -3.]).astype(np.float32) + rec["brain_data"][~rec["valid_samples"]] = np.nan + for i in range(N): + source = [i - lag for lag in OFFSETS] + if (not rec["valid_samples"][i] + or any(j < 2 or j >= N - 1 or 199 <= j <= 201 for j in source)): + continue + # Half-open event bins and speech brackets with one sample of past + # support. This is the oracle, independent of production helpers. + left = min(j - j % 2 - 1 for j in source) + right = max(np.nextafter(origin + (j + 1) / 4, -np.inf) for j in source) + right = max(right, max(origin + (j + j % 2) / 4 for j in source)) + expected[(name, i)] = (np.concatenate([base[j] for j in source]), + rec["brain_data"][i], [origin + left / 4, right]) + records.append(rec) + return records, frames, activations, expected + + +def run(path, data, monkeypatch, *, observe_normalizers=False, model=None): + records, frames, activations, oracle = data + path.mkdir() + vectors = path / "tiny.w2v.txt" + vectors.write_text("2 1\nplus 1\nminus -1\n") + static = StaticEmbeddingFeatureExtractor(dict( + vector_path=str(vectors), oov_handling="error", use_tqdm=False, + )) + language = object.__new__(LanguageModelFeatureExtractor) + language.model_name, language.hook_type = "fixture-lm", "fixture-hook" + language.activation_cache = ActivationCache(path / "language_cache") + language.extract_all_layers = lambda texts: { + 0: np.array([activations[text] for text in texts], dtype=np.float32)[:, None] + } + speech = object.__new__(SpeechFeatureExtractor) + speech.model_name, speech.chunk_size, speech.context_size = "fixture-speech", .5, .25 + speech.pool, speech.target_sample_rate = "mean", 4 + speech.speech_cache = SpeechActivationCache(path / "speech_cache") + speech.extract_all_layers = frames.__getitem__ + assembly = ECoGAssemblyGenerator().generate_assembly("S1", recordings=records) + if model is None: + model = nested_cv.NestedCVModel("ridge") + trainer = AbstractTrainer( + assembly, [language, static, WordRateFeatureExtractor({}), speech], None, model, + None, {}, layer_idx=0, dataset_type="ecog", logger_backend="tensorboard", + results_dir=str(path / "results"), + ecog_temporal_config=dict( + delays_s=REQUESTED, protocol="blocked", embargo_s=.5, + memory_budget_bytes=64_000_000, + feature_specs=[ + dict(method="word_sum", support_s=[0, 0]), + dict(method="word_sum", support_s=[0, 0]), + dict(method="words_per_second", support_s=[0, 0]), + dict(method="speech_linear", support_s=[0, 0], max_gap_s=.5, + frame_origin_s={r["recording_id"]: r["neural_times"][0] for r in records}), + ], + ), + ) + observed = {} + normalizer_inputs = [] + inner_scores = [] + original_score = nested_cv.ridge_corr_torch + fit = model.fit_predict + original_fit = nested_cv.DataNormalizer.fit + + def inspect_design(features, targets, **kwargs): + observed.update(x=features, y=targets) + return fit(features, targets, **kwargs) + + def inspect_normalizer(self, x, y): + normalizer_inputs.append((x.numpy().copy(), y.numpy().copy())) + return original_fit(self, x, y) + + def inspect_score(*args, **kwargs): + scores = original_score(*args, **kwargs) + inner_scores.append(scores.numpy().copy()) + return scores + + with monkeypatch.context() as patch: + patch.setattr(model, "fit_predict", inspect_design) + if observe_normalizers: + patch.setattr(nested_cv.DataNormalizer, "fit", inspect_normalizer) + patch.setattr(nested_cv, "ridge_corr_torch", inspect_score) + trainer.train(alphas=ALPHAS if model.estimator is None else None, n_outer_folds=4, n_inner_folds=2, use_gpu=False, + normalpha=True, normalize_features=True, normalize_targets=True, + singcutoff=CUTOFF) + result = trainer.model_saver.load_encoding_result(trainer.last_run_dir_) + metadata = result["results"]["metadata"]["temporal"] + keys = [(r["recording_id"], r["source_index"]) for r in metadata["rows"]] + assert keys == list(oracle) + x, y, bounds = map(np.array, zip(*(oracle[key] for key in keys))) + np.testing.assert_allclose(observed["x"], x, atol=1e-7, rtol=0) + np.testing.assert_array_equal(observed["y"], y) + np.testing.assert_array_equal(metadata["support_bounds_s"], bounds) + for row in metadata["rows"] + metadata["exclusions"]: + run_index = int(row["recording_id"].split("-")[1]) + source = records[run_index] + i = row["source_index"] + assert row["sample_id"] == source["sample_ids"][i] + assert row["time_s"] == source["neural_times"][i] + excluded = {(r["recording_id"], r["source_index"]) for r in metadata["exclusions"]} + assert excluded == {(r["recording_id"], i) for r in records for i in range(N)} - set(keys) + return result, x.astype(np.float32), y, keys, normalizer_inputs, inner_scores + + +def reference(x_train, y_train, x_test, alphas): + """Independent NumPy CPU float32 ridge in normalized coordinates.""" + x_mean, y_mean = x_train.mean(axis=0), y_train.mean(axis=0) + x_scale = x_train.std(axis=0, ddof=1) + np.float32(1e-8) + y_scale = y_train.std(axis=0, ddof=1) + np.float32(1e-8) + x = (x_train - x_mean) / x_scale + y = (y_train - y_mean) / y_scale + u, s, vt = np.linalg.svd(x, full_matrices=False) + condition = s[0] / s[-1] + keep = s > CUTOFF + penalty = (np.broadcast_to(np.asarray(alphas, dtype=np.float32), y.shape[1]) * s[0]) ** 2 + s = s[keep] + weights = np.column_stack([ + vt[keep].T @ ((s / (s**2 + penalty[i])) * (u[:, keep].T @ y[:, i])) + for i in range(y.shape[1]) + ]) + prediction = ((x_test - x_mean) / x_scale) @ weights * y_scale + y_mean + return prediction, weights, penalty, condition + + +def correlations(a, b): + return np.array([np.corrcoef(a[:, i], b[:, i])[0, 1] for i in range(a.shape[1])]) + + +def check_purge(metadata, keys, eligible, train, held, purged): + bounds = np.array(metadata["support_bounds_s"]) + rec = np.array([key[0] for key in keys]) + # Pairwise reference against every held-out interval on the same recording. + candidates = np.setdiff1d(eligible, held) + embargo = metadata["embargo_s"] + overlap = ((rec[candidates, None] == rec[held]) + & (bounds[candidates, 0, None] <= bounds[held, 1] + embargo) + & (bounds[candidates, 1, None] >= bounds[held, 0] - embargo)).any(axis=1) + np.testing.assert_array_equal(train, candidates[~overlap]) + np.testing.assert_array_equal(purged, candidates[overlap]) + + +def test_signal_recovery_isolation_ridge_parity_and_replay(tmp_path, monkeypatch): + data = fixture(29, signal=True) + result, x, y, keys, inputs, inner_scores = run(tmp_path / "signal", data, monkeypatch, + observe_normalizers=True) + saved = result["results"] + metadata = saved["metadata"]["temporal"] + assert [t["electrode_id"] for t in saved["metadata"]["target_metadata"]] == ["E9", "E1"] + assert saved["metadata"]["sample_ids"] == [ + (name, f"{name}:sample:{i}") for name, i in keys + ] + assert saved["final_refit"] is None + assert result["manifest"]["returned_weights_role"] == "descriptive_fold_mean" + for recording_meta in metadata["recordings"].values(): + assert recording_meta["delays"] == dict( + requested_s=REQUESTED, sample_offsets=list(OFFSETS), realized_s=[0., .25, .75], + ) + scores, kernel_errors, conditions, parity, replay_errors = [], [], [], [], [] + fit_index = score_index = 0 + assert any(len(f["purged_indices"]) for f in saved["folds"]) + assert any(len(s["purged_indices"]) for f in saved["folds"] for s in f["inner_splits"]) + for fold_id, fold in enumerate(saved["folds"]): + train, held = fold["train_indices"], fold["test_indices"] + assert fold["fold_id"] == fold_id and fold["model_role"] == "outer_fold" + check_purge(metadata, keys, np.arange(len(x)), train, held, fold["purged_indices"]) + selection = [] + actual_selection = [] + for split in fold["inner_splits"]: + a, b = split["train_indices"], split["validation_indices"] + check_purge(metadata, keys, train, a, b, split["purged_indices"]) + np.testing.assert_array_equal(inputs[fit_index][0], x[a]) + np.testing.assert_array_equal(inputs[fit_index][1], y[a]) + fit_index += 1 + selection.append([correlations(reference(x[a], y[a], x[b], alpha)[0], y[b]) + * ((len(b) - 1) / len(b)) for alpha in ALPHAS]) + actual_selection.append(inner_scores[score_index]) + score_index += 1 + np.testing.assert_allclose(actual_selection[-1], selection[-1], + rtol=0, atol=INNER_SCORE_ATOL) + np.testing.assert_array_equal(inputs[fit_index][0], x[train]) + np.testing.assert_array_equal(inputs[fit_index][1], y[train]) + fit_index += 1 + best = np.array(ALPHAS, dtype=np.float32)[np.mean(actual_selection, axis=0).argmax(axis=0)] + np.testing.assert_array_equal(fold["selected_alphas"], best) + expected, weights, penalties, condition = reference(x[train], y[train], x[held], best) + np.testing.assert_allclose(fold["effective_penalties"], penalties, rtol=3e-5, atol=1e-9) + np.testing.assert_allclose(fold["weights"], weights, rtol=0, atol=REFERENCE_ATOL) + np.testing.assert_allclose(fold["predictions"], expected, rtol=0, atol=REFERENCE_ATOL) + replay = nested_cv.NestedCVModel.predict_fold(fold, x[held]) + np.testing.assert_allclose(replay, fold["predictions"], atol=REPLAY_ATOL, rtol=0) + np.testing.assert_allclose(fold["targets"], y[held], atol=REPLAY_ATOL, rtol=0) + state = fold["transform"] + kernel = fold["weights"] * (state["target_stds"] + state["eps"]) / ( + state["feature_stds"].T + state["eps"] + ) + kernel_errors.extend(np.linalg.norm(kernel - KERNEL, axis=0) / np.linalg.norm(KERNEL, axis=0)) + scores.extend(correlations(replay, y[held])) + conditions.append(condition) + parity.append(np.max(abs(expected - fold["predictions"]))) + replay_errors.append(np.max(abs(replay - fold["predictions"]))) + assert fit_index == len(inputs) and score_index == len(inner_scores) + print(f"M5 signal scores={np.array(scores)} kernel_relative={np.array(kernel_errors)} " + f"conditions={conditions} parity_max={max(parity):.8g} replay_max={max(replay_errors):.8g}") + assert min(scores) >= SIGNAL_R_MIN + assert max(kernel_errors) <= KERNEL_RELATIVE_MAX + assert max(conditions) <= CONDITION_MAX + + # Intervene only on the first outer test set. Other folds may legitimately + # train on these rows. The first fold's fit and selection must be invariant. + first = saved["folds"][0] + changed = fixture(29, signal=True) + for i in first["test_indices"]: + name, source_index = keys[i] + rec = next(r for r in changed[0] if r["recording_id"] == name) + rec["brain_data"][source_index] = -3 * rec["brain_data"][source_index] + 20 + design, _, bounds = changed[3][(name, source_index)] + changed[3][(name, source_index)] = design, rec["brain_data"][source_index], bounds + changed_result, *_ = run(tmp_path / "outer_intervention", changed, monkeypatch) + after = changed_result["results"]["folds"][0] + for field in ("train_indices", "test_indices", "selected_alphas", "weights", "predictions"): + np.testing.assert_array_equal(after[field], first[field]) + for field in ("feature_means", "feature_stds", "target_means", "target_stds"): + np.testing.assert_array_equal(after["transform"][field], first["transform"][field]) + assert not np.allclose(after["targets"], first["targets"]) + + +def test_repeated_independent_autocorrelated_null(tmp_path, monkeypatch): + averages = [] + for seed in NULL_SEEDS: + result, _, y, *_ = run(tmp_path / str(seed), fixture(seed, signal=False), monkeypatch) + scores = [correlations(fold["predictions"], y[fold["test_indices"]]) + for fold in result["results"]["folds"]] + averages.append(float(np.mean(scores))) + print(f"M5 null seeds={list(NULL_SEEDS)} averages={np.round(averages, 6)} " + f"mean={np.mean(averages):.6f} mean_abs={np.mean(np.abs(averages)):.6f} " + f"sd={np.std(averages, ddof=1):.6f}") + assert abs(np.mean(averages)) <= NULL_BIAS_MAX + assert np.mean(np.abs(averages)) <= NULL_MEAN_ABS_MAX + assert max(abs(np.array(averages))) <= NULL_MAX_ABS diff --git a/tests/test_ecog_temporal.py b/tests/test_ecog_temporal.py new file mode 100644 index 0000000..81404e2 --- /dev/null +++ b/tests/test_ecog_temporal.py @@ -0,0 +1,313 @@ +"""M4 hand-calculated temporal fixtures and continuous trainer regression.""" +import numpy as np +import pytest + +from encoding import ecog_temporal as temporal +from encoding.models.nested_cv import NestedCVModel +from encoding.features.simple_features import WordRateFeatureExtractor +from encoding.trainer import AbstractTrainer +from test_ecog_assembly import generate, recording + + +def test_signed_delays_round_decimal_ties_away_from_zero(): + assert temporal.delay_offsets([-.375, 0, .125, .625], 4) == { + "requested_s": [-.375, 0., .125, .625], + "sample_offsets": [-2, 0, 1, 3], + "realized_s": [-.5, 0., .25, .75], + } + assert temporal.delay_offsets([.124999, -.125001], 4)["sample_offsets"] == [0, -1] + assert temporal.delay_offsets([.15, -.15], 10)["sample_offsets"] == [2, -2] + with pytest.raises(ValueError, match="Duplicate realized"): + temporal.delay_offsets([0, .1249], 4) + with pytest.raises(ValueError, match="explicit"): + temporal.delay_offsets([], 4) + + +@pytest.mark.parametrize(("method", "expected"), [ + ("word_sum", [1, 5, 0, 0, 4, 0, 0, 5]), + ("word_mean", [1, 2.5, 0, 0, 4, 0, 0, 5]), + ("word_last", [1, 3, 0, 0, 4, 0, 0, 5]), + ("words_per_bin", [1, 1, 0, 0, 1, 0, 0, 1]), + ("words_per_second", [4, 4, 0, 0, 4, 0, 0, 4]), +]) +def test_word_alignment_distinguishes_empty_and_missing_bins(method, expected): + story = generate(recording()).story_data["run-A"] + values, valid, _ = temporal.align_features( + story, np.arange(1., 6.)[:, None], + dict(method=method, support_s=[0, 0], missing_intervals_s=[[10.5, 10.75]]), + ) + np.testing.assert_array_equal(values[:, 0], expected) + np.testing.assert_array_equal(np.flatnonzero(~valid), [2]) + + +def test_speech_linear_timestamp_coverage_and_support(): + story = generate(recording()).story_data["run-A"] + spec = dict(method="speech_linear", support_s=[.25, 0], frame_origin_s=10, + max_gap_s=.5) + frames = np.array([[2.], [6.], [10.]]) + values, valid, bounds = temporal.align_features( + story, (frames, np.array([.25, .75, 1.5])), spec, + ) + np.testing.assert_array_equal(np.flatnonzero(valid), [1, 2, 3, 6]) + assert values[2, 0] == 4 + np.testing.assert_array_equal(bounds[2], [10., 10.75]) + _, valid, _ = temporal.align_features( + story, (frames, np.array([.25, .75, 1.5])), + dict(spec, missing_intervals_s=[[10., 10.125]]), + ) + np.testing.assert_array_equal(np.flatnonzero(valid), [3, 6]) + frames[1, 0] = np.nan + _, valid, _ = temporal.align_features(story, (frames, np.array([.25, .75, 1.5])), spec) + np.testing.assert_array_equal(np.flatnonzero(valid), [1, 6]) + with pytest.raises(ValueError, match="strictly increasing"): + temporal.align_features(story, (frames, np.array([.25, .25, 1.5])), spec) + + +def test_expansion_runs_on_original_grid_before_exclusion(): + rec = recording() + rec["valid_samples"][5] = False + story = generate(rec).story_data["run-A"] + values = np.arange(8., dtype=np.float32)[:, None] + good = np.ones(8, dtype=bool) + good[3] = False + bounds = np.column_stack((story.tr_times, story.tr_times)) + delays = temporal.delay_offsets([-.25, 0, .25], 4) + design, _, rows, _, reasons = temporal.expand_recording( + story, [(values, good, bounds)], delays, [0, 0], + ) + np.testing.assert_array_equal(rows, [1, 6]) + np.testing.assert_array_equal(design, [[2, 1, 0], [7, 6, 5]]) + assert design.dtype == np.float32 + assert reasons[0] and reasons[7] and reasons[5] + _, _, rows, _, _ = temporal.expand_recording(story, [(values, good, bounds)], delays, [.25, 0]) + np.testing.assert_array_equal(rows, [1]) + + +def long_recording(name, origin): + rec = recording(name, origin) + n = 96 + rng = np.random.default_rng(54) + rec["brain_data"] = rng.normal(size=(n, 2)).astype(np.float32) + rec["neural_times"] = origin + np.arange(n) / 4 + rec["valid_samples"] = np.ones(n, dtype=bool) + rec["valid_samples"][15:19] = False + rec["sample_ids"] = [f"{name}-original-{i}" for i in range(n)] + rec["stimulus_times"] = origin + np.arange(0, n, 2) / 4 + rec["words"] = rec["stimuli"] = ["event"] * (n // 2) + rec["word_ids"] = [f"w{i}" for i in range(n // 2)] + rec["provenance"]["preprocessing"]["support_s"] = [.25, 0] + return rec + + +def trainer_fixture(tmp_path, budget=10_000_000): + assembly = generate(long_recording("A", 10), long_recording("B", 100)) + return AbstractTrainer( + assembly, [WordRateFeatureExtractor({})], None, NestedCVModel("ridge"), None, {}, + logger_backend="tensorboard", results_dir=str(tmp_path), + ecog_temporal_config=dict( + delays_s=[-.25, 0, .25], retrospective=True, protocol="blocked", embargo_s=.25, + memory_budget_bytes=budget, + feature_specs=[dict(method="words_per_bin", support_s=[0, 0], + missing_intervals_s={"A": [[14., 14.25]], "B": []})], + ), + ) + + +def assert_disjoint(temporal_metadata, train, test): + rows = temporal_metadata["rows"] + bounds = np.array(temporal_metadata["support_bounds_s"]) + embargo = temporal_metadata["embargo_s"] + for i in train: + for j in test: + if rows[i]["recording_id"] == rows[j]["recording_id"]: + assert bounds[i, 1] < bounds[j, 0] - embargo or bounds[i, 0] > bounds[j, 1] + embargo + + +def test_saved_nested_splits_use_original_coordinates_and_support(tmp_path): + trainer = trainer_fixture(tmp_path) + trainer.train(alphas=[1.], use_gpu=False, n_outer_folds=3, n_inner_folds=2) + result = trainer.model_saver.load_encoding_result(trainer.last_run_dir_)["results"] + metadata = result["metadata"]["temporal"] + assert result["metadata"]["target_space"] == "ecog" + assert metadata["validity_applied"] + assert metadata["recordings"]["A"]["delays"]["sample_offsets"] == [-1, 0, 1] + assert metadata["recordings"]["B"]["delays"]["realized_s"] == [-.25, 0, .25] + assert metadata["rows"][0]["source_index"] == 1 + for row in metadata["rows"]: + origin = {"A": 10, "B": 100}[row["recording_id"]] + assert row["time_s"] == origin + row["source_index"] / 4 + assert row["source_index"] not in {0, 15, 16, 17, 18, 19, 95} + assert any(row["sample_id"] == "A-original-15" for row in metadata["exclusions"]) + for fold in result["folds"]: + assert_disjoint(metadata, fold["train_indices"], fold["test_indices"]) + assert set(fold["purged_indices"]) == (set(range(len(metadata["rows"]))) + - set(fold["train_indices"]) - set(fold["test_indices"])) + for split in fold["inner_splits"]: + assert set(split["train_indices"]) <= set(fold["train_indices"]) + assert set(split["validation_indices"]) <= set(fold["train_indices"]) + assert_disjoint(metadata, split["train_indices"], split["validation_indices"]) + assert set(split["purged_indices"]) == (set(fold["train_indices"]) + - set(split["train_indices"]) - set(split["validation_indices"])) + + +def test_recording_holdout_and_impossible_purge(): + ids = np.repeat(["a", "b", "c", "d"], 12) + bounds = np.column_stack((np.arange(48), np.arange(48))) + for train, test, nested in temporal.temporal_splits(ids, bounds, 2, 2, "recording", 0): + assert not set(ids[train]) & set(ids[test]) + for a, b in nested: + assert not set(ids[train[a]]) & set(ids[train[b]]) + with pytest.raises(ValueError, match="Temporal exclusion"): + temporal.temporal_splits(np.repeat("a", 48), bounds, 3, 2, "blocked", 100) + + +def test_budget_rejects_before_expansion_and_solver(tmp_path, monkeypatch): + trainer = trainer_fixture(tmp_path, budget=1) + monkeypatch.setattr(temporal, "expand_recording", + lambda *args: pytest.fail("expanded before memory check")) + with pytest.raises(MemoryError, match="against budget 1"): + trainer.train(n_outer_folds=3, n_inner_folds=2, use_gpu=False) + + import encoding.models.nested_cv as model_module + monkeypatch.setattr(model_module.torch, "tensor", + lambda *args, **kwargs: pytest.fail("allocated solver input before check")) + data = np.arange(20., dtype=np.float32)[:, None] + with pytest.raises(MemoryError, match="against budget 1"): + trainer.model.fit_predict( + data, data, use_gpu=False, temporal_cv=dict( + recordings=["a"] * 20, bounds=np.repeat(data, 2, axis=1), + protocol="blocked", embargo_s=0, memory_budget_bytes=1, + ), + ) + + +def test_unknown_support_is_rejected(tmp_path): + trainer = trainer_fixture(tmp_path) + trainer.assembly.story_data["A"].provenance["preprocessing"]["support_s"] = None + with pytest.raises(ValueError, match="requires known"): + trainer.train(use_gpu=False) + + +def test_negative_delays_require_retrospective_declaration(tmp_path): + trainer = trainer_fixture(tmp_path) + del trainer.ecog_temporal_config["retrospective"] + with pytest.raises(ValueError, match="retrospective=True"): + trainer.train(use_gpu=False) + + +def test_legacy_fmri_trainer_bypasses_ecog_preflight(tmp_path, monkeypatch): + from test_results_saving import make_trainer + + monkeypatch.setattr(temporal, "prepare_ecog", + lambda *args: pytest.fail("fMRI entered ECoG preparation")) + trainer = make_trainer(tmp_path) + metrics = trainer.train(alphas=[1.], n_inner_folds=2, use_gpu=False) + assert metrics["n_valid_targets"] == 2 + assert trainer.model.results_["mode"] == "train_test" + + +def test_static_copy_dependency_survives_delays_and_purges(tmp_path): + from encoding.features.embeddings import StaticEmbeddingFeatureExtractor + + vectors = tmp_path / "tiny.w2v.txt" + vectors.write_text("2 1\nknown 7\nother 2\n") + extractor = StaticEmbeddingFeatureExtractor(dict(vector_path=str(vectors), use_tqdm=False)) + rec = long_recording("A", 10) + rec["words"] = ["known", "other"] * 24 + rec["words"][8:11] = ["known", "oov", "oov"] + rec["words"][19:25] = ["other"] + ["oov"] * 5 + trainer = trainer_fixture(tmp_path) + trainer.assembly = generate(rec) + trainer.stories_to_process = ["A"] + trainer.feature_extractors = [extractor] + trainer.ecog_temporal_config.update( + delays_s=[.25], retrospective=False, embargo_s=0, + feature_specs=[dict(method="word_sum", support_s=[0, 0], + missing_intervals_s=[[14., 14.25]])], + ) + trainer.train(alphas=[1.], use_gpu=False, n_outer_folds=3, n_inner_folds=2) + result = trainer.model_saver.load_encoding_result(trainer.last_run_dir_)["results"] + meta = result["metadata"]["temporal"] + retained = {row["source_index"]: bounds for row, bounds in + zip(meta["rows"], meta["support_bounds_s"])} + # The event at 14 s supplies the copied vectors at 14.5 and 15 s. + assert {17, 19, 21}.isdisjoint(retained) + # The other copied span starts at event 19, grid row 38, then reaches row 49. + assert retained[49][0] == 19.5 + for fold in result["folds"]: + assert_disjoint(meta, fold["train_indices"], fold["test_indices"]) + for split in fold["inner_splits"]: + assert_disjoint(meta, split["train_indices"], split["validation_indices"]) + assert any(len(fold["purged_indices"]) for fold in result["folds"]) + assert any(len(split["purged_indices"]) for fold in result["folds"] for split in fold["inner_splits"]) + + +def test_diagnostic_policy_and_provenance_round_trip(tmp_path, monkeypatch, caplog): + import encoding.models.nested_cv as model_module + + a, b = long_recording("A", 10), long_recording("B", 100) + a["stimulus_clock"] = "transcript" + a["stimulus_times"] -= 10 + a["synchronization"] = dict(source_clock="transcript", target_clock="recording", scale=1, + offset_s=10, provenance={"source": "fixture"}) + a["unknown_samples"] = np.zeros(96, dtype=bool) + a["unknown_samples"][[15, 16]] = True + a["brain_data"][16, 0] = np.nan + a["provenance"]["preprocessing"] = {"support_status": "unknown"} + trainer = trainer_fixture(tmp_path) + trainer.assembly = generate(a, b) + with pytest.raises(ValueError, match="requires known"): + trainer.train(alphas=[1.], use_gpu=False) + + trainer.ecog_temporal_config.update(protocol="diagnostic_in_sample", embargo_s=0, delays_s=[0]) + with pytest.raises(ValueError, match="fixed"): + trainer.train(alphas=[1., 2.], use_gpu=False) + monkeypatch.setattr(model_module, "_find_best_alphas", + lambda *args, **kwargs: pytest.fail("diagnostic used selection")) + monkeypatch.setattr(temporal, "temporal_splits", + lambda *args, **kwargs: pytest.fail("diagnostic used CV")) + monkeypatch.setattr(trainer.brain_plotter, "log_descriptive_correlations", + lambda *args: pytest.fail("diagnostic plotted correlation")) + with caplog.at_level("INFO"): + metrics = trainer.train(alphas=[1.], use_gpu=False, normalize_features=True) + assert "Inference not assessed" in caplog.text + assert trainer.reporting_error_ is None + loaded = trainer.model_saver.load_encoding_result(trainer.last_run_dir_) + result = loaded["results"] + assert result["mode"] == "diagnostic_in_sample" and result["final_refit"] is None + assert loaded["manifest"]["replay_available"] + assert set(metrics) == {"evaluation", "inference_status", "n_fit_samples"} + assert loaded["metrics"]["inference_status"] == result["inference_status"] == "not_assessed" + fold, = result["folds"] + assert fold["model_role"] == "in_sample_diagnostic" + assert not fold["inner_splits"] and "test_indices" not in fold + meta = result["metadata"]["temporal"] + assert meta["validity_policy"] == "allow_finite_unknown_in_sample" + rec = meta["recordings"]["A"] + assert rec["signal_units"] == a["signal_units"] and rec["grid_count"] == 96 + assert rec["sampling_rate_hz"] == 4 and rec["synchronization"] == a["synchronization"] + assert rec["preprocessing_support_s"] is None + assert any(row["sample_id"] == "A-original-15" and row["validity"] == "unknown" for row in meta["rows"]) + excluded = {row["sample_id"]: row for row in meta["exclusions"]} + assert excluded["A-original-16"]["reason"] == "nonfinite neural row" + assert excluded["A-original-17"]["validity"] == "known_invalid" + design, _, _ = temporal.prepare_ecog(trainer, trainer.ecog_temporal_config, {"alphas": [1.]}) + np.testing.assert_array_equal(trainer.model.predict_fold(fold, design["X"]), fold["predictions"]) + + +def test_ecog_descriptive_reporting_has_no_inference(tmp_path, monkeypatch, caplog): + import encoding.models.nested_cv as model_module + + trainer = trainer_fixture(tmp_path) + monkeypatch.setattr(model_module, "pearsonr", lambda *args: pytest.fail("computed Pearson p-value")) + monkeypatch.setattr(model_module, "fdrcorrection", lambda *args, **kwargs: pytest.fail("computed FDR")) + monkeypatch.setattr(trainer.brain_plotter, "log_plots", lambda *args, **kwargs: pytest.fail("significance plot")) + seen = [] + monkeypatch.setattr(trainer.brain_plotter, "log_descriptive_correlations", seen.append) + with caplog.at_level("INFO"): + metrics = trainer.train(alphas=[1.], use_gpu=False, n_outer_folds=3, n_inner_folds=2) + assert trainer.reporting_error_ is None + assert metrics["inference_status"] == "not_assessed" and "significant_mask" not in metrics + assert "p_values" not in metrics + assert "inference not assessed" in caplog.text and "Significant voxels" not in caplog.text + np.testing.assert_array_equal(seen[0], metrics["correlations"]) diff --git a/tests/test_results_saving.py b/tests/test_results_saving.py new file mode 100644 index 0000000..8ef77a7 --- /dev/null +++ b/tests/test_results_saving.py @@ -0,0 +1,299 @@ +"""M2: target-generic reporting and reproducible, identified fitted results.""" +import json +import pickle + +import numpy as np +import pytest + +from encoding.models.nested_cv import NestedCVModel +from encoding.plotting.plotting_utils import BrainPlotter +from encoding.trainer import AbstractTrainer +from encoding.utils import ModelSaver + + +FIT = dict(alphas=[1., 10.], use_gpu=False, folding_type='kfold', + n_inner_folds=2, n_outer_folds=3) +TARGETS = [{'electrode_id': 'E9'}, {'electrode_id': 'E1'}, {'electrode_id': 'dead'}] + + +def fixture_data(): + rng = np.random.default_rng(51) + X = rng.normal(size=(90, 4)).astype(np.float32) + Y = X @ rng.normal(size=(4, 3)).astype(np.float32) + 7 + Y[:, 2] = 2.5 + return X, Y + + +def make_trainer(tmp_path): + from types import SimpleNamespace + X, Y = fixture_data() + assembly = SimpleNamespace(stories=['first', 'heldout'], + get_brain_data=lambda: [Y[:60], Y[60:]]) + trainer = AbstractTrainer( + assembly, [], None, NestedCVModel('ridge'), [0], {}, + use_train_test_split=True, logger_backend='tensorboard', + results_dir=str(tmp_path), result_metadata={ + 'target_metadata': TARGETS, + 'provenance': {'signal': 'synthetic', 'units': 'fixture units'}, + 'temporal_parameters': {'requested_delays_s': [0.], 'sample_offsets': [0]}, + }, + ) + trainer.extract_and_downsample_features = lambda: {'first': X[:60], 'heldout': X[60:]} + # conftest replaces trainer's plotter globally; explicitly exercise the real + # plotting implementation. Its fsaverage fetch is guarded against downloads. + trainer.brain_plotter = BrainPlotter(trainer.experiment_logger) + return trainer + + +def test_small_target_count_real_reporting_and_default_save(tmp_path): + trainer = make_trainer(tmp_path) + metrics = trainer.train(**FIT) + assert metrics['n_valid_targets'] == 2 + assert trainer.reporting_error_ is None + loaded = trainer.model_saver.load_encoding_result(trainer.last_run_dir_) + assert loaded['weights'].shape == (4, 3) + assert loaded['results']['metadata']['target_metadata'] == TARGETS + assert loaded['results']['metadata']['provenance']['signal'] == 'synthetic' + assert loaded['results']['metadata']['temporal_parameters']['sample_offsets'] == [0] + assert loaded['results']['metadata']['sample_ids'][0] == 'first:0' + assert loaded['results']['metadata']['test_sample_ids'][-1] == 'heldout:29' + assert loaded['results']['folds'][0]['invalid_target_mask'].tolist() == [False, False, True] + assert loaded['results']['mode'] == 'train_test' + assert loaded['results']['final_refit'] == {'fold_id': 0, 'scope': 'provided_training_set_only'} + assert loaded['manifest']['returned_weights_role'] == 'training_fit' + + +def test_optional_plotting_failure_happens_after_save(tmp_path, monkeypatch, caplog): + trainer = make_trainer(tmp_path) + + def broken_plot(*args, **kwargs): + # The result must already be readable when optional plotting starts. + assert trainer.model_saver.load_encoding_result(trainer.last_run_dir_)['results'] + raise RuntimeError('optional render failure') + + monkeypatch.setattr(trainer.brain_plotter, 'log_plots', broken_plot) + metrics = trainer.train(**FIT) + assert np.isfinite(metrics['median_score']) + assert 'optional render failure' in trainer.reporting_error_ + assert 'Optional result reporting failed' in caplog.text + assert (trainer.last_run_dir_ / 'results.pkl').is_file() + + +@pytest.mark.parametrize('stage', ['fit', 'save']) +def test_core_failures_propagate(tmp_path, monkeypatch, stage): + trainer = make_trainer(tmp_path) + + def fail(*args, **kwargs): + raise OSError(f'{stage} failed') + + if stage == 'fit': + monkeypatch.setattr(trainer.model, 'fit_predict', fail) + else: + monkeypatch.setattr(trainer.model_saver, 'save_encoding_model', fail) + with pytest.raises(OSError, match=f'{stage} failed'): + trainer.train(**FIT) + assert not list(tmp_path.glob('run_*')) + + +@pytest.mark.parametrize('mode', ['train_test', 'nested_cv']) +@pytest.mark.parametrize('normalize', [False, True]) +def test_saved_folds_replay_predictions_and_retain_identity(tmp_path, mode, normalize): + X, Y = fixture_data() + # Scale/offset magnitudes make normalization state indispensable for replay. + X = X * 5 + np.arange(4) * 3 + Y[:, :2] = Y[:, :2] * [3, 6] + [20, -40] + metadata = {'target_metadata': TARGETS, + 'sample_ids': [f'recording:gap:{i*2}' for i in range(60 if mode == 'train_test' else 90)], + 'provenance': {'prior_normalization': 'none', 'clock': 'fixture'}, + 'sample_time_s': np.arange(60 if mode == 'train_test' else 90) * 2.} + kwargs = {} + if mode == 'train_test': + kwargs = dict(X_test=X[60:], y_test=Y[60:]) + metadata['test_sample_ids'] = [f'test:{i}' for i in range(30)] + model = NestedCVModel('ridge') + metrics, weights, alphas = model.fit_predict( + X[:60] if mode == 'train_test' else X, + Y[:60] if mode == 'train_test' else Y, + result_metadata=metadata, normalize_features=normalize, + normalize_targets=normalize, **kwargs, **FIT, + ) + saver = ModelSaver(tmp_path) + run = saver.save_encoding_model(weights, alphas, {'alpha_grid': np.array([1., 10.])}, + metrics, results=model.results_) + loaded = saver.load_encoding_result(run) + restored = loaded['results'] + assert restored['metadata']['target_metadata'] == TARGETS + assert restored['metadata']['sample_ids'] == metadata['sample_ids'] + np.testing.assert_array_equal(restored['metadata']['sample_time_s'], metadata['sample_time_s']) + assert restored['configuration']['normalpha'] is True + assert len(restored['folds']) == (1 if mode == 'train_test' else 3) + for i, fold in enumerate(restored['folds']): + assert fold['fold_id'] == i + indices = fold['test_indices'] + fixed_design = X[60:] if mode == 'train_test' else X[indices] + prediction = model.predict_fold(fold, fixed_design) + np.testing.assert_allclose(prediction, fold['predictions'], rtol=2e-5, atol=2e-5, equal_nan=True) + np.testing.assert_allclose(model.predict_fold(fold, fixed_design, original_units=False), + fold['predictions_scaled'], rtol=2e-5, atol=2e-5, equal_nan=True) + np.testing.assert_allclose(fold['targets'][:, :2], + (Y[60:] if mode == 'train_test' else Y[indices])[:, :2], + rtol=2e-5, atol=2e-5) + assert fold['transform']['normalize_features'] is normalize + assert fold['transform']['normalize_targets'] is normalize + for inner in fold['inner_splits']: + assert set(inner['train_indices']) <= set(fold['train_indices']) + assert set(inner['validation_indices']) <= set(fold['train_indices']) + if mode == 'nested_cv': + assert not set(fold['train_indices']) & set(indices) + assert fold['model_role'] == 'outer_fold' + if mode == 'nested_cv': + assert restored['final_refit'] is None + assert restored['returned_weights_role'] == 'descriptive_fold_mean' + assert restored['returned_alphas_role'] == 'descriptive_fold_mean' + assert loaded['manifest']['returned_alphas_role'] == 'descriptive_fold_mean' + np.testing.assert_allclose(weights, np.mean([f['weights'] for f in restored['folds']], axis=0), equal_nan=True) + assert not np.allclose(restored['folds'][0]['weights'][:, :2], restored['folds'][1]['weights'][:, :2]) + # Existing four-value loading remains usable, including default weight saving. + w, a, config, m = saver.load_encoding_model(run) + np.testing.assert_array_equal(w, weights) + np.testing.assert_array_equal(a, alphas) + assert config['alpha_grid'] == [1., 10.] + assert m['invalid_target_mask'] == [False, False, True] + + +def test_legacy_preparation_stats_and_trim_coordinates_are_saved(tmp_path): + trainer = make_trainer(tmp_path) + trainer.trimming_config = dict(train_features_start=2, train_targets_start=2, + test_features_start=3, test_targets_start=3) + trainer.train(**FIT) + result = trainer.model_saver.load_encoding_result(trainer.last_run_dir_)['results'] + prepared = result['metadata']['preparation'] + assert prepared['partitions']['train']['features'][0]['source_index'] == 2 + assert prepared['partitions']['test']['targets'][0]['source_index'] == 3 + stats = prepared['upstream_transforms'] + X, _ = fixture_data() + first = next(s for s in stats if s['domain'] == 'features' and s['partition'] == 'train') + np.testing.assert_allclose(first['mean'], X[2:60].mean(axis=0)) + fold = result['folds'][0] + test = next(s for s in stats if s['domain'] == 'features' and s['partition'] == 'test') + fixed = (X[63:] - test['mean']) / test['std'] + np.testing.assert_allclose(NestedCVModel.predict_fold(fold, fixed), fold['predictions'], rtol=2e-5, atol=2e-5, equal_nan=True) + + +def test_versioned_omission_and_legacy_incomplete_load(tmp_path, caplog): + saver = ModelSaver(tmp_path) + run = saver.save_encoding_model(np.ones((2, 3)), np.ones(3), {}, {'best_alphas': [1, 1, 1]}, save_weights=False) + loaded = saver.load_encoding_result(run) + assert loaded['weights'] is None + assert loaded['manifest']['replay_available'] is False + assert loaded['best_alphas'].tolist() == [1, 1, 1] + legacy = tmp_path / 'legacy'; legacy.mkdir() + (legacy / 'hyperparams.json').write_text('{}') + with open(legacy / 'metrics.pkl', 'wb') as f: + pickle.dump({'best_alphas': [2., 3.]}, f) + loaded = saver.load_encoding_result(legacy) + assert loaded['format_version'] == 1 + assert loaded['results'] is None and loaded['weights'] is None + assert loaded['best_alphas'].tolist() == [2., 3.] + assert 'Legacy run' in caplog.text + + +def test_repeated_saves_do_not_overwrite_and_failure_is_not_published(tmp_path, monkeypatch): + saver = ModelSaver(tmp_path) + one = saver.save_encoding_model(np.ones((2, 3)), np.ones(3), {}, {}) + two = saver.save_encoding_model(np.zeros((2, 3)), np.ones(3), {}, {}) + assert one != two + np.testing.assert_array_equal(saver.load_encoding_model(one)[0], np.ones((2, 3))) + def broken_dump(*args, **kwargs): + raise OSError('storage failure') + monkeypatch.setattr(pickle, 'dump', broken_dump) + with pytest.raises(OSError, match='storage failure'): + saver.save_encoding_model(np.ones((2, 3)), np.ones(3), {}, {}) + assert len(list(tmp_path.glob('run_*'))) == 2 + assert not list(tmp_path.glob('.saving_*')) + + +def test_unknown_format_and_missing_required_v2_file_raise(tmp_path): + saver = ModelSaver(tmp_path) + run = saver.save_encoding_model(np.ones((2, 3)), np.ones(3), {}, {}) + manifest = json.loads((run / 'manifest.json').read_text()) + manifest['format_version'] = 999 + (run / 'manifest.json').write_text(json.dumps(manifest)) + with pytest.raises(ValueError, match='Unsupported'): + saver.load_encoding_result(run) + manifest['format_version'] = 2 + (run / 'manifest.json').write_text(json.dumps(manifest)) + (run / 'weights.npy').unlink() + with pytest.raises(FileNotFoundError): + saver.load_encoding_result(run) + + +def test_existing_unified_entrypoint_saves_before_optional_reporting(tmp_path, caplog): + import logging + from unified import UnifiedTrainer + + X, Y = fixture_data() + trainer = object.__new__(UnifiedTrainer) + trainer.prepare_data = lambda: {'X': X, 'Y': Y} + trainer.model = NestedCVModel('ridge') + trainer.logger = logging.getLogger('test_unified_m2') + trainer.model_saver = ModelSaver(tmp_path) + trainer.config = dict(folding_type='kfold', n_outer_folds=3, n_inner_folds=2, + chunk_length=20, singcutoff=1e-10, use_gpu=False, + normalize_features=True, normalize_targets=True, + result_metadata={'target_metadata': TARGETS}) + + def broken(metrics): + assert trainer.model_saver.load_encoding_result(trainer.last_run_dir_)['results'] + raise RuntimeError('optional unified reporting failed') + + trainer.log_metrics = broken + trainer.train() + assert 'optional unified reporting failed' in trainer.reporting_error_ + assert 'Optional result reporting failed' in caplog.text + loaded = trainer.model_saver.load_encoding_result(trainer.last_run_dir_) + assert loaded['results']['final_refit'] is None + assert loaded['results']['metadata']['target_metadata'] == TARGETS + + +@pytest.mark.parametrize('count', [1, 20484]) +def test_generic_histograms_allow_single_target_and_explicit_surface_opt_out(count): + from conftest import _NullLogger + import matplotlib.pyplot as plt + + logger = _NullLogger() + plotter = BrainPlotter(logger) + scores = np.linspace(0.1, 0.9, count) + plotter.log_plots(scores, np.zeros(count, dtype=bool), surface=False) + assert not plt.get_fignums() + + +def test_figure_is_closed_when_optional_image_logger_fails(): + from conftest import _NullLogger + import matplotlib.pyplot as plt + + class BrokenImageLogger(_NullLogger): + def log_image(self, *args, **kwargs): + raise RuntimeError('image logger failed') + + with pytest.raises(RuntimeError, match='image logger failed'): + BrainPlotter(BrokenImageLogger()).log_plots(np.array([.1, .3]), np.array([False, True])) + assert not plt.get_fignums() + + +def test_explicit_weight_omission_keeps_predictions_without_mutating_live_model(tmp_path): + X, Y = fixture_data() + model = NestedCVModel('ridge') + metrics, weights, alphas = model.fit_predict(X, Y, **FIT) + saver = ModelSaver(tmp_path) + run = saver.save_encoding_model(weights, alphas, {}, metrics, + results=model.results_, save_weights=False) + restored = saver.load_encoding_result(run) + assert restored['manifest']['replay_available'] is False + assert restored['weights'] is None + fold = restored['results']['folds'][0] + assert 'weights' not in fold + assert 'weights' in model.results_['folds'][0] + np.testing.assert_array_equal(fold['predictions'], model.results_['folds'][0]['predictions']) + with pytest.raises(ValueError, match='omitted'): + NestedCVModel.predict_fold(fold, X[fold['test_indices']]) diff --git a/tests/test_shared_fixes.py b/tests/test_shared_fixes.py new file mode 100644 index 0000000..25c07e8 --- /dev/null +++ b/tests/test_shared_fixes.py @@ -0,0 +1,315 @@ +"""Acceptance tests A1-A5 for the shared-correctness milestone (M1). + +A1 fold arguments and fallbacks, A2 fold-local normalization, A3 LM cache identity, +A4 no silent truncation of feature families, A5 invalid targets excluded from scores. +""" + +import pickle + +import numpy as np +import pytest + +import encoding.models.nested_cv as nested_cv +from encoding.features.factory import FeatureExtractorFactory +from encoding.features.language_model import LanguageModelFeatureExtractor +from encoding.models.folding import create_folds +from encoding.models.nested_cv import NestedCVModel +from encoding.trainer import AbstractTrainer +from encoding.utils import ActivationCache + +FIT = dict(alphas=[1.0, 100.0], use_gpu=False) + + +def _data(n=120, f=3, t=4, seed=0): + rng = np.random.default_rng(seed) + X = rng.normal(size=(n, f)) + Y = X @ rng.normal(size=(f, t)) + rng.normal(size=(n, t)) + return X, Y + + +# --- A1: fold arguments and fallbacks --------------------------------------- + + +def test_trimmed_chunks_use_trim_size_and_accept_groups(): + groups = np.repeat(np.arange(5), 20) + splits = create_folds(100, "chunked_trimmed", 5, chunk_length=20, trim_size=3, groups=groups) + for train, test in splits: + assert len(test) == 20 - 2 * 3 + assert not set(train) & set(test) + + +def test_array_in_trim_size_slot_is_rejected(): + groups = np.repeat(np.arange(5), 20) + with pytest.raises(TypeError, match="groups by keyword"): + create_folds(100, "chunked_trimmed", 5, 20, groups) + + +@pytest.mark.parametrize( + "fold_type, kwargs", + [ + ("chunked", dict(chunk_length=20)), + ("chunked_contiguous", dict(chunk_length=20)), + ("chunked_trimmed", dict(chunk_length=20, trim_size=2)), + ("kfold_trimmed", dict(trim_size=5)), + ], +) +def test_too_few_samples_raise_instead_of_falling_back(fold_type, kwargs): + with pytest.raises(ValueError): + create_folds(30, fold_type, 5, **kwargs) + + +def test_trimming_that_empties_test_sets_raises(): + with pytest.raises(ValueError, match="0 test"): + create_folds(100, "chunked_trimmed", 5, chunk_length=10, trim_size=5) + + +def test_fit_predict_passes_fold_arguments_by_keyword(monkeypatch): + calls = [] + + def spy(*args, **kwargs): + calls.append((args, kwargs)) + return create_folds(*args, **kwargs) + + monkeypatch.setattr(nested_cv, "create_folds", spy) + X, Y = _data() + groups = np.repeat(np.arange(6), 20) + NestedCVModel("ridge").fit_predict( + X, Y, X_test=X[:30], y_test=Y[:30], groups=groups, + folding_type="chunked_trimmed", n_inner_folds=3, chunk_length=10, trim_size=2, **FIT, + ) + (args, kwargs), = calls + assert len(args) == 3 + assert kwargs["trim_size"] == 2 and kwargs["chunk_length"] == 10 + assert kwargs["groups"] is groups + + +# --- A2: fold-local normalization --------------------------------------------- + + +def test_normalizers_are_fit_on_training_rows_only(monkeypatch): + fitted_ids = [] + + class RecordingNormalizer(nested_cv.DataNormalizer): + def fit(self, X_train, y_train): + fitted_ids.append(frozenset(X_train[:, 0].cpu().numpy().round().astype(int))) + return super().fit(X_train, y_train) + + monkeypatch.setattr(nested_cv, "DataNormalizer", RecordingNormalizer) + X, Y = _data() + X[:, 0] = np.arange(len(X)) # row IDs, so each fit's rows can be identified + + NestedCVModel("ridge").fit_predict( + X, Y, folding_type="kfold", n_outer_folds=3, n_inner_folds=2, + normalize_features=True, normalize_targets=True, **FIT, + ) + + expected = [] + for outer_train, _ in create_folds(len(X), "kfold", 3): + outer_train = np.asarray(outer_train) + for inner_train, _ in create_folds(len(outer_train), "kfold", 2): + expected.append(frozenset(outer_train[inner_train])) + expected.append(frozenset(outer_train)) + assert fitted_ids == expected + + +def test_no_normalizer_without_normalization_flags(monkeypatch): + def forbidden(*a, **k): + raise AssertionError("DataNormalizer constructed with normalization off") + + monkeypatch.setattr(nested_cv, "DataNormalizer", forbidden) + X, Y = _data() + NestedCVModel("ridge").fit_predict(X, Y, folding_type="kfold", n_outer_folds=3, n_inner_folds=2, **FIT) + + +# --- A3: LM cache identity ---------------------------------------------------- + + +class _Assembly: + def __init__(self, stimuli): + self.stimuli = stimuli + + def get_stimuli(self): + return [self.stimuli] + + +def _lm_extractor(tmp_path, hook_type="hook_resid_pre"): + ext = object.__new__(LanguageModelFeatureExtractor) # skip model download + ext.model_name, ext.hook_type = "fake-lm", hook_type + ext.last_token, ext.context_type = True, "fullcontext" + ext.activation_cache = ActivationCache(cache_dir=str(tmp_path)) + ext.n_computed = 0 + + def extract_all_layers(texts): + ext.n_computed += 1 + return {0: np.full((len(texts), 2), float(ext.n_computed))} + + ext.extract_all_layers = extract_all_layers + return ext + + +def _extract(ext, stimuli): + return FeatureExtractorFactory.extract_features_with_caching( + ext, _Assembly(stimuli), "story", 0, layer_idx=0, lookback=8, dataset_type="x" + ) + + +def test_cache_key_covers_hook_and_stimuli(tmp_path): + ext = _lm_extractor(tmp_path) + _extract(ext, ["a", "a b"]) + _extract(ext, ["a", "a b"]) + assert ext.n_computed == 1 # cache hit + + ext.hook_type = "hook_resid_post" + _extract(ext, ["a", "a b"]) + assert ext.n_computed == 2 # hook changes the identity + + _extract(ext, ["a", "a c"]) + assert ext.n_computed == 3 # stimulus content changes the identity + + +def test_cache_metadata_mismatch_raises(tmp_path): + ext = _lm_extractor(tmp_path) + _extract(ext, ["a", "a b"]) + (path,) = tmp_path.glob("*.pkl") + with open(path, "rb") as f: + data = pickle.load(f) + data["metadata"]["hook_type"] = "hook_resid_post" + with open(path, "wb") as f: + pickle.dump(data, f) + with pytest.raises(ValueError, match="do not match"): + _extract(ext, ["a", "a b"]) + + +# --- A4: feature families must align ------------------------------------------ + + +def test_feature_families_with_different_row_counts_raise(): + trainer = object.__new__(AbstractTrainer) + trainer.assembly = type("A", (), {"stories": ["s"]})() + trainer.stories_to_process = ["s"] + trainer.feature_extractors = ["short", "long"] + rows = {"short": np.zeros((9, 2)), "long": np.zeros((10, 3))} + trainer._extract_single_features = lambda ext, story, idx: rows[ext] + trainer._should_downsample = lambda ext: False + + with pytest.raises(ValueError, match="refusing to truncate"): + trainer.extract_and_downsample_features() + + +# --- A5: invalid targets are excluded, not scored as r=0 ---------------------- + + +def test_constant_and_nonfinite_targets_are_nan(): + rng = np.random.default_rng(0) + y_true = rng.normal(size=(50, 4)) + y_true[:, 1] = 3.0 + y_true[5, 2] = np.nan + corr, p = nested_cv._calculate_correlations_pvalues(y_true, rng.normal(size=(50, 4))) + assert np.isnan(corr[1]) and np.isnan(p[1]) + assert np.isnan(corr[2]) and np.isnan(p[2]) + assert np.isfinite(corr[0]) and np.isfinite(corr[3]) + + +@pytest.mark.parametrize("mode", ["train_test", "cv"]) +def test_constant_target_is_excluded_from_summaries(mode): + X, Y = _data() + Y[:, 1] = 2.5 # constant everywhere, so invalid in every test set + model = NestedCVModel("ridge") + if mode == "train_test": + metrics, _, _ = model.fit_predict(X[:90], Y[:90], X_test=X[90:], y_test=Y[90:], + folding_type="kfold", n_inner_folds=3, **FIT) + else: + metrics, _, _ = model.fit_predict(X, Y, folding_type="kfold", n_outer_folds=3, + n_inner_folds=2, **FIT) + + corr = np.asarray(metrics["correlations"], dtype=float) + assert np.isnan(corr[1]) + assert metrics["n_invalid_targets"] == 1 and metrics["n_valid_targets"] == 3 + assert metrics["invalid_target_mask"] == [False, True, False, False] + assert not metrics["significant_mask"][1] + assert metrics["median_score"] == pytest.approx(np.median(corr[[0, 2, 3]])) + + +def test_inner_selection_excludes_invalid_targets_and_folds(monkeypatch): + import torch + + X = torch.arange(12, dtype=torch.float32).reshape(6, 2) + y = torch.tensor([[0., 1.], [1., 1.], [2., 1.], [3., 1.], [4., 1.], [5., 1.]]) + # Invalid column would dominate selection if included. The first column is + # valid and favors alpha 2; the constant column must have no vote. + monkeypatch.setattr(nested_cv, 'ridge_corr_torch', + lambda *a, **kw: torch.tensor([[0.1, 100.], [0.9, 0.]])) + selected = nested_cv._find_best_alphas( + X, y, [([0, 1, 2], [3, 4, 5])], [1., 2.], single_alpha=True, + ) + assert selected.tolist() == [2., 2.] + y[:, 0] = float('nan') + with pytest.raises(ValueError, match='No valid targets'): + nested_cv._find_best_alphas( + X, y, [([0, 1, 2], [3, 4, 5])], [1., 2.], single_alpha=True, + ) + + +def test_nonfinite_training_target_retains_identity(): + X, Y = _data() + Y[0, 1] = np.nan + metrics, _, _ = NestedCVModel('ridge').fit_predict( + X[:90], Y[:90], X_test=X[90:], y_test=Y[90:], + folding_type='kfold', n_inner_folds=3, **FIT, + ) + assert metrics['invalid_target_mask'] == [False, True, False, False] + assert np.isnan(metrics['correlations'][1]) + + +def test_zero_trim_keeps_test_rows(): + for train, test in create_folds(30, 'kfold_trimmed', 3, trim_size=0): + assert len(train) == 20 and len(test) == 10 + + +def test_constant_training_target_is_not_scored_on_variable_test(): + X, Y = _data() + Y[:90, 1] = 2.5 + metrics, weights, _ = NestedCVModel('ridge').fit_predict( + X[:90], Y[:90], X_test=X[90:], y_test=Y[90:], + folding_type='kfold', n_inner_folds=3, **FIT, + ) + assert metrics['invalid_target_mask'] == [False, True, False, False] + assert np.isnan(weights[:, 1]).all() + + +@pytest.mark.parametrize('normalpha', [False, True]) +def test_squared_alpha_matches_reference_ridge(normalpha): + import torch + from sklearn.linear_model import Ridge + from encoding.models.ridge_regression import ridge_torch + + X, Y = _data() + X = X.astype(np.float32) + Y = Y.astype(np.float32) + effective = 3. * (np.linalg.svd(X, compute_uv=False)[0] if normalpha else 1.) + actual = ridge_torch(torch.tensor(X), torch.tensor(Y), + torch.full((Y.shape[1],), 3.), normalpha=normalpha) + expected = Ridge(alpha=effective**2, fit_intercept=False, solver='svd').fit(X, Y) + np.testing.assert_allclose(actual.numpy(), expected.coef_.T, rtol=2e-5, atol=2e-5) + + +def test_group_labels_propagate_to_nested_folds(monkeypatch): + calls = [] + X, Y = _data() + groups = np.repeat(np.arange(6), 20) + + def spy(n, kind, folds, **kwargs): + labels = np.asarray(kwargs['groups']) + splits = create_folds(n, kind, folds, **kwargs) + for train, test in splits: + assert not set(labels[train]) & set(labels[test]) + calls.append(labels) + return splits + + monkeypatch.setattr(nested_cv, 'create_folds', spy) + NestedCVModel('ridge').fit_predict( + X, Y, groups=groups, folding_type='group', n_outer_folds=3, + n_inner_folds=2, **FIT, + ) + assert len(calls) == 4 + assert all(len(labels) == 80 for labels in calls[1:]) diff --git a/tests/test_supplied_estimators.py b/tests/test_supplied_estimators.py new file mode 100644 index 0000000..c32d896 --- /dev/null +++ b/tests/test_supplied_estimators.py @@ -0,0 +1,166 @@ +import numpy as np +import pytest +from sklearn.base import BaseEstimator, RegressorMixin +from sklearn.linear_model import Ridge +from sklearn.pipeline import make_pipeline +from sklearn.preprocessing import StandardScaler +from sklearn.svm import SVR +from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor + +from encoding.models.nested_cv import NestedCVModel +from encoding.utils import ModelSaver +from test_ecog_end_to_end import fixture, run + + +OPTIONS = dict(folding_type="kfold", n_outer_folds=3, n_inner_folds=2, use_gpu=False) + + +class RecordingScaler(StandardScaler): + fits = [] + + def fit(self, X, y=None, **kwargs): + self.fits.append((self, X.copy(), y.copy())) + return super().fit(X, y, **kwargs) + + +class WrongShape(RegressorMixin, BaseEstimator): + def fit(self, X, y): + return self + + def predict(self, X): + return np.zeros((len(X), 2)) + + +@pytest.fixture +def data(): + rng = np.random.default_rng(42) + x = rng.normal(size=(60, 4)).astype(np.float32) + y = x[:, :2] + rng.normal(size=(60, 2)).astype(np.float32) * .1 + return x, y + + +def test_ridge_penalty_parity(data): + ridge = NestedCVModel("optimized") + sklearn = NestedCVModel("supplied", estimator=Ridge(alpha=4, fit_intercept=False, solver="svd")) + options = dict(OPTIONS, normalize_features=True, normalize_targets=True) + ridge.fit_predict(*data, alphas=[2.], normalpha=False, **options) + _, weights, alphas = sklearn.fit_predict(*data, **options) + assert weights is alphas is None + for left, right in zip(ridge.results_["folds"], sklearn.results_["folds"]): + np.testing.assert_array_equal(left["test_indices"], right["test_indices"]) + np.testing.assert_array_equal(left["effective_penalties"], [4, 4]) + np.testing.assert_allclose(left["predictions"], right["predictions"], atol=2e-6, rtol=0) + + +def test_pipeline_fits_only_on_training_rows_and_outer_targets_are_isolated(data): + x, y = data + pipeline = make_pipeline(RecordingScaler(), DecisionTreeRegressor(random_state=42)) + model = NestedCVModel("tree", estimator=pipeline, + param_grid={"decisiontreeregressor__max_depth": [1, 4]}) + RecordingScaler.fits.clear() + model.fit_predict(x, y, **OPTIONS) + before = model.results_["folds"][0] + expected = [] + for fold in model.results_["folds"]: + for _ in range(2): + expected.extend(split["train_indices"] for split in fold["inner_splits"]) + expected.append(fold["train_indices"]) + assert len(RecordingScaler.fits) == len(expected) + assert len({id(fitted) for fitted, _, _ in RecordingScaler.fits}) == len(expected) + assert not hasattr(pipeline[0], "mean_") + for (_, features, targets), indices in zip(RecordingScaler.fits, expected): + np.testing.assert_array_equal(features, x[indices]) + np.testing.assert_array_equal(targets, y[indices]) + candidate_scores = {} + for depth in (1, 4): + scores = [] + for split in before["inner_splits"]: + train, validation = split["train_indices"], split["validation_indices"] + scaler = StandardScaler().fit(x[train]) + tree = DecisionTreeRegressor(random_state=42, max_depth=depth) + tree.fit(scaler.transform(x[train]), y[train]) + predicted = tree.predict(scaler.transform(x[validation])) + for actual, estimate in zip(y[validation].T, predicted.T): + scores.append(np.corrcoef(actual, estimate)[0, 1] if np.ptp(estimate) else 0.) + candidate_scores[depth] = np.mean(scores) + assert before["selected_params"] == { + "decisiontreeregressor__max_depth": max(candidate_scores, key=candidate_scores.get) + } + assert before["inner_selection_score"] == pytest.approx(max(candidate_scores.values()), abs=2e-6) + changed = y.copy() + changed[before["test_indices"]] *= -100 + model.fit_predict(x, changed, **OPTIONS) + after = model.results_["folds"][0] + assert before["selected_params"] == after["selected_params"] + assert before["inner_selection_score"] == after["inner_selection_score"] + np.testing.assert_array_equal(before["predictions"], after["predictions"]) + RecordingScaler.fits.clear() + + +def test_estimator_contract_and_explicit_adapter(data): + x, y = data + with pytest.raises(ValueError, match="regressor instance"): + NestedCVModel("classifier", estimator=DecisionTreeClassifier()) + cached = make_pipeline(StandardScaler(), Ridge(), memory="/tmp") + with pytest.raises(ValueError, match="caching must be disabled"): + NestedCVModel("cached", estimator=cached) + with pytest.raises(ValueError, match="native multi-output"): + NestedCVModel("svr", estimator=SVR()).fit_predict(*data, **OPTIONS) + with pytest.raises(ValueError, match="prediction shape"): + NestedCVModel("shape", estimator=WrongShape()).fit_predict(x, y[:, :1], **OPTIONS) + model = NestedCVModel("svr", estimator=SVR(), target_mode="per_target") + model.fit_predict(*data, **OPTIONS) + for fold in model.results_["folds"]: + first, second = fold["estimator_state"]["models"] + assert first is not second + np.testing.assert_allclose( + model.predict_fold(fold, x[fold["test_indices"]]), fold["predictions"] + ) + + +def test_ecog_pipeline_saved_replay(tmp_path, monkeypatch): + model = NestedCVModel( + "sklearn", estimator=make_pipeline(StandardScaler(), Ridge()), + param_grid={"ridge__alpha": [.1, 1.]}, + ) + loaded, x, _, keys, *_ = run(tmp_path / "ecog", fixture(29, signal=True), monkeypatch, model=model) + saved = loaded["results"] + metadata = saved["metadata"] + assert metadata["sample_ids"] == [(name, f"{name}:sample:{i}") for name, i in keys] + assert [entry["electrode_id"] for entry in metadata["target_metadata"]] == ["E9", "E1"] + assert loaded["weights"] is loaded["best_alphas"] is saved["final_refit"] is None + assert loaded["manifest"]["replay_available"] + for i, fold in enumerate(saved["folds"]): + assert fold["fold_id"] == i and fold["model_role"] == "outer_fold" + assert fold["selected_params"]["ridge__alpha"] in (.1, 1.) + np.testing.assert_allclose( + model.predict_fold(fold, x[fold["test_indices"]]), fold["predictions"], atol=2e-6 + ) + assert any(len(fold["purged_indices"]) for fold in saved["folds"]) + assert any(len(split["purged_indices"]) for fold in saved["folds"] for split in fold["inner_splits"]) + + saver = ModelSaver(tmp_path / "without_models") + path = saver.save_encoding_model(None, None, {}, loaded["metrics"], save_weights=False, results=saved) + stripped = saver.load_encoding_result(path) + assert not stripped["manifest"]["replay_available"] + with pytest.raises(ValueError, match="omitted"): + model.predict_fold(stripped["results"]["folds"][0], x) + + +def test_provided_test_partition_and_invalid_target_identity(data): + x, y = data + y[:, 0] = 0 + model = NestedCVModel("ridge", estimator=Ridge(alpha=2)) + metrics, _, _ = model.fit_predict( + x[:40], y[:40], X_test=x[40:], y_test=y[40:], + result_metadata={"test_sample_ids": list(range(40, 60))}, + **OPTIONS, + ) + result = model.results_ + assert result["final_refit"] == {"fold_id": 0, "scope": "provided_training_set_only"} + assert result["metadata"]["test_sample_ids"] == list(range(40, 60)) + fold = result["folds"][0] + assert fold["model_role"] == "training_fit" + assert metrics["invalid_target_mask"] == [True, False] + np.testing.assert_array_equal(fold["estimator_state"]["target_indices"], [1]) + np.testing.assert_allclose(model.predict_fold(fold, x[40:]), fold["predictions"]) diff --git a/unified.py b/unified.py index a8766a6..c749048 100644 --- a/unified.py +++ b/unified.py @@ -323,6 +323,8 @@ def prepare_data(self) -> Dict[str, np.ndarray]: def train(self) -> Dict[str, Any]: """Run the training process.""" + self.last_run_dir_ = None + self.reporting_error_ = None try: # Prepare data using universal method data = self.prepare_data() @@ -347,6 +349,7 @@ def train(self) -> Dict[str, Any]: use_corr=True, normalize_features=self.config["normalize_features"], normalize_targets=self.config["normalize_targets"], + result_metadata=self.config.get("result_metadata"), ) else: # Cross-validation (LPP/Narratives) @@ -364,11 +367,10 @@ def train(self) -> Dict[str, Any]: use_corr=True, normalize_features=self.config["normalize_features"], normalize_targets=self.config["normalize_targets"], + result_metadata=self.config.get("result_metadata"), ) - # Log and save - self.log_metrics(metrics) - + # Persist fitted state before optional result reporting. hyperparams = { **self.config, "single_alpha": True, @@ -376,12 +378,22 @@ def train(self) -> Dict[str, Any]: "use_corr": True, } - self.model_saver.save_encoding_model( + self.last_run_dir_ = self.model_saver.save_encoding_model( weights=weights, best_alphas=best_alphas, hyperparams=hyperparams, metrics=metrics, + results=getattr(self.model, "results_", None), ) + self.reporting_error_ = None + try: + self.log_metrics(metrics) + except Exception as error: + self.reporting_error_ = f"{type(error).__name__}: {error}" + self.logger.warning( + "Optional result reporting failed; fitted results are saved at %s: %s", + self.last_run_dir_, self.reporting_error_, exc_info=True, + ) # Print results self.logger.info("\nTraining Results:") @@ -553,4 +565,4 @@ def main(): if __name__ == "__main__": - main() \ No newline at end of file + main() From 1804737b31b2ebeb9a8ac8fc536d57211c75a900 Mon Sep 17 00:00:00 2001 From: Aadhav Thaniga Date: Wed, 18 Nov 2026 20:25:49 -0500 Subject: [PATCH 9/9] Add ECoG support to unified CLI --- README.md | 25 +++ tests/test_unified_ecog_cli.py | 321 +++++++++++++++++++++++++++++++++ unified.py | 172 ++++++++++++++++-- 3 files changed, 500 insertions(+), 18 deletions(-) create mode 100644 tests/test_unified_ecog_cli.py diff --git a/README.md b/README.md index 7809a2d..6036fef 100644 --- a/README.md +++ b/README.md @@ -206,6 +206,31 @@ in the recorded feature and sample order. Synthetic validation exercises the encoding path. Real-data loading/alignment and diagnostic replay do not establish independent predictive performance or exact paper replication. +#### ECoG from the command line + +`unified.py` runs the same ECoG path. Put the `ecog_temporal_config` above in a +JSON file, with one `feature_specs` entry per modality, in the same order: + +```json +{"delays_s": [0, 0.1, 0.2], "protocol": "blocked", "embargo_s": 0.3, + "memory_budget_bytes": 2000000000, + "feature_specs": [{"method": "words_per_second", "support_s": [0, 0]}, + {"method": "word_sum", "support_s": [0, 0]}]} +``` + +```bash +python unified.py --dataset_type ecog --data_dir path/to/ecog_dir --subject S1 \ + --modalities wordrate embeddings --model_names wordrate word2vec \ + --vector_path vectors.bin --binary --ecog_config ecog_config.json \ + --cache_dir cache --n_outer_folds 5 --n_inner_folds 5 --alphas 0.1 1 10 +``` + +`--data_dir` holds `ecog.json`. fMRI-only options (`--tr`, `--ndelays`, trimming, +downsampling, `--folding_type`, `--chunk_length`) are rejected. For +`diagnostic_in_sample`, omit `embargo_s` and the fold counts and pass one +`--alphas` value. The saved results record the effective configuration and +the config/manifest hashes under `metadata["run_config"]`. + ## 3) Quick tutorial: This library uses the same core modules across datasets, here's an example for Narratives: diff --git a/tests/test_unified_ecog_cli.py b/tests/test_unified_ecog_cli.py new file mode 100644 index 0000000..8402b4c --- /dev/null +++ b/tests/test_unified_ecog_cli.py @@ -0,0 +1,321 @@ +"""ECoG through the existing ``unified.py`` CLI: parity with the Python API, +temporal semantics, and unchanged fMRI argument handling. Synthetic and offline.""" +import hashlib +import json +import os +import subprocess +import sys +from pathlib import Path + +import numpy as np +import pytest + +import unified +from encoding.assembly import ECoGAssemblyGenerator +from encoding.downsample.downsampling import Downsampler +from encoding.features.embeddings import StaticEmbeddingFeatureExtractor +from encoding.features.FIR_expander import FIR +from encoding.features.simple_features import WordRateFeatureExtractor +from encoding.models.nested_cv import NestedCVModel +from encoding.trainer import AbstractTrainer +from encoding.utils import ModelSaver + +REPO = Path(__file__).resolve().parents[1] +RATE, N = 10.0, 240 +ALPHAS = [0.1, 1.0, 10.0] +BLOCKED = { + "delays_s": [0, 0.1, 0.2], "protocol": "blocked", "embargo_s": 0.3, + "memory_budget_bytes": 200_000_000, + "feature_specs": [ + {"method": "words_per_second", "support_s": [0, 0]}, + {"method": "word_sum", "support_s": [0, 0]}, + ], +} +DIAGNOSTIC = {**{k: v for k, v in BLOCKED.items() if k != "embargo_s"}, + "protocol": "diagnostic_in_sample"} +# Effective config of the pre-change CLI for this command (snapshot of HEAD 8a9ca6f). +FMRI_ARGV = ("--dataset_type lebel --data_dir d --subject UTS03 --tr 2 --ndelays 4 " + "--lookback 256 --cache_dir c --modality wordrate --model_name wordrate").split() +FMRI_SNAPSHOT = { + 'dataset_type': 'lebel', 'data_dir': 'd', 'subject': 'UTS03', 'tr': 2.0, + 'context_type': 'fullcontext', 'use_volume': False, 'story_idx': None, + 'modality': 'wordrate', 'modalities': None, 'model_name': 'wordrate', 'model_names': None, + 'layer_idx': 9, 'last_token': False, 'n_outer_folds': 5, 'n_inner_folds': 5, + 'folding_type': 'chunked', 'chunk_length': 20, 'singcutoff': 1e-10, + 'downsample_method': 'lanczos', 'lanczos_cutoff_mult': 1.0, 'lanczos_window': 3, + 'normalize_features': False, 'normalize_targets': False, 'ndelays': 4, 'lookback': 256, + 'use_gpu': False, 'cache_dir': 'c', 'results_dir': 'results', 'logger_backend': 'wandb', + 'wandb_project_name': 'lit-encoding', 'vector_path': None, 'binary': False, + 'lowercase': False, 'chunk_size': 0.1, 'context_size': 16.0, 'story_order': None, + **{f"{p}{d}_{e}": None for p in ("", "train_", "test_") + for d in ("features", "targets") for e in ("start", "end")}, +} + + +def write_inputs(root, config): + """Two recordings with a declared neural gap, written as an ecog.json manifest.""" + data = root / "data" + data.mkdir() + rng = np.random.default_rng(7) + records = [] + for run in range(2): + name, origin = f"run-{run}", 100.0 * run + times = origin + np.arange(N) / RATE + words, onsets, signs = [], [], np.zeros(N) + for i in range(N): + for k in range(rng.integers(0, 3)): + word = "plus" if rng.random() > .5 else "minus" + words.append(word) + onsets.append(times[i] + k / (4 * RATE)) + signs[i] += 1 if word == "plus" else -1 + counts = np.bincount(np.searchsorted(times, onsets, side="right") - 1, minlength=N) + brain = np.zeros((N, 2)) + brain[1:, 0] += 0.5 * counts[:-1] + brain[2:, 1] += signs[:-2] + brain += 0.3 * rng.normal(size=brain.shape) + valid = np.ones(N, dtype=bool) + valid[50:53] = False + brain[~valid] = np.nan + arrays = {"brain_data": brain.astype(np.float32), "neural_times": times, + "stimulus_times": np.asarray(onsets), "valid_samples": valid} + record = { + "recording_id": name, "subject_id": "S1", "run_id": name, + "sampling_rate_hz": RATE, "neural_time_unit": "s", "stimulus_time_unit": "s", + "neural_clock": "rec", "stimulus_clock": "rec", + "words": words, "stimuli": words, "word_ids": [f"{name}:w{j}" for j in range(len(words))], + "sample_ids": [f"{name}:s{i}" for i in range(N)], + "electrodes": [{"electrode_id": "E2"}, {"electrode_id": "E1"}], + "signal_units": "synthetic", + "invalid_intervals": [{"start": times[50], "stop": times[53], "reason": "gap"}], + "provenance": {"source": "synthetic CLI fixture", + "preprocessing": {"description": "none", "support_s": [0, 0]}, + "stimulus_context": {"policy": "single words"}}, + } + for field, value in arrays.items(): + np.save(data / f"{name}_{field}.npy", value) + record[field] = {"npy": f"{name}_{field}.npy"} + records.append((record, times)) + (data / "ecog.json").write_text(json.dumps( + {"schema_version": 1, "recordings": [r for r, _ in records]})) + vectors = root / "tiny.w2v.txt" + vectors.write_text("2 1\nplus 1\nminus -1\n") + cfg = root / "ecog_cfg.json" + cfg.write_text(json.dumps(config)) + return data, cfg, vectors, {r["recording_id"]: t for r, t in records} + + +def cli_argv(root, data, cfg, vectors, *extra): + return ["--dataset_type", "ecog", "--data_dir", str(data), "--subject", "S1", + "--modalities", "wordrate", "embeddings", "--model_names", "wordrate", "tiny", + "--vector_path", str(vectors), "--ecog_config", str(cfg), + "--cache_dir", str(root / "cache"), "--results_dir", str(root / "cli"), + "--logger_backend", "tensorboard", "--normalize_features", "--normalize_targets", + *extra] + + +def api_run(root, data, vectors, config, **fit): + """The documented Python API, built independently of the CLI helpers.""" + assembly = ECoGAssemblyGenerator(data).generate_assembly("S1") + static = StaticEmbeddingFeatureExtractor(dict( + vector_path=str(vectors), binary=False, lowercase=False, + oov_handling="copy_prev", use_tqdm=True)) + trainer = AbstractTrainer( + assembly, [WordRateFeatureExtractor({}), static], None, + NestedCVModel("ridge_regression"), None, {}, layer_idx=9, lookback=256, + dataset_type="ecog", logger_backend="tensorboard", results_dir=str(root / "api"), + ecog_temporal_config=config) + trainer.train(use_gpu=False, single_alpha=True, normalpha=True, use_corr=True, + normalize_features=True, normalize_targets=True, singcutoff=1e-10, **fit) + return load(trainer.last_run_dir_) + + +def load(run_dir): + return ModelSaver(Path(run_dir).parent).load_encoding_result(run_dir) + + +def forbid_fmri_preparation(monkeypatch): + def fail(*args, **kwargs): + raise AssertionError("ECoG entered fMRI preparation") + for owner, name in [(Downsampler, "downsample"), (FIR, "make_delayed"), + (AbstractTrainer, "extract_and_downsample_features"), + (AbstractTrainer, "apply_fir_delays"), (AbstractTrainer, "structure_data"), + (unified.UnifiedTrainer, "__init__"), (unified.UnifiedTrainer, "prepare_data")]: + monkeypatch.setattr(owner, name, fail) + + +# --- argument acceptance / rejection --------------------------------------- + +def test_fmri_effective_defaults_unchanged(): + assert vars(unified.parse_args(FMRI_ARGV)) == FMRI_SNAPSHOT + assert list(vars(unified.parse_args(FMRI_ARGV))) == list(FMRI_SNAPSHOT) + + +@pytest.mark.parametrize("drop", ["--tr", "--ndelays", "--lookback"]) +def test_fmri_required_options_still_exit_2(drop): + i = FMRI_ARGV.index(drop) + with pytest.raises(SystemExit) as error: + unified.parse_args(FMRI_ARGV[:i] + FMRI_ARGV[i + 2:]) + assert error.value.code == 2 + + +@pytest.mark.parametrize("extra", [["--ecog_config", "x.json"], ["--alphas", "1"]]) +def test_ecog_only_options_rejected_for_fmri(extra): + with pytest.raises(SystemExit) as error: + unified.parse_args(FMRI_ARGV + extra) + assert error.value.code == 2 + + +ECOG_BASE = "--dataset_type ecog --data_dir d --subject S1 --cache_dir c --modality wordrate --model_name wordrate".split() + + +def test_ecog_minimal_arguments_accepted(): + args = vars(unified.parse_args(ECOG_BASE + ["--ecog_config", "cfg.json", "--alphas", "1", "2"])) + assert args["lookback"] == 256 and args["alphas"] == [1.0, 2.0] + assert all(args[name] is None for name in unified.ECOG_REJECTED) + + +@pytest.mark.parametrize("extra", [ + [], ["--tr", "2"], ["--ndelays", "4"], ["--features_start", "3"], ["--use_volume"], + ["--folding_type", "kfold"], ["--chunk_length", "5"], ["--downsample_method", "average"], + ["--lanczos_window", "5"], ["--story_idx", "1"], ["--story_order", "a"], +]) +def test_ecog_rejects_missing_config_and_fmri_only_options(extra, capsys): + config = [] if not extra else ["--ecog_config", "cfg.json"] + with pytest.raises(SystemExit) as error: + unified.parse_args(ECOG_BASE + config + extra) + assert error.value.code == 2 + message = capsys.readouterr().err + assert (extra[0] if extra else "--ecog_config") in message + + +def test_fmri_main_still_uses_unified_trainer(monkeypatch): + seen = {} + + class Fake: + DATASET_CONFIGS = unified.UnifiedTrainer.DATASET_CONFIGS + + def __init__(self, config): + seen.update(config) + + def train(self): + return {"median_score": 0.0} + + monkeypatch.setattr(unified, "UnifiedTrainer", Fake) + monkeypatch.setattr(unified, "run_ecog", lambda c: pytest.fail("fMRI routed to ECoG")) + unified.main(FMRI_ARGV) + assert seen == {**FMRI_SNAPSHOT, "modalities": ["wordrate"], "model_names": ["wordrate"]} + + +# --- ECoG CLI behaviour ------------------------------------------------------- + +def test_blocked_cli_matches_python_api(tmp_path, monkeypatch): + data, cfg, vectors, times = write_inputs(tmp_path, BLOCKED) + with monkeypatch.context() as patch: + forbid_fmri_preparation(patch) + trainer = unified.main(cli_argv(tmp_path, data, cfg, vectors, "--n_outer_folds", "3", + "--n_inner_folds", "2", "--alphas", *map(str, ALPHAS))) + cli = load(trainer.last_run_dir_) + api = api_run(tmp_path, data, vectors, BLOCKED, alphas=ALPHAS, n_outer_folds=3, n_inner_folds=2) + + # Scores, predictions, splits and fitted state are identical. + np.testing.assert_array_equal(cli["metrics"]["correlations"], api["metrics"]["correlations"]) + assert cli["metrics"]["inference_status"] == "not_assessed" + assert len(cli["results"]["folds"]) == 3 + for a, b in zip(cli["results"]["folds"], api["results"]["folds"]): + for key in ("train_indices", "test_indices", "predictions", "targets", + "weights", "selected_alphas"): + np.testing.assert_array_equal(a[key], b[key]) + for ia, ib in zip(a["inner_splits"], b["inner_splits"]): + np.testing.assert_array_equal(ia["train_indices"], ib["train_indices"]) + np.testing.assert_array_equal(ia["validation_indices"], ib["validation_indices"]) + assert cli["hyperparams"] == api["hyperparams"] + ca, cb = cli["results"]["configuration"], api["results"]["configuration"] + assert ca.pop("alphas").tolist() == cb.pop("alphas").tolist() == ALPHAS + assert ca == cb and ca["folding_type"] == "blocked" and ca["n_outer_folds"] == 3 + + # Aligned rows, exclusions, support bounds and delay records are identical. + meta, api_meta = cli["results"]["metadata"], api["results"]["metadata"] + temporal = meta["temporal"] + for key in ("rows", "exclusions", "support_bounds_s", "feature_specs", "feature_widths", + "protocol", "embargo_s", "design_order", "recordings"): + assert repr(temporal[key]) == repr(api_meta["temporal"][key]), key + assert meta["sample_ids"] == api_meta["sample_ids"] + + # Sample timing and delays survive untouched. + for row in temporal["rows"] + temporal["exclusions"]: + assert row["time_s"] == times[row["recording_id"]][row["source_index"]] + assert row["sample_id"] == f"{row['recording_id']}:s{row['source_index']}" + assert not any(r["source_index"] in (50, 51, 52) for r in temporal["rows"]) + for record in temporal["recordings"].values(): + assert record["delays"]["requested_s"] == [0, 0.1, 0.2] + assert record["delays"]["sample_offsets"] == [0, 1, 2] + assert record["sampling_rate_hz"] == RATE + assert temporal["embargo_s"] == 0.3 and tuple(temporal["feature_widths"]) == (1, 1) + + # Blocked CV: contiguous test blocks covering every row once, and no retained + # training row whose support overlaps an embargo-dilated test row. + bounds = np.asarray(temporal["support_bounds_s"]) + recordings = np.array([r["recording_id"] for r in temporal["rows"]]) + tested = np.concatenate([f["test_indices"] for f in cli["results"]["folds"]]) + np.testing.assert_array_equal(np.sort(tested), np.arange(len(recordings))) + for fold in cli["results"]["folds"]: + train, test = fold["train_indices"], fold["test_indices"] + np.testing.assert_array_equal(test, np.arange(test[0], test[-1] + 1)) + assert not set(train) & set(test) + assert len(train) < len(recordings) - len(test) # the embargo purged rows + for rec in np.unique(recordings[test]): + held = bounds[test[recordings[test] == rec]] + [-0.3, 0.3] + for lo, hi in bounds[train[recordings[train] == rec]]: + assert not ((held[:, 0] <= hi) & (lo <= held[:, 1])).any() + + # Reproducibility record: effective config, hashes, no absolute paths. + run = meta["run_config"] + assert run["ecog_temporal_config"] == BLOCKED + assert run["ecog_config_sha256"] == hashlib.sha256(cfg.read_bytes()).hexdigest() + assert run["manifest_sha256"] == hashlib.sha256((data / "ecog.json").read_bytes()).hexdigest() + assert (run["subject"], run["modalities"], run["model_names"]) == ( + "S1", ["wordrate", "embeddings"], ["wordrate", "tiny"]) + assert run["fit_options"]["n_outer_folds"] == 3 and run["encoding_model"] == "ridge_regression" + assert str(tmp_path) not in json.dumps(run, default=str) + assert "run_config" not in api_meta + + +def test_diagnostic_in_sample_protocol(tmp_path, monkeypatch): + data, cfg, vectors, _ = write_inputs(tmp_path, DIAGNOSTIC) + with monkeypatch.context() as patch: + forbid_fmri_preparation(patch) + trainer = unified.main(cli_argv(tmp_path, data, cfg, vectors, "--alphas", "1.0")) + cli = load(trainer.last_run_dir_) + api = api_run(tmp_path, data, vectors, DIAGNOSTIC, alphas=[1.0]) + assert cli["metrics"]["evaluation"] == "in_sample_diagnostic" + [fold] = cli["results"]["folds"] + assert fold["model_role"] == "in_sample_diagnostic" + np.testing.assert_array_equal(fold["predictions"], api["results"]["folds"][0]["predictions"]) + temporal = cli["results"]["metadata"]["temporal"] + assert temporal["protocol"] == "diagnostic_in_sample" + assert temporal["validity_policy"] == "allow_finite_unknown_in_sample" + assert repr(temporal["rows"]) == repr(api["results"]["metadata"]["temporal"]["rows"]) + + +def test_diagnostic_semantics_are_enforced_through_cli(tmp_path): + data, cfg, vectors, _ = write_inputs(tmp_path, DIAGNOSTIC) + with pytest.raises(ValueError, match="do not use CV fold counts"): + unified.main(cli_argv(tmp_path, data, cfg, vectors, "--alphas", "1", "--n_outer_folds", "3")) + with pytest.raises(ValueError, match="one fixed positive"): + unified.main(cli_argv(tmp_path, data, cfg, vectors)) + + +def test_cli_subprocess_smoke(tmp_path): + data, cfg, vectors, _ = write_inputs(tmp_path, BLOCKED) + env = {**os.environ, "PYTHONPATH": str(REPO), "WANDB_MODE": "disabled", + "HF_HUB_OFFLINE": "1", "TRANSFORMERS_OFFLINE": "1", "MPLBACKEND": "Agg"} + # Real reporting path (no conftest stubs); wandb in disabled mode stays offline. + argv = cli_argv(tmp_path, data, cfg, vectors, "--n_outer_folds", "3", "--n_inner_folds", "2", + "--logger_backend", "wandb") + done = subprocess.run([sys.executable, str(REPO / "unified.py"), *argv], cwd=tmp_path, + env=env, capture_output=True, text=True, timeout=300) + assert done.returncode == 0, done.stderr[-3000:] + [run] = [p for p in (tmp_path / "cli").iterdir() if p.name.startswith("run_")] + result = load(run) + assert result["results"]["metadata"]["temporal"]["protocol"] == "blocked" + assert np.isfinite(result["metrics"]["correlations"]).all() diff --git a/unified.py b/unified.py index c749048..8ddfc75 100644 --- a/unified.py +++ b/unified.py @@ -4,7 +4,11 @@ """ import argparse +import hashlib +import json import logging +from pathlib import Path +from types import SimpleNamespace from typing import Dict, List, Union, Any, Optional import numpy as np from datetime import datetime @@ -13,6 +17,7 @@ from encoding.features.factory import FeatureExtractorFactory from encoding.downsample.downsampling import Downsampler from encoding.models.nested_cv import NestedCVModel +from encoding.trainer import AbstractTrainer from encoding.utils import ActivationCache, ModelSaver, zs from encoding.features.FIR_expander import FIR from encoding.plotting.plotting_utils import ( @@ -434,18 +439,43 @@ def log_metrics(self, metrics: Dict[str, Union[float, List[float]]]): self.experiment_logger.log_scalar("n_significant_voxels", float(metrics["n_significant"])) -def parse_args(): +# fMRI defaults are applied after parsing so ECoG can reject explicitly set +# fMRI-only options. Effective fMRI values are unchanged. +FMRI_DEFAULTS = { + "n_outer_folds": 5, "n_inner_folds": 5, "folding_type": "chunked", + "chunk_length": 20, "downsample_method": "lanczos", + "lanczos_cutoff_mult": 1.0, "lanczos_window": 3, +} +FMRI_REQUIRED = ("tr", "ndelays", "lookback") +TRIMMING_PARAMS = ( + "features_start", "features_end", "targets_start", "targets_end", + "train_features_start", "train_features_end", "train_targets_start", "train_targets_end", + "test_features_start", "test_features_end", "test_targets_start", "test_targets_end", +) +# Options with no meaning for continuous ECoG; timing comes from --ecog_config. +ECOG_REJECTED = ( + "tr", "ndelays", "story_idx", "story_order", "folding_type", "chunk_length", + "downsample_method", "lanczos_cutoff_mult", "lanczos_window", *TRIMMING_PARAMS, +) + + +def parse_args(argv=None): """Parse command line arguments.""" parser = argparse.ArgumentParser(description="Unified trainer for encoding models") # Dataset parameters parser.add_argument("--dataset_type", type=str, required=True, - choices=["lpp", "lebel", "narratives"], + choices=["lpp", "lebel", "narratives", "ecog"], help="Dataset type") parser.add_argument("--data_dir", type=str, required=True, - help="Path to dataset directory") + help="Path to dataset directory (ECoG: directory with ecog.json, or the manifest)") parser.add_argument("--subject", type=str, required=True, help="Subject ID") - parser.add_argument("--tr", type=float, required=True, help="TR value") + parser.add_argument("--tr", type=float, help="TR value (required for fMRI)") + parser.add_argument("--ecog_config", type=str, + help="ECoG only: JSON file with the temporal config (delays_s, feature_specs, " + "protocol, embargo_s, memory_budget_bytes, retrospective)") + parser.add_argument("--alphas", type=float, nargs="+", + help="ECoG only: ridge alphas (exactly one for diagnostic_in_sample)") parser.add_argument("--context_type", type=str, default="fullcontext", choices=["fullcontext", "nocontext", "halfcontext"], help="Context window type") @@ -465,20 +495,20 @@ def parse_args(): parser.add_argument("--last_token", action="store_true", help="Use last token only") # Training parameters - parser.add_argument("--n_outer_folds", type=int, default=5, help="Outer CV folds") - parser.add_argument("--n_inner_folds", type=int, default=5, help="Inner CV folds") - parser.add_argument("--folding_type", type=str, default="chunked", help="CV folding type") - parser.add_argument("--chunk_length", type=int, default=20, help="Chunk length") + parser.add_argument("--n_outer_folds", type=int, help="Outer CV folds (fMRI default 5)") + parser.add_argument("--n_inner_folds", type=int, help="Inner CV folds (fMRI default 5)") + parser.add_argument("--folding_type", type=str, help="CV folding type (fMRI only, default chunked)") + parser.add_argument("--chunk_length", type=int, help="Chunk length (fMRI only, default 20)") parser.add_argument("--singcutoff", type=float, default=1e-10, help="Singular value cutoff") # Preprocessing parameters - parser.add_argument("--downsample_method", type=str, default="lanczos", help="Downsampling method") - parser.add_argument("--lanczos_cutoff_mult", type=float, default=1.0, help="Lanczos cutoff multiplier") - parser.add_argument("--lanczos_window", type=int, default=3, help="Lanczos window") + parser.add_argument("--downsample_method", type=str, help="Downsampling method (fMRI only, default lanczos)") + parser.add_argument("--lanczos_cutoff_mult", type=float, help="Lanczos cutoff multiplier (fMRI only, default 1.0)") + parser.add_argument("--lanczos_window", type=int, help="Lanczos window (fMRI only, default 3)") parser.add_argument("--normalize_features", action="store_true", help="Normalize features") parser.add_argument("--normalize_targets", action="store_true", help="Normalize targets") - parser.add_argument("--ndelays", type=int, required=True, help="Number of FIR delays") - parser.add_argument("--lookback", type=int, required=True, help="Context lookback") + parser.add_argument("--ndelays", type=int, help="Number of FIR delays (required for fMRI)") + parser.add_argument("--lookback", type=int, help="Context lookback (required for fMRI; ECoG default 256)") # System parameters parser.add_argument("--use_gpu", action="store_true", help="Use GPU") @@ -513,12 +543,115 @@ def parse_args(): parser.add_argument("--test_targets_start", type=int, help="Test targets trim start") parser.add_argument("--test_targets_end", type=int, help="Test targets trim end") - return parser.parse_args() - - -def main(): + args = parser.parse_args(argv) + if args.dataset_type == "ecog": + if not args.ecog_config: + parser.error("--dataset_type ecog requires --ecog_config") + rejected = [name for name in ECOG_REJECTED if getattr(args, name) is not None] + rejected += ["use_volume"] if args.use_volume else [] + if rejected: + parser.error("fMRI-only options are not valid for --dataset_type ecog: " + + ", ".join(f"--{name}" for name in rejected)) + if args.lookback is None: + args.lookback = 256 # AbstractTrainer default + else: + for name in ("ecog_config", "alphas"): + if getattr(args, name) is not None: + parser.error(f"--{name} is only valid for --dataset_type ecog") + delattr(args, name) # keep the saved fMRI config/run hash unchanged + missing = [f"--{name}" for name in FMRI_REQUIRED if getattr(args, name) is None] + if missing: + parser.error("the following arguments are required: " + ", ".join(missing)) + for name, value in FMRI_DEFAULTS.items(): + if getattr(args, name) is None: + setattr(args, name, value) + return args + + +def _sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def run_ecog(config: Dict) -> AbstractTrainer: + """Run continuous ECoG through the existing ECoG Python API. + + The assembly comes from the ECoG manifest loader and preparation/CV come from + AbstractTrainer's ECoG branch; no fMRI downsampling, FIR or trimming is used. + """ + config_path = Path(config["ecog_config"]) + temporal = json.loads(config_path.read_text()) + if not isinstance(temporal, dict): + raise ValueError("--ecog_config must contain a JSON object") + + assembly = AssemblyGenerator.generate_assembly( + dataset_type="ecog", + data_dir=config["data_dir"], + subject=config["subject"], + lookback=config["lookback"], + context_type=config["context_type"], + ) + + # Reuse the fMRI CLI's extractor/model construction unchanged: setup_models + # only reads .config/.logger and sets .feature_extractors/.downsampler/.model. + # The Downsampler it creates is not passed on; ECoG alignment uses feature_specs. + components = SimpleNamespace(config=config, logger=logger) + UnifiedTrainer.setup_models(components) + + fit_options = {name: config[name] for name in ("n_outer_folds", "n_inner_folds", "alphas") + if config[name] is not None} + fit_options.update( + singcutoff=config["singcutoff"], use_gpu=config["use_gpu"], + single_alpha=True, normalpha=True, use_corr=True, + normalize_features=config["normalize_features"], + normalize_targets=config["normalize_targets"], + ) + + # Reproducibility record: the full temporal config and content hashes, + # with file names rather than absolute paths. + data_path = Path(config["data_dir"]) + manifest = data_path / "ecog.json" if data_path.is_dir() else data_path + paths = {"data_dir", "ecog_config", "vector_path", "cache_dir", "results_dir"} + run_config = {key: value for key, value in config.items() + if key not in paths and value is not None} + run_config.update( + entrypoint="unified.py", + encoding_model=components.model.model_name, + fit_options=fit_options, + ecog_temporal_config=temporal, + ecog_config_file=config_path.name, + ecog_config_sha256=_sha256(config_path), + manifest_file=manifest.name, + manifest_sha256=_sha256(manifest), + ) + if config.get("vector_path"): + run_config["vector_file"] = Path(config["vector_path"]).name + + trainer = AbstractTrainer( + assembly=assembly, + feature_extractors=components.feature_extractors, + downsampler=None, + model=components.model, + fir_delays=None, + trimming_config={}, + use_train_test_split=False, + layer_idx=config["layer_idx"], + lookback=config["lookback"], + dataset_type="ecog", + logger_backend=config["logger_backend"], + wandb_project_name=config["wandb_project_name"], + results_dir=config["results_dir"], + run_name=f"ecog-{config['subject']}-{datetime.now().strftime('%Y%m%d-%H%M%S')}", + result_metadata={"run_config": run_config}, + ecog_temporal_config=temporal, + ) + trainer.train(**fit_options) + logger.info(f"Results saved to {trainer.last_run_dir_}") + return trainer + + +def main(argv=None): """Main training function.""" - args = parse_args() + args = parse_args(argv) config = vars(args) if not config.get("modalities") and not config.get("modality"): @@ -530,6 +663,9 @@ def main(): config["modalities"] = [config["modality"]] if config.get("model_name") and not config.get("model_names"): config["model_names"] = [config["model_name"]] + + if config["dataset_type"] == "ecog": + return run_ecog(config) custom_trimming = {} trimming_params = [