coco_pipe.io.embeddings#

BIDS-compatible derivative I/O for foundation-model embeddings.

Functions#

embedding_label(label, *[, seed, pooling, transform])

Return the desc label of embeddings made from label's data.

embedding_path(root, label, view, *[, recording_id, ...])

Return the BIDS path of an embedding file.

write_recording_embeddings(results, root, *, label, ...)

Write one recording's embeddings, one file per view.

embeddings_up_to_date(recording, written)

Return whether a recording's embedding files are written and up to date.

write_embedding_dataset(root, descriptions, *, name, ...)

Write the dataset files of an embedding derivative and its sidecars.

write_embedding_manifest(root, label, records)

Write the run records of one label: its skipped and failed recordings.

find_embeddings(root, label, view, *[, subjects])

Return the per-recording embedding files of one label and view.

load_embeddings(source, *[, representation, ...])

Load embedding files into a DataContainer.

consolidate_embeddings(files, root)

Write recordings' embedding files as one file at the dataset root.

write_transformed_embeddings(source, embeddings, root, ...)

Write transformed embeddings as one file holding every recording.

Module Contents#

coco_pipe.io.embeddings.embedding_label(label, *, seed=None, pooling='mean', transform=None)#

Return the desc label of embeddings made from label’s data.

The label of the data embedded, then Random<seed> for random weights, the pooling’s name for window vectors pooled otherwise than by the mean, and the label of a subject transform: "base", "baseRandom3", "baseAttention", "baseRandom3EaCoralCh". The writers name their files with it.

Parameters:
  • label (str) – The label of the data embedded, e.g. "base" for epochs labelled desc-base.

  • seed (int, optional) – The seed of random weights; None for pretrained weights.

  • pooling (str) – The pooling of window vectors; only window files take it.

  • transform (str, optional) – The label of a subject transform, e.g. EuclideanAlign’s.

Return type:

str

Raises:

ValueError – If label or the result is not a BIDS label.

coco_pipe.io.embeddings.embedding_path(root, label, view, *, recording_id=None, task=None, datatype='eeg')#

Return the BIDS path of an embedding file.

A file is named <entities>_desc-<label>_<view>embeddings.nc. With recording_id it holds one recording and sits in its subject (and session) folder; without it, it holds every recording and sits at the dataset root, named by task when one is given.

Parameters:
  • root (path-like) – The derivative dataset, e.g. derivatives/coco-pipe-cbramod.

  • label (str) – The desc label, e.g. "base" or "baseRandom0EaCoral" (see embedding_label()). A BIDS label: letters, digits and +.

  • view (str) – One of EMBEDDING_VIEWS.

  • recording_id (str, optional) – A recording’s BIDS entities, as the BIDS loader’s recording_id coordinate holds them, e.g. "sub-01_ses-01_task-rest_run-01".

  • task (str, optional) – The task of a file holding every recording. A recording’s file takes its task from recording_id.

  • datatype (str) – The BIDS datatype folder of a recording’s file, e.g. "eeg".

Returns:

The file’s path, without checks for BIDS suffixes; .fpath is the file.

Return type:

BIDSPath

Raises:

ValueError – If label is not a BIDS label, view is not an embedding view, recording_id is not a recording’s entities, or both recording_id and task are given.

coco_pipe.io.embeddings.write_recording_embeddings(results, root, *, label, source, source_dataset, bad_channels=(), token_dtype='float32', skip_up_to_date=False)#

Write one recording’s embeddings, one file per view.

Each view the results hold (window_embeddings, token_embeddings, and so on, see EMBEDDING_VIEWS) goes to its own file, named by embedding_path() after the source recording, with the label embedding_label() gives for the weights and pooling: e.g. baseRandom3 for random weights of seed 3. The window vectors of each other pooling (extra_window_embeddings, e.g. REVE’s attention read-out) go to a window file of their own label (baseAttention), whose settings name that pooling. A file holds every condition, its windows in epoch order. Nothing is written if any check fails, and each file is written to a temporary name and then moved into place, so an existing file is replaced whole or not at all.

Parameters:
  • results (mapping of str to FoundationEmbeddingResult) – The extractor’s result for each condition of the recording. Its window_index holds the epoch numbers.

  • root (path-like) – The derivative dataset, e.g. derivatives/coco-pipe-cbramod.

  • label (str) – The label of the data embedded, e.g. "base" for epochs labelled desc-base.

  • source (path-like) – The file the epochs were read from, in its datatype folder of a BIDS dataset: the source coordinate of the BIDS loader’s rows, or a BIDSPath’s fpath. Its entities name the recording, and the embedding files go in the same datatype folder.

  • source_dataset (str) – The name of the source dataset in DatasetLinks, e.g. "preproc", for the BIDS URI of source.

  • bad_channels (str | sequence of str) – The recording’s bad channels, or the BIDS loader’s bad_channels coordinate (comma-separated).

  • token_dtype ({"float32", "float16"}) – The dtype of the token file; "float16" halves its size. The other views are float32.

  • skip_up_to_date (bool) – Keep a file that already holds the same windows with the same config_hash, as embeddings_up_to_date() tells, instead of replacing it. Its values are not compared.

