# ICASSP 2027 EEG-sAAD Grand Challenge — team prediction package

This package writes one label CSV per subject for the blind test sets. Python and
MATLAB provide the same interface; use the language your decoder is written in.
Both run end to end as shipped, with the reference decoder in
`matlab/reference_decoder.mat`.

## What to do

1. **Fill `submission_metadata.yaml`.** `label_type`
   (`attended-speaker-label` / `attended-direction-label`), `code_public`, and
   `decoder_lookahead_ms` are required. Scoring reads them from the archive; a
   missing value, or a lookahead above 1000 ms, stops the run with a message
   naming the field.
2. **Put your decoder in the hook.**
   - Python: `challenge/hook/load_decoder.py` and `challenge/hook/decode_single_window.py`
   - MATLAB: `matlab/loadDecoder.m` and `matlab/decodeSingleWindow.m`
   - Either replace the body with your model, or keep the body and supply a
     `.mat` written by `matlab/packDecoder.m` — see
     [Taking your own trained decoder to inference](#taking-your-own-trained-decoder-to-inference).
   - A decoder that keeps state across the windows of a trial implements the
     reset in `reset_decoder.py` / `resetDecoder.m`; the shipped one returns
     the model unchanged.
   - Keep the total lookahead of your chain at or below 1000 ms: every read
     stays at or before the sample a label is assigned to.
3. **Run the pipeline.** It loads every trial, preprocesses it, calls the hook,
   and writes one CSV per subject. Run `challenge.run_predictions` or `runPredictions.m`.

### Python

Requires `numpy`, `scipy`, and `torch`.

`--data_dir` is the `dataCND` folder of one test set (`<set>/dataCND`). Input
`.mat` names carry the subject number without zero padding (`dataSub1.mat`);
output CSV names carry three digits (`test_sample_001.csv`). See
[Test sets](#test-sets) for the level of every path argument. Each set gets its
own output directory:

```
python -m challenge.run_predictions --data_dir <nju>/dataCND   --output_dir <out>/nju   --dataset nju
python -m challenge.run_predictions --data_dir <dlaad>/dataCND --output_dir <out>/dlaad --dataset dlaad
```

Both sets name their prediction files `test_sample_NNN.csv` and share seven
subject ids (1, 3, 5, 8, 10, 11, 12); a shared `--output_dir` overwrites the
first run's files. Separate output directories give the archive the `nju/` and
`dlaad/` folders it requires.

`--dataset` takes `nju`, `dlaad`, or `auto` (default). It selects the reader
class; both classes read the same files in `dataCND`. `auto` reads the last two
path components of `--data_dir` and requires `nju` or `dlaad` in them;
otherwise the run stops and asks for the flag. Subject ids come from the `.mat`
file names in `dataCND`, not from this flag.

### MATLAB

```matlab
addpath('<test package>/matlab');
addpath('<training package>/functions');    % loadSubject, timeDelayEmbedding, expandToSamples, resolveChannelSet
runPredictions('<nju>/dataCND',   '<out>/nju',   'NJUSUSTech2026');
runPredictions('<dlaad>/dataCND', '<out>/dlaad', 'DLAAD2021');
```

`<training package>` is the `TOPUBLISH-crossDataset-example` folder.

`dataDir` is the `dataCND` folder of one test set (`<set>/dataCND`).
`datasetName` is recorded in the loader's `info.dataset` and in its verbose
output; file discovery uses `dataDir` and the
file prefixes. Both sets are read the same way. Pass `preprocessing` (fourth
argument) to override the `loadSubject` options. Every `dataCND` folder holds
the raw pair (`dataSub`/`dataStim`, 128 Hz) next to the preprocessed pair
(`pre_dataSub`/`pre_dataStim`, 32 Hz); the default reads the preprocessed pair,
and `filePrefixes` (fifth) selects the raw pair for your own preprocessing.
Input `.mat` names carry the subject number without zero padding
(`dataSub1.mat`); `runPredictions` writes `test_sample_NNN.csv` with three
digits. A shared output directory overwrites the first run's files; keep
`<out>/nju` and `<out>/dlaad` separate for the archive. The MATLAB plug-in
points are `matlab/loadDecoder.m` (how the model is loaded),
`matlab/decodeSingleWindow.m` (one decision window in, one label out) and
`matlab/resetDecoder.m` (the state reset before every trial's first window);
`decodeTrial.m` runs the decision grid, the per-window slicing and the label
expansion around them.

## Settings

`reference_decoder.mat` supplies every setting below to the Python and MATLAB
pipelines, except the output grid, which both pipelines fix at 128 Hz
(`labelFs` in `matlab/config.m`, `LABEL_FS` in `challenge/config.py`).

| step            | setting                                     | field                                                             |
| --------------- | ------------------------------------------- | ----------------------------------------------------------------- |
| input files     | `pre_dataSub` / `pre_dataStim` at 32 Hz | `challenge/run_predictions.py` `resolve_prefixes`, `runPredictions>resolvePrefixes` |
| channels        | 58-channel intersection set, by label       | `preprocessing.channelSelection`                                |
| re-referencing  | `CAR`                                     | `preprocessing.reReference`                                     |
| rate            | 32 Hz                                       | `preprocessing.targetFs`, `fs`                                |
| normalisation   | per-trial `zscore`, EEG and features      | `preprocessing.normEEG` / `normFeatures`                      |
| EEG lags        | `Leeg = [0 0.4]` s → 14 lags at 32 Hz    | `Leeg`                                                          |
| bias column     | none                                        | `bias`                                                          |
| decision window | 1 s                                         | `windowSeconds` in the decoder; `WINDOW_SECONDS` / `cfg.windowSeconds` override |
| window hop      | 1 sample                                    | `HOP_SAMPLES` / `cfg.hopSamples`                                |
| expansion       | `lookahead = 1000 ms`                     | `MAX_LOOKAHEAD_MS` / `cfg.maxLookaheadMs`                        |
| output grid     | 128 Hz, zero-order hold                     | `LABEL_FS` / `cfg.labelFs`                                        |

`matlab/config.m` sets `cfg.windowSeconds = 1`; `challenge/config.py` sets
`WINDOW_SECONDS = None`. The shipped decoder records 1 s, so both pipelines read
the same grid. `[]` in MATLAB and `None` in Python take the decoder's value; a
number overrides it with a warning.

The 128 Hz files supply each trial's native length.

## Test sets

Each set is a folder whose `dataCND/` subfolder holds four files per subject:
`dataSubN.mat`, `dataStimN.mat`, and their `pre_` copies at 32 Hz. Input `.mat`
names carry the subject number without zero padding; prediction CSV names carry
it as three digits.

```
<parent>/
└── <set>/
    └── dataCND/
        ├── dataSub1.mat
        ├── dataStim1.mat
        ├── pre_dataSub1.mat
        ├── pre_dataStim1.mat
        └── ...
```

`<parent>` and `<set>` are folder names you choose. The pipeline reads the
`dataCND/` folder passed to it. Subject ids come from the `.mat` file names in
that folder. `--dataset auto` requires `nju` or `dlaad` in the last two path
components of `--data_dir`; pass `--dataset` explicitly when the folder has
another name.

| argument | points at |
| -------- | --------- |
| `--data_dir` (Python), `dataDir` (MATLAB) | `<set>/dataCND` |
| `--output_dir`, `outputDir` | one folder per set (`<out>/nju`, `<out>/dlaad`) |
| `--submission_dir` (`check_format.py`) | folder holding `submission_metadata.yaml`, `nju/`, `dlaad/` |
| `--nju_data`, `--dlaad_data` (`check_format.py`) | the `dataCND` folder of each set, with the 128 Hz `dataStimN.mat` files |
| `makeReference(..., trainRoot)` | the training package root (`TOPUBLISH-crossDataset-example/`) |
| `makeReference(..., dataRoot)` | folder holding the four training dataset folders, each with `dataCND/` |

```
python -m challenge.check_format --submission_dir <submission folder> \
    --nju_data <nju set>/dataCND --dlaad_data <dlaad set>/dataCND
```

| set            | `--dataset` | subjects              | trials per subject | trial length | channels            |
| -------------- | ----------- | --------------------- | ------------------ | ------------ | ------------------- |
| NJUSUSTech2026 | `nju`       | 12 (1–12)             | 10                 | 300 s        | 64 in file, 58 used |
| DLAAD2021      | `dlaad`     | 19 (1, 3, 5, … 42)   | 6–36              | 60 s        | 64 in file, 58 used |

Every NJU trial is 38 400 samples at 128 Hz. Every DLAAD trial is 7680 samples
at 128 Hz (60 s). Each subject's CSV holds one row per
sample of that subject; `challenge/check_format.py` verifies the whole submission
and stops at the first violation. It needs only `numpy` and `scipy`.

## The hook interface

Both languages expose the same three plug-in points; the fixed decode loop
around them calls all three:

| plug-in point | Python | MATLAB |
|---------------|--------|--------|
| load the model, once per run | `load_decoder()` | `loadDecoder()` |
| reset the state, once per trial | `reset_decoder(model)` | `resetDecoder(model)` |
| decode one decision window | `decode_single_window(model, window_index, starts, fs, seg_len, hop_samples, neural_current, stim_current, neural_past, stim_past, past_labels)` | `decodeSingleWindow(model, windowIndex, starts, fs, segLen, hopSamples, neuralCurrent, stimCurrent, neuralPast, stimPast, pastLabels)` |

The fixed decode loop is `decode_trial(model, neural, stim, fs, lengths=None)`
in Python — one trial, or a padded batch where `lengths` carries each trial's
sample length — and `decodeTrial(model, neural, stim, fs)` in MATLAB — one
trial per call. Both return **one label per sample they received**, at `fs`,
in input order:

| argument | shape | meaning |
|----------|-------|---------|
| `model` | — | what `load_decoder.py` / `loadDecoder.m` returned; the pipeline loads it once |
| `neural` | `(channels, samples)`; Python also accepts `(batch, channels, samples)` | preprocessed EEG |
| `stim` | `(streams, samples)`; Python also accepts `(batch, streams, samples)` | preprocessed envelopes |
| `fs` | scalar | sampling rate after preprocessing |
| `lengths` | Python only: `(batch,)` or `None` | sample length of each trial when padded |

The pipeline holds those labels zero-order onto the 128 Hz grid of the
original recording and writes the CSV.

Labels are 0 or 1. Their meaning is the `label_type` you declare:

- `attended-speaker-label` — the index of the attended stream, in the order the
  streams arrive.
- `attended-direction-label` — the attended side, 0 for the left-most position of
  the trial and 1 for the right-most.

The shipped metadata says `attended-speaker-label`; the shipped decoder returns
the winning stream index.

Output order = input order. The total lookahead of your chain — model,
windowing, any post-processing — must be at most 1000 ms; `decoder_lookahead_ms`
reports it.

The pipeline owns preprocessing and passes the arrays straight to the hook.
Everything after preprocessing — feature construction, windowing, post-processing
— is inside the hook.

## Writing the Python hook

`challenge/hook/` splits the decode path one function per file. Two files are
yours to edit:

1. `load_decoder.py` — how the model is loaded, once per run.
2. `decode_single_window.py` — one decision window in, one label out: it
   receives the model, the resolved grid, the current window, everything
   before the window, and the labels already emitted.

A decoder that keeps state across the windows of a trial also edits
`reset_decoder.py`: the state reset the pipeline runs before every trial's
first window. The shipped one returns the model unchanged.

The pipeline loads the model once (`load_decoder.py`) and passes it in;
`decode_trial.py` is fixed: it resets the model at the start of every trial,
takes the model, one trial or a padded batch, keeps the input order, resolves
the grid, slices every window, and runs each through `decode_single_window`
and `expand_to_samples`. A model that already emits per-sample labels still
goes in `decode_single_window`.

The decision window defaults to `reference_decoder.mat` (`window_seconds`); the
hop defaults to one sample. Both are hyperparameters of the decoding, held in
the package config: `WINDOW_SECONDS` / `HOP_SAMPLES` in `challenge/config.py`,
`windowSeconds` / `hopSamples` in `matlab/config.m`.
`WINDOW_SECONDS = None` uses the decoder file's value; a number overrides it
with a warning. Legal range for the hop: one sample to `window_seconds`
(overlapping windows included), verified in both languages. The linear
baseline needs no retraining under a different grid; models whose input size
is tied to the window length do. Keep the window at or below 60 s: the
shortest test trial is 60 s, and a longer window takes one guess for the
whole trial.

## Writing the MATLAB hook

`matlab/` mirrors the Python split, one function per file. Three files are
yours to edit:

1. `loadDecoder.m` — how the model is loaded, once per run: it caches in a
   persistent variable, `runPredictions.m` calls it and passes the returned
   `model` down through `decodeTrial.m` to `decodeSingleWindow.m`.
2. `decodeSingleWindow.m` — one decision window in, one label out:

   | argument | meaning |
   |----------|---------|
   | `model` | what `loadDecoder()` returned |
   | `windowIndex` | 1-based index of the current window; the first window of a trial is 1 |
   | `starts` | 1-based first sample of every window of the trial; window `windowIndex` spans `starts(windowIndex) : starts(windowIndex) + segLen - 1`; the entries before it are the previous windows of the trial |
   | `fs` | sampling rate of the inputs |
   | `segLen`, `hopSamples` | the resolved grid: window length and step, in samples |
   | `neuralCurrent`, `stimCurrent` | `(n_channels x segLen)` / `(n_streams x segLen)` — the current window |
   | `neuralPast`, `stimPast` | `(n_channels x starts(windowIndex)-1)` / `(n_streams x ...)` — everything before the current window |
   | `pastLabels` | the labels already emitted for the previous windows, in window order (empty for the first window) |

   The shipped body is the linear baseline: lagged embedding of the current
   window with `timeDelayEmbedding`, reconstruction with `model.W`,
   `windowCorrelation` against every candidate envelope over the window span,
   largest wins. Ties resolve to the lowest index, and the returned label is
   the 0-based stream index.
3. `resetDecoder.m` — the state reset `decodeTrial.m` runs before every
   trial's first window (`windowIndex == 1`); the shipped one returns the
   model unchanged.

`decodeTrial.m` is fixed: it resets the model, resolves the decision grid
from `config.m` (`windowSeconds`: empty uses the value in the model, a number
overrides it with a warning; `hopSamples`: the hop in samples, default 1),
slices every window, and expands the window labels onto samples with
`expandToSamples`. MATLAB decodes one trial per call — no padded batches;
`runPredictions.m` loops over subjects and trials and writes the CSVs.

The training functions (`timeDelayEmbedding`, `expandToSamples`) come from
the training package: `addpath('<training package>/functions')` before
decoding. `runPredictions` stops and names what is missing. The other
helpers of the package — `checkDecoder.m` (model validation at load time),
`guessLabel.m` and `lcgStep.m` (the deterministic guess), `windowCorrelation.m`
(the per-window correlation) — are fixed.

## The window grid and the previous windows

`window_starts(n_samples, seg_len, hop_samples)` is the standard
window grid: window `k` spans `starts[k] : starts[k] + seg_len`
(0-based). `decodeTrial` decodes the same windows through
`decodeSingleWindow` with 1-based indexing (`starts(windowIndex)` is that
window's first sample); the entries before the current one are the previous
windows of the trial. Each call receives the current window, everything before it,
and the labels already emitted; a sequential decoder — a causal HMM over the
per-window scores, for example — reads the previous windows from those
arguments inside the plug-in point.

A trial is decoded independently of every other trial. Any state a sequential
decoder keeps across the windows of one trial has to be back at its trained
initial value at the trial's first window, where the pipeline runs the reset
(`reset_decoder.py` / `resetDecoder.m`) — a test trial must not carry
information into the next one. The model itself loads once per run.

## Samples that carry no decision

The CSV needs one row per sample. A window's label is assigned to the sample
1000 ms before the window ends. Samples before the first assignment, and every
sample of a trial shorter than one window, take **one guess per block**:
uniform over `{0, 1}`, deterministic, seeded from the trial's own content. The
hop sets the spacing: with `hop = window length` each label covers one window
span; with `hop = 1` sample the label is assigned to a single sample.

## The lagged design matrix

`time_delay_embedding` in `challenge/hook/time_delay_embedding.py` (Python) and
`timeDelayEmbedding.m` (MATLAB, from the training package) take the signal
**time × channels** and return a design matrix whose columns are **channel-major**,
each channel's lags running from the end of the window down to its start
(`toeplitz` order). `W` is indexed by that column order.

## Output format

One `test_sample_NNN.csv` per subject:

```
time_index,label,trial
0,0,0
1,0,0
...
```

`time_index` and `trial` are 0-based; `time_index` restarts at 0 for every
trial. `label` is 0 or 1 and means what `label_type` declares — see
[the hook interface](#the-hook-interface).

For `attended-direction-label`: NJU places its streams at −30 and +30 degrees;
DLAAD uses −45, 0 and +45 for two streams; the 0-degree stream is the left-most
one in a trial whose other stream sits at +45, and the right-most one when the
other sits at −45.

Both pipelines reject a label outside {0, 1} before writing a file.

## Submission structure

Zip these items **at the top level**:

```
submission.zip
├── submission_metadata.yaml
├── nju/
│   ├── test_sample_001.csv
│   └── …
└── dlaad/
    ├── test_sample_001.csv
    └── …
```

- Both `nju/` and `dlaad/` are required, each with one file per subject of that
  set. A missing subject, a missing set, or an unexpected subject id fails
  scoring.
- `submission_metadata.yaml` stays at the root. Its `label_type` selects which
  reference labels the predictions are scored against.
- File names are `test_sample_NNN.csv`; subject ids come from the blind data and
  are not always consecutive (`dlaad` runs 001, 003, 005, …); take them from
  the data or let the pipeline name the files.

From the folder holding those three items:

```
zip -r submission.zip submission_metadata.yaml nju dlaad
```

## Reference decoder

`matlab/reference_decoder.mat` holds 58 channels × 14 lags, fitted on 1880 trials
from 82 subjects across the four non-blind training sets, with the backward
(stimulus-reconstruction) model and Ledoit–Wolf covariance regularisation
(`trainLinearDecoder`, `computeLedoitWolf` in the training package).
`matlab/makeReference.m` refits it and prints how far its own `W` differs from the
shipped one.

The weights are loaded once per run (`loadDecoder.m` / `load_decoder`) and passed
through `decodeTrial.m` / `decode_trial` to the window decoder; the design matrix is
built, the attended envelope reconstructed, and the candidate stream whose
envelope correlates best in each window wins.

To ship your own weights in the same file, keep these fields:

| field                             | meaning                                                                                                                                    |
| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `W`                             | `n_channels * n_lags` (+1 with bias) rows, one column: channel-major, each channel's lags in the order `timeDelayEmbedding` emits them |
| `Leeg`                          | `[start end]` lag window in seconds                                                                                                      |
| `bias`                          | whether the design matrix carries a constant column                                                                                        |
| `fs`                            | rate the lags are quantised on                                                                                                             |
| `windowSeconds`                 | decision window the model was fitted under; `WINDOW_SECONDS` / `windowSeconds` in the config overrides it                                |
| `hopSeconds`                    | recorded with the file; the inference hop comes from `HOP_SAMPLES` / `hopSamples` in the config                                          |
| `channelLabels`                 | one label per channel `W` expects                                                                                                        |
| `preprocessing`                 | the `loadSubject` options the weights were fitted under; the pipeline reads them from here (optional)                                    |

Both readers check the first seven fields before decoding and name the missing
or inconsistent field; a missing `preprocessing` falls back to the `loadSubject`
defaults. Three more checks run before the first decision:

| check                                                        | what it rejects                                                                     |
| ------------------------------------------------------------ | ----------------------------------------------------------------------------------- |
| `fs` vs `model.fs`                                       | decoding at a rate other than the one the lags were quantised on                    |
| `channelLabels` vs the channels the preprocessing produced | the right number of channels in another order (`W` is indexed by column position) |
| `stim` streams > 2                                         | a multi-stream decision in a 0/1 column                                             |

### Reproducing the shipped baseline decoder

Optional. Reads the four training sets and writes one `.mat`.

```matlab
addpath('<package>/matlab');
makeReference('<somewhere>/my_decoder.mat', ...
              '<training package>', ...
              '<dataRoot>');
```

`outFile` is the `.mat` to write, `trainRoot` is the
`TOPUBLISH-crossDataset-example` folder, and `dataRoot` is the folder that
contains the four dataset folders (`KUL_AAD_UltraHD2021`, `DTU2018`, `USTC2026`,
`KUL2016`), each with its `dataCND/` subfolder. Name-value: `maxSubjects` (default
all), `verbose`, `referenceFile`.

The configuration comes from `reference_decoder.mat`; the fit is the training
package's. Five checks on the arguments, each naming the problem:

| check                               | meaning                                              |
| ----------------------------------- | ---------------------------------------------------- |
| `makeReference:noReference`       | `referenceFile` is missing                         |
| `makeReference:noTrainPackage`    | `trainRoot` has no `functions/` folder           |
| `makeReference:staleTrainPackage` | that copy is missing a function the fit needs        |
| `makeReference:noTrainingData`    | `dataRoot` does not hold the four dataset folders  |
| `makeReference:wouldOverwrite`    | `outFile` is the shipped `reference_decoder.mat` |

The run ends with:

```
vs shipped .../reference_decoder.mat: max|dW| = 0, channel order identical
```

`0` means the same fit; small values are last-bit floating point differences. The four
training sets are listed inside the script.

### Taking your own trained decoder to inference

**1. Replace the decoder function.** Both languages split the plug-in into
the same three edit points: loading the model (`load_decoder.py` /
`loadDecoder.m`, once per run), the state reset before every trial's first
window (`reset_decoder.py` / `resetDecoder.m`; the shipped one returns the
model unchanged), and decoding one window (`decode_single_window.py` /
`decodeSingleWindow.m`, one decision window in, one label out). The data one
window call receives: everything before the window and the window itself. The
`decode_trial` / `decodeTrial` wrappers expand the window labels onto one
label per sample.

**2. Ship the weights in the `.mat`.** `matlab/packDecoder.m` writes the format
this package reads:

```matlab
decoder = packDecoder(d, params, layout, windowHop, provenance);
save('my_decoder.mat', '-struct', 'decoder');
```

`d` is the weight vector (`p x 1`); `params` carries `Leeg`, `bias`,
`windowLengths`, `regularization` (a struct with field `name`) and
`preprocessing`; `layout` carries `fs`, `chanLabels` and `streamNames`;
`windowHop` is the hop in seconds, one entry per window length. Copy the
result over `matlab/reference_decoder.mat`. From Python, write the same
fields with `scipy.io.savemat`.

`crossDatasetMain.m` writes label CSVs. To write a decoder file, use
`packDecoder.m`.

Four things must match the shipped file: lag layout, channel order, rate,
decision grid.

### Training CSVs and test-phase CSVs differ

- **Grid.** The training export writes `round(nIn*128/32)` rows per trial; the
  test pipeline reads each trial's native 128 Hz length from `dataStimN.mat`.
- **Decision window.** The training demo runs a 50 s window; the baseline uses
  1 s.
- **Lookahead.** Both default to 0: `runHMMPostprocessor` fills
  `.HMM.causality.lookaheadSeconds = 0` when it is absent. A training run that
  sets it, a decoder that reads ahead of the labeled sample, or post-processing
  that buffers ahead all add to `decoder_lookahead_ms`, whose limit is 1000 ms.

The baseline declares **1000 ms**. The decoder reads 13
samples = 406.25 ms past the current sample (`Leeg = [0, 0.4]`;
`timeDelayEmbedding` takes a positive lag that way). Window k's label is
assigned 1000 ms before the window ends; the latest usable window wins, and
the hop sets the spacing. With the shipped 1 s window and 1-sample hop, every
sample carries the decision of the window ending one second after it, and no
sample takes a guess.

`matlab/windowCorrelation.m` holds the re-centred correlation;
`challenge/hook/window_correlation.py` is its Python counterpart, and
`evaluateWindows.m` in the training package keeps the same rule as a local
function. The window grid itself lives in `challenge/hook/window_starts.py`
and `matlab/windowStarts.m`; both build it and hand `starts` to the window
decoder.

## Package layout

```
challenge/
  __init__.py
  config.py      package-level constants (submission grid, decision-grid
                 overrides, the 1000 ms lookahead limit, file names, prefixes)
  datasets.py    torch Dataset per test set, batch collation
  run_predictions.py
                 loading loop, format checks, CSV writer
  io_cnd.py      loadSubject-equivalent preprocessing
  check_format.py  submission self-check (run before zipping)
  hook/          the decode path, one function per file:
                   load_decoder.py + decode_single_window.py are the team
                   edit points, reset_decoder.py the optional one (state
                   reset per trial); decode_trial.py, window_starts.py,
                   lcg_step.py, expand_to_samples.py, guess_label.py,
                   time_delay_embedding.py, window_correlation.py are fixed
matlab/
  runPredictions.m           run one test set
  decodeTrial.m               fixed decode loop: model reset, decision grid,
                             per-window calls, label expansion
  loadDecoder.m              your model loading (once per run)
  decodeSingleWindow.m       your decoder (one window in, one label out)
  resetDecoder.m, windowStarts.m, checkDecoder.m, guessLabel.m, lcgStep.m
  config.m                   package-level constants
  reference_decoder.mat
  packDecoder.m              write a decoder file
  makeReference.m            refit the baseline (optional)
  windowCorrelation.m
```

All package-level constants — the submission grid, file names, prefixes —
live in one place: `challenge/config.py` (Python) and
`matlab/config.m` (MATLAB). The functions read from there; a
change applies everywhere at once.

`loadSubject.m`, `timeDelayEmbedding.m`, `expandToSamples.m` and
`resolveChannelSet.m` come from the training package's `functions/` folder (the
`addpath` above). `challenge/io_cnd.py` and the modules under `challenge/hook/`
are their Python counterparts.

Entry points are `runPredictions.m` / `challenge.run_predictions` (run the test sets)
and `makeReference.m` (refit the baseline); everything else is called by them or
by your decoder.

Two rates appear here: `preprocessing.targetFs` (32 Hz) is the rate the EEG is
**decoded** at and the rate the lags are quantised on; `LABEL_FS` in
`challenge/config.py` and `labelFs` in `matlab/config.m` (128 Hz) is the rate
the CSV is **written** at, the grid of the reference labels.
