Skip to content
114 changes: 114 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,120 @@ 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.

#### 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:
Expand Down
1 change: 1 addition & 0 deletions encoding/assembly/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
from .assemblies import SimpleNeuroidAssembly
from .assembly_loader import load_assembly, save_assembly, AssemblyLoader
from .ecog_processor import ECoGAssemblyGenerator
17 changes: 16 additions & 1 deletion encoding/assembly/assemblies.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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"]
Expand Down
56 changes: 38 additions & 18 deletions encoding/assembly/assembly_generator.py
Original file line number Diff line number Diff line change
@@ -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:
Expand All @@ -27,27 +22,42 @@ 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

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,
Expand All @@ -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
Expand All @@ -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,
Expand All @@ -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,
Expand Down
Loading