coco_pipe.io.embeddings#
BIDS-compatible derivative I/O for foundation-model embeddings.
Functions#
|
Return the |
|
Return the BIDS path of an embedding file. |
|
Write one recording's embeddings, one file per view. |
|
Return whether a recording's embedding files are written and up to date. |
|
Write the dataset files of an embedding derivative and its sidecars. |
|
Write the run records of one label: its skipped and failed recordings. |
|
Return the per-recording embedding files of one label and view. |
|
Load embedding files into a DataContainer. |
|
Write recordings' embedding files as one file at the dataset 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
desclabel of embeddings made fromlabel’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 labelleddesc-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
labelof a subject transform, e.g.EuclideanAlign’s.
- Return type:
- Raises:
ValueError – If
labelor 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. Withrecording_idit holds one recording and sits in its subject (and session) folder; without it, it holds every recording and sits at the dataset root, named bytaskwhen one is given.- Parameters:
root (path-like) – The derivative dataset, e.g.
derivatives/coco-pipe-cbramod.label (str) – The
desclabel, e.g."base"or"baseRandom0EaCoral"(seeembedding_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_idcoordinate 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;
.fpathis the file.- Return type:
BIDSPath
- Raises:
ValueError – If
labelis not a BIDS label,viewis not an embedding view,recording_idis not a recording’s entities, or bothrecording_idandtaskare 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, seeEMBEDDING_VIEWS) goes to its own file, named byembedding_path()after the source recording, with the labelembedding_label()gives for the weights and pooling: e.g.baseRandom3for 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_indexholds 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 labelleddesc-base.source (path-like) – The file the epochs were read from, in its datatype folder of a BIDS dataset: the
sourcecoordinate of the BIDS loader’s rows, or aBIDSPath’sfpath. 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 ofsource.bad_channels (str | sequence of str) – The recording’s bad channels, or the BIDS loader’s
bad_channelscoordinate (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, asembeddings_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:
- 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 matchmodel_channels, if a pooling’s name is not letters and digits, iflabelis not a BIDS label, ifsourceis not a file in a datatype folder of a subject, or iftoken_dtypeis not"float32"or"float16".
Notes
The
embeddingsvariable holds the view, as float32 (tokens astoken_dtype; values beyond float16’s range are refused). Alongwindoware the coordinatesobs(<recording_id>_epoch-NNNN, as the BIDS loader names observations),recording_id,subject,session,task,run,condition,epoch,startandstop. Alongrecordingare itssource(a BIDS URI), sampling rate, channels, bad channels and the channels the model interpolated, zero-filled or dropped. A view with achannelaxis names it with thechannelcoordinate: the channels the model saw (model_channels). The attributes aremodel_key,config(the extraction settings that are the same for every recording, as JSON text, seeEMBEDDING_CONFIG_KEYS),config_hash(their hash) anddescription(the file’s label); a token file addstoken_sourceandtoken_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.
writtenis whatwrite_recording_embeddings()returned for another recording of the same model and settings.recordingis up to date when it has each of those files, holding its windows (condition and epoch, from the BIDS loader’s rows) with theconfig_hashof 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:
- 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.tsvand itsdescriptions.json, and.bidsignore(keeping lines already there).descriptions.tsvlists the label of each top-level embedding file (one holding every recording): what its data is, fromdescriptions, 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 (itsconfigattribute), itsconfig_hashasConfigHashand aDescription. 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"}: thelabelgiven to the writers, not the labelsembedding_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"}: theDatasetLinksthat resolve the BIDS URIs of the recordings’ sources, also listed asSourceDatasets.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
descriptionsgives with its settings, a label other than the one it holds, an unknown view, noconfigor one that does not match itsconfig_hash, sources in a datasetdataset_linksdoes 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.jsonat 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
desclabel the records belong to.records (iterable of mapping) – One record per recording, e.g. its
recording_id,statusandreason.
- 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
desclabel, 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:
FileNotFoundError – If
rootis not a directory.ValueError – If
labelis not a BIDS label orviewis not an embedding view.
- 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
conditionsandsubjectsare 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_dfholding the subject ID. It matches rows to subjects and is not attached itself.
- Returns:
Xis float32, with the file’s axes andwindowrenamedobs:("obs", "feature")for window and cov files, andchannel,time_patchor the model’s token axes beforefeaturefor the others.idsisobs. Alongobsare the file’s window coordinates (recording_id,subject,session,task,run,condition,epoch,start,stop), each recording’sbad_channelsand each subject’s metadata: the columns ofparticipants.tsv, found in the files’ dataset or, followingSourceDatasets, in a dataset it comes from (seeload_participants_tsv()), and those ofsubject_metadata_df.sessionandrunare dropped when no recording has one. A channel axis keeps itschannelnames.metaholdsmodel_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_sourceandtoken_feature_axis.- Return type:
- Raises:
ValueError – If
sourcenames 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; ifsubject_metadata_dfcomes withoutsubject_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
obsis<recording_id>_cond-<condition>andepoch_countholds 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 offiles, their recording tables and their attributes, and reads back withload_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(): iffilesis 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.
sourceis whatload_embeddings()returned for one label and view, one row per window, andembeddingsits transform, row for row: of the same shape for a transform that keeps it (EuclideanAlign,LeaceEraser), or(window, feature)withview="cov"forRiemannAlign’s tangent vectors. The file keeps the windows, the recordings and the channels ofsource; its settings are those ofsourcewithTransformadded, so itsconfig_hashdiffers, and withoutNormalizeEmbeddings, which says how the source’s vectors were made, not the transformed ones. Its label is that ofsourcefollowed by the transform’s (seeembedding_label()), e.g.baseRandom3EaCoralCh. It is named byembedding_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. anEuclideanAlign. Itsname,labeland parameters are recorded as the settingTransform, with its fittedrank_andn_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
sourceby 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
sourceis not one row per window of an embedding file, or is already transformed, ifembeddingsdoes not have one row per window, has axes its view cannot have or holds non-finite values, iftransformworks per channel (channel_axis) along an axis ofsourcethat is notchannel, or if the label is not a BIDS label.