Returns:

The path of each label and view, e.g. paths["baseRandom3", "window"].

Return type:

dict of (str, str) to BIDSPath

Raises:

ValueError – If the conditions come from different models or settings (their config_hash), differ in views, poolings, feature size or channels, hold non-finite values or share epoch numbers, if a channel axis does not match model_channels, if a pooling’s name is not letters and digits, if label is not a BIDS label, if source is not a file in a datatype folder of a subject, or if token_dtype is not "float32" or "float16".

Notes

The embeddings variable holds the view, as float32 (tokens as token_dtype; values beyond float16’s range are refused). Along window are the coordinates obs (<recording_id>_epoch-NNNN, as the BIDS loader names observations), recording_id, subject, session, task, run, condition, epoch, start and stop. Along recording are its source (a BIDS URI), sampling rate, channels, bad channels and the channels the model interpolated, zero-filled or dropped. A view with a channel axis names it with the channel coordinate: the channels the model saw (model_channels). The attributes are model_key, config (the extraction settings that are the same for every recording, as JSON text, see EMBEDDING_CONFIG_KEYS), config_hash (their hash) and description (the file’s label); a token file adds token_source and token_feature_axis, the other token axes being the observation axes. Other metadata in the results is not stored.

coco_pipe.io.embeddings.embeddings_up_to_date(recording, written)#

Return whether a recording’s embedding files are written and up to date.

written is what write_recording_embeddings() returned for another recording of the same model and settings. recording is up to date when it has each of those files, holding its windows (condition and epoch, from the BIDS loader’s rows) with the config_hash of the file written: a file of other windows or settings (another model revision, pooling and so on) is not. A resubmitted job uses it to skip the recordings that need no extraction.

Parameters:
  • recording (DataContainer) – The BIDS loader’s rows of one recording.

  • written (mapping of (str, str) to BIDSPath) – The files written for another recording, by label and view.

Return type:

bool

coco_pipe.io.embeddings.write_embedding_dataset(root, descriptions, *, name, dataset_links, authors=())#

Write the dataset files of an embedding derivative and its sidecars.

Writes dataset_description.json, README.md, descriptions.tsv and its descriptions.json, and .bidsignore (keeping lines already there). descriptions.tsv lists the label of each top-level embedding file (one holding every recording): what its data is, from descriptions, then its weights, pooling and transform, from its settings. Each such file gets a JSON sidecar of the same name, holding the file’s extraction settings (its config attribute), its config_hash as ConfigHash and a Description. By BIDS inheritance a sidecar also applies to the recording files of the same label and suffix. Every file is replaced atomically and comes out the same whoever calls on the same files, so several jobs may call this on one dataset.

Parameters:
  • root (path-like) – The derivative dataset, e.g. derivatives/coco-pipe-cbramod.

  • descriptions (mapping of str to str) – What the data of each label embedded is, e.g. {"base": "Every epoch of the preprocessed recordings"}: the label given to the writers, not the labels embedding_label() makes from it.

  • name (str) – The dataset’s Name.

  • dataset_links (mapping of str to str) – Each source dataset’s name and location, e.g. {"preproc": "../preproc"}: the DatasetLinks that resolve the BIDS URIs of the recordings’ sources, also listed as SourceDatasets.

  • authors (sequence of str) – The dataset’s Authors.

Returns:

The files written.

Return type:

list of Path

Raises:

ValueError – If a label or link name is not valid, a description holds a tab or a line break, or a top-level embedding file has a label no label of descriptions gives with its settings, a label other than the one it holds, an unknown view, no config or one that does not match its config_hash, sources in a dataset dataset_links does not name, or another model than the other files.

coco_pipe.io.embeddings.write_embedding_manifest(root, label, records)#

Write the run records of one label: its skipped and failed recordings.

Each label has its own file, desc-<label>_manifest.json at the dataset root, written by the job that makes the label, so jobs writing other labels of the dataset never replace it. Nothing reads it to find embedding files. The file is replaced atomically.

Parameters:
  • root (path-like) – The derivative dataset, e.g. derivatives/coco-pipe-cbramod.

  • label (str) – The desc label the records belong to.

  • records (iterable of mapping) – One record per recording, e.g. its recording_id, status and reason.

Return type:

Path

coco_pipe.io.embeddings.find_embeddings(root, label, view, *, subjects=None)#

Return the per-recording embedding files of one label and view.

The files are found on disk with mne_bids.find_matching_paths(), never through a manifest. The files at the dataset root, which hold every recording, are not returned.

Parameters:
  • root (path-like) – The derivative dataset, e.g. derivatives/coco-pipe-cbramod.

  • label (str) – The desc label, matched whole: "base" does not find the "baseRandom0" files.

  • view (str) – One of EMBEDDING_VIEWS.

  • subjects (str or sequence of str, optional) – The subject labels to find, without sub-; every subject when omitted.

Returns:

The files, sorted by path; empty when none match.

Return type:

list of BIDSPath

Raises:
coco_pipe.io.embeddings.load_embeddings(source, *, representation='epoch', conditions=None, subjects=None, subject_metadata_df=None, subject_key=None)#

Load embedding files into a DataContainer.

The files are read one at a time into one float32 array, so memory holds the result and a block of 1,024 windows of one file. Only the windows of conditions and subjects are read.

Parameters:
  • source (path-like or BIDSPath, or a sequence of them) – Embedding files of one model, label and view: one file holding every recording, or recordings’ files (see find_embeddings()).

  • representation ({"epoch", "recording"}) – "epoch": one row per window. "recording": one row per recording and condition, the mean of its windows.

  • conditions (str or sequence of str, optional) – The conditions to load; every condition when omitted.

  • subjects (str or sequence of str, optional) – The subjects to load, labels without sub-; every subject when omitted. A subject no file holds is not an error.

  • subject_metadata_df (DataFrame, optional) – Subject-level metadata to attach, in addition to participants.tsv.

  • subject_key (str, optional) – The column of subject_metadata_df holding the subject ID. It matches rows to subjects and is not attached itself.

Returns:

X is float32, with the file’s axes and window renamed obs: ("obs", "feature") for window and cov files, and channel, time_patch or the model’s token axes before feature for the others. ids is obs. Along obs are the file’s window coordinates (recording_id, subject, session, task, run, condition, epoch, start, stop), each recording’s bad_channels and each subject’s metadata: the columns of participants.tsv, found in the files’ dataset or, following SourceDatasets, in a dataset it comes from (see load_participants_tsv()), and those of subject_metadata_df. session and run are dropped when no recording has one. A channel axis keeps its channel names. meta holds model_key, config, config_hash, description (the label), view, representation, files, recordings (each loaded recording’s row of the files’ recording table) and, for tokens, token_source and token_feature_axis.

Return type:

DataContainer

Raises:

ValueError – If source names no file or a file that is not an embedding file; if the files differ in model, settings (config_hash), label, view, axes, shape, token layout or channel names; if a condition is in no file, no window is selected, an observation appears twice or a value is not finite; if subject_metadata_df comes without subject_key, or a subject metadata column is named like a coordinate the loader sets.

Notes

The recording level is the mean of the window vectors as stored, which are L2-normalised when the extractor normalises them; its obs is <recording_id>_cond-<condition> and epoch_count holds the number of windows. Channel axes that hold the same channels in another order are put in the first file’s order.

coco_pipe.io.embeddings.consolidate_embeddings(files, root)#

Write recordings’ embedding files as one file at the dataset root.

The file is named by embedding_path() from the files’ label and view, with their task when they all have the same one. It holds their windows in the order of files, their recording tables and their attributes, and reads back with load_embeddings() as the files do. The files are copied one at a time, so memory holds one of them; the embeddings keep their dtype. The file is written to a temporary name and then moved into place, so nothing is left if a check fails.

Parameters:
  • files (sequence of path-like or BIDSPath) – Embedding files of one model, label and view, e.g. from find_embeddings().

  • root (path-like) – The derivative dataset, e.g. derivatives/coco-pipe-cbramod.

Returns:

The file written.

Return type:

BIDSPath

Raises:

ValueError – As load_embeddings(): if files is empty or names a file that is not an embedding file, if the files cannot be combined, if an observation appears twice or a value is not finite.

coco_pipe.io.embeddings.write_transformed_embeddings(source, embeddings, root, *, transform, fitted_on=None, view=None, token_dtype='float32')#

Write transformed embeddings as one file holding every recording.

source is what load_embeddings() returned for one label and view, one row per window, and embeddings its transform, row for row: of the same shape for a transform that keeps it (EuclideanAlign, LeaceEraser), or (window, feature) with view="cov" for RiemannAlign’s tangent vectors. The file keeps the windows, the recordings and the channels of source; its settings are those of source with Transform added, so its config_hash differs, and without NormalizeEmbeddings, which says how the source’s vectors were made, not the transformed ones. Its label is that of source followed by the transform’s (see embedding_label()), e.g. baseRandom3EaCoralCh. It is named by embedding_path(), with the task of the windows when they share one, and written to a temporary name, then moved into place.

Parameters:
  • source (DataContainer) – Embeddings read by load_embeddings(), one row per window.

  • embeddings (np.ndarray) – The transformed embeddings, one row per row of source.

  • root (path-like) – The derivative dataset, e.g. derivatives/coco-pipe-cbramod.

  • transform (SubjectAlignment) – The fitted transform that made embeddings, e.g. an EuclideanAlign. Its name, label and parameters are recorded as the setting Transform, with its fitted rank_ and n_subjects_ when it has them (LEACE).

  • fitted_on (str, optional) – What the transform was fitted on, recorded in Transform, e.g. "every window of base, both conditions".

  • view (str, optional) – The view of the file; that of source by default.

  • token_dtype ({"float32", "float16"}) – The dtype of a token file; other views are float32.

Returns:

The file written.

Return type:

BIDSPath

Raises:

ValueError – If source is not one row per window of an embedding file, or is already transformed, if embeddings does not have one row per window, has axes its view cannot have or holds non-finite values, if transform works per channel (channel_axis) along an axis of source that is not channel, or if the label is not a BIDS label.