cedalion.io package

Submodules

cedalion.io.anatomy module

Functions for reading and processing anatomical data.

cedalion.io.anatomy.read_segmentation_masks(
basedir: str,
mask_files: Dict[str, str] = {'csf': 'csf.nii', 'gm': 'gm.nii', 'scalp': 'scalp.nii', 'skull': 'skull.nii', 'wm': 'wm.nii'},
) → Tuple[DataArray, ndarray][source]

Read segmentation masks from NIFTI files.

Parameters:
  • basedir (str) – Directory containing the mask files

  • mask_files (Dict[str, str]) – Dictionary mapping segmentation types to filenames

Returns:

  • masks (xr.DataArray): Concatenated segmentation masks with a new dimension segmentation_type.

  • affine (np.ndarray): Affine transformation matrix associated with the NIFTI files.

Return type:

Tuple[xr.DataArray, np.ndarray]

cedalion.io.anatomy.cell_coordinates(mask, affine, units='mm', center=False)[source]

Get the coordinates of each voxel in the transformed mask.

Parameters:
  • mask (xr.DataArray) – A binary mask of shape (i, j, k).

  • affine (np.ndarray) – Affine transformation matrix.

  • units (str) – Units of the output coordinates.

  • center – if true the cells’ center positions are returned. Otherwise it is the position of the lower-left corner of the voxel.

Returns:

Coordinates of the center of each voxel in the mask.

Return type:

xr.DataArray

cedalion.io.anatomy.read_parcellations(parcel_file: str | Path) → DataFrame[source]

Read parcellation labels from a json file.

Parameters:

parcel_file – The parcels file name

Returns:

Contains vertices’ labels, their appropriate colors

Return type:

pd.DataFrame

cedalion.io.anatomy.read_parcel_colors(parcel_colors_file: str | Path) → dict[str, list][source]

Read parcel RGB colors from a JSON file.

Parameters:

parcel_colors_file – Path to the JSON file mapping parcel names to RGB color lists.

Returns:

Dictionary mapping parcel label strings to RGB color lists.

cedalion.io.anatomy.trimesh_from_freesurfer(
lh: str | Path,
rh: str | Path,
crs: str,
units: str,
offset_hemispheres: bool = True,
) → TrimeshSurface[source]

Load freesurfer surfaces as a cdc.TrimeshSurface object.

Parameters:
  • lh – path of the left hemisphere surface file.

  • rh – path of the right hemisphere surface file.

  • crs – label of the coordinate reference system

  • units – units of vertex coordinates

  • offset_hemispheres – If True, offset the hemispheres along the x-axis such that the left hemisphere’s maximum x-coordinate aligns with the right hemisphere’s minimum x-coordinate, removing the overlap that occurs with inflated surfaces.

Returns:

A single TrimeshSurface containing both hemispheres, with left-hemisphere vertices preceding right-hemisphere vertices in the vertex array.

cedalion.io.bids module

cedalion.io.bids.read_events_from_tsv(fname: str | Path)[source]
cedalion.io.bids.check_for_bids_field(path_parts: list, field: str)[source]

@author: lauracarlton.

cedalion.io.bids.get_snirf2bids_mapping_csv(dataset_path)[source]

@author: lauracarlton.

cedalion.io.bids.find_files_with_pattern(
start_dir: str | Path,
pattern: str,
) → List[str][source]

Recursively finds all files in the specified directory (and subdirectories) that match the given pattern.

Parameters:

start_dirstr | Path

The directory to start the search from.

patternstr

The pattern to match filenames against.

Returns:

List[str]

A list of file paths (as strings) of all files that match the pattern.

cedalion.io.bids.create_bids_standard_filenames(
row: Series,
) → Tuple[str, str][source]

Generates a BIDS compliant file name and its parent directory path based on the information in the given row.

This function constructs a filename and directory path following the BIDS naming convention for a specific subject, session, task, acquisition, and run based on the provided DataFrame row. The final filename will include “_nirs.snirf” as the extension, and the directory path will be created under a “nirs” directory.

Parameters:

rowpd.Series

A row of a Pandas DataFrame containing the following potential columns: - “sub” : The subject identifier (e.g., “01”) - “ses” : The session identifier (e.g., “01”), can be NaN if not available - “task” : The task name or identifier (e.g., “rest”) - “acq” : The acquisition identifier (e.g., “01”), can be NaN if not available - “run” : The run identifier (e.g., “1”), can be NaN if not available

Returns:

Tuple[str, str]

A tuple containing: 1. The generated filename string based on the BIDS standard. 2. The parent directory path where the file is expected to be located.

cedalion.io.bids.copy_rename_snirf(row: Series, dataset_path: str, bids_dir: str)[source]

Copies a .snirf file from the source directory, renaming it according to BIDS standards, and places it in the appropriate destination directory.

This function takes the source file (in the dataset_path), renames it based on the information in the provided row, and copies it to the target bids_dir directory, following the BIDS directory structure.

Parameters:

rowpd.Series

A row from a Pandas DataFrame containing the following columns: - “current_name” : The current name of the file (without the .snirf extension). - “parent_path” : The relative path within the BIDS structure where the file should be stored. - “bids_name” : The new BIDS-compliant name for the file.

dataset_pathstr

The path to the directory containing the original .snirf file(s) to be copied.

bids_dirstr

The path to the root BIDS directory where the renamed file should be copied to.

cedalion.io.bids.search_for_acq_time_in_scan_files(dataset_path: str) → DataFrame[source]

Searches for _scans.tsv files in the given dataset path, reads them into DataFrames, and processes them to extract the filename and acq_time columns.

This function looks for all _scans.tsv files in the dataset_path, reads them into a DataFrame, and processes the filename and acq_time columns. If the acq_time column does not exist in the merged DataFrame, it will be added with None values. If no _scans.tsv files are found, an empty DataFrame with the columns filename_org and acq_time is returned.

Parameters:

dataset_pathstr

The path to the dataset where the _scans.tsv files are located.

Returns:

pd.DataFrame

A DataFrame with the following columns: - filename_org: The original filename (without the .snirf extension) from the _scans.tsv files. - acq_time: The acquisition time for each scan. If the acq_time column does not exist in the original files, it will be filled with None.

cedalion.io.bids.search_for_acq_time_in_snirf_files(
row: Series,
dataset_path: str,
) → datetime[source]

Extracts acquisition time from SNIRF files if missing in the _scans.tsv file.

This function checks if the acquisition time (acq_time) is missing (NaN) in the input row. If missing, it loads the corresponding SNIRF file, extracts the acquisition date and time, and returns it as a datetime object.

Parameters:

rowpd.Series

A row from the mapping_df DataFrame containing current_name and acq_time columns.

dataset_pathstr

Path to the dataset where the SNIRF files are located.

Returns:

datetime

The acquisition timestamp extracted from the SNIRF file, or the existing acq_time if not missing.

cedalion.io.bids.search_for_sessions_acq_time(dataset_path: str) → DataFrame[source]

Searches for _sessions.tsv files in the provided dataset path, reads them into DataFrames, and processes them to extract the session_id, sub (subject ID), and ses_acq_time (session acquisition time).

This function looks for all _sessions.tsv files in the given dataset_path, reads them into DataFrames, and processes them to extract the subject ID and session acquisition time. If the acq_time column does not exist in the input files, it will be added with None values. Additionally, it extracts the subject ID from the filename using a regular expression.

Parameters:

dataset_pathstr

The path to the dataset where the _sessions.tsv files are located.

Returns:

pd.DataFrame

A DataFrame with the following columns: - session_id: The session identifier (extracted from the filenames). - sub: The subject ID extracted from the filename. - ses_acq_time: The session acquisition time for each session. If the acq_time column does not exist in the original files, it will be filled with None.

cedalion.io.bids.create_scan_files(group_df: DataFrame, bids_dir: str) → None[source]

Creates a _scans.tsv file for each subject (and session, if provided) from the provided DataFrame and saves it in the BIDS directory.

This function generates a _scans.tsv file for each group of data (grouped by subject and session) in the group_df DataFrame. The resulting file contains two columns: filename (with a relative path to the NIRS file) and acq_time (acquisition time). The function saves this file in the appropriate directory within the BIDS dataset.

Parameters:

group_dfpd.DataFrame

A DataFrame containing a group of rows for a particular subject and session. This DataFrame should include at least the bids_name and acq_time columns.

bids_dirstr

The path to the BIDS directory where the _scans.tsv file will be saved.

Returns:

None

This function does not return anything. It saves the generated _scans.tsv file to the BIDS directory.

cedalion.io.bids.create_session_files(group_df: DataFrame, bids_dir: str) → None[source]

Creates a _sessions.tsv file for each subject from the provided DataFrame and saves it in the BIDS directory.

This function generates a _sessions.tsv file for each subject in the group_df DataFrame. The resulting file contains two columns: ses (session identifier) and acq_time (session acquisition time). The function saves this file in the appropriate directory within the BIDS dataset.

Parameters:

group_dfpd.DataFrame

A DataFrame containing a group of rows for a particular subject. This DataFrame should include at least the ses (session identifier) and ses_acq_time (session acquisition time) columns.

bids_dirstr

The path to the BIDS directory where the _sessions.tsv file will be saved.

Returns:

None

This function does not return anything. It saves the generated _sessions.tsv file to the BIDS directory.

cedalion.io.bids.create_data_description(
dataset_path: str,
bids_dir: str,
extra_meta_data: str | None = None,
) → None[source]

Creates or updates the dataset_description.json file in the specified BIDS directory.

This function checks for an existing dataset_description.json file in the specified dataset path and updates it with relevant metadata. It also adds any additional metadata from an optional external JSON file (extra_meta_data). If some required keys are missing, it will add them with default values.

Parameters:

dataset_pathstr

The path to the dataset where the dataset_description.json file is located.

bids_dirstr

The path to the BIDS directory where the updated dataset_description.json file will be saved.

extra_meta_dataOptional[str], default=None

An optional path to a JSON file containing additional metadata to be included in the dataset_description.json. If not provided, no extra metadata will be added.

Returns:

None

This function does not return any value. It updates the dataset_description.json file in the BIDS directory.

cedalion.io.bids.check_coord_files(bids_dir: str) → None[source]

Checks for and updates *_coordsystem.json files in a BIDS directory.

This function searches for files matching the pattern “*_coordsystem.json” within the specified BIDS directory. If the “NIRSCoordinateSystem” field is empty, it updates the field with the value “Other” and writes the updated data back to the JSON file.

Parameters:

bids_dirstr

The path to the BIDS directory where *_coordsystem.json files are located.

Returns:

None

This function does not return any value. It directly modifies the *_coordsystem.json files.

cedalion.io.bids.create_participants_tsv(
bids_dir: str,
mapping_df: DataFrame,
fields: List[str] | None = None,
) → None[source]

Creates a participants.tsv file in a BIDS-compliant directory.

This function generates a participants.tsv file based on the provided mapping_df, which must include at least a “sub” column (subject identifier). It ensures that the specified fields are present in the output, initializing any missing fields with None.

Parameters:
  • bids_dir (str) – Path to the BIDS directory.

  • mapping_df (pd.DataFrame) – A DataFrame containing subject metadata, including a “sub” column.

  • fields (List[str], optional) – A list of additional participant-level fields to include in the TSV. Defaults to [“species”, “age”, “sex”, “handedness”].

Returns:

Writes participants.tsv to the specified BIDS directory.

Return type:

None

cedalion.io.bids.create_participants_json(bids_dir: str, fields: List[str] | None = None) → None[source]

Creates or updates a participants.json file in a BIDS-compliant directory.

If no custom fields are provided, this function uses a default schema based on BIDS recommendations. The output describes participant-level metadata for each field in the corresponding participants.tsv file.

Parameters:
  • bids_dir (str) – Path to the BIDS directory.

  • fields (List[str], optional) – List of fields to include in the JSON schema. If None, a default set is used.

Returns:

Writes participants.json to the specified BIDS directory.

Return type:

None

cedalion.io.bids.create_participants_files(
bids_dir: str,
mapping_df: DataFrame | None = None,
participants_tsv_path: str | None = None,
participants_json_path: str | None = None,
fields: List[str] | None = None,
)[source]

Creates or updates participants.tsv and participants.json files in a BIDS-compliant directory.

If a participants.tsv file already exists and contains data, it is cleaned and standardized: - Ensures the first column is named participant_id - Prepends “sub-” to subject IDs if missing - Sorts the participants by ID The corresponding participants.json file is also updated or created based on the TSV’s columns.

If no valid participants.tsv file is found, the function will fall back to generating new files using the provided mapping_df.

Parameters:
  • bids_dir (str) – Path to the BIDS directory where output files will be written.

  • mapping_df (pd.DataFrame, optional) – Used to create participants.tsv if no existing file is found.

  • participants_tsv_path (str, optional) – Path to an existing participants.tsv file.

  • participants_json_path (str, optional) – Path to an existing participants.json file.

  • fields (List[str], optional) – List of fields to include in your schema. If None, a default set is used.

cedalion.io.bids.edit_events(row: Series, bids_dir: str) → None[source]

Edits an events.tsv file in a BIDS directory based on specified conditions.

This function modifies an events.tsv file corresponding to a specific row of mapping scv. It updates the “duration” and/or “trial_type” columns based on the values in the row parameter.

Parameters:
  • row (pd.Series) – A pandas Series containing the following keys: - “cond” (str or None): A string representing a list of keys for mapping trial types. - “cond_match” (str or None): A string representing a list of values for mapping trial types. - “duration” (float or None): The duration to update in the events file. - “bids_name” (str): The base name of the BIDS file to find the corresponding events.tsv file. - “parent_path” (str): The relative path to the directory containing the events.tsv file.

  • bids_dir (str) – The base directory for the BIDS dataset.

Returns:

The function modifies the events.tsv file in place and does not return a value.

Return type:

None

cedalion.io.bids.sort_events(row: Series, bids_dir: str) → None[source]

Sorts the events in a BIDS-compatible .tsv file by onset time.

This function locates the corresponding _events.tsv file for a given dataset, reads the file, sorts the events by the “onset” column, and overwrites the original file with the sorted version.

Parameters:

rowpd.Series

A row from a DataFrame containing BIDS file metadata. Must include the keys “bids_name” and “parent_path”.

bids_dirstr

The root directory of the BIDS dataset.

cedalion.io.bids.save_source(dataset_path: str, destination_path: str) → None[source]

Copies the dataset to a ‘sourcedata’ folder within the specified destination path.

If a ‘sourcedata’ folder already exists inside the dataset_path, only that folder is copied. Otherwise, the entire dataset is copied into a new ‘sourcedata’ folder in the destination.

Parameters:
  • dataset_path (str) – Path to the original dataset.

  • destination_path (str) – Directory where the ‘sourcedata’ folder will be created and data copied.

cedalion.io.forward_model module

Module for saving and loading forward model computation results.

cedalion.io.forward_model.save_Adot(fn: str, Adot: DataArray)[source]

Save Adot to a netCDF file.

Parameters:
  • fn (str) – File name to save the data to.

  • Adot (xr.DataArray) – Data to save.

Returns:

None

cedalion.io.forward_model.load_Adot(fn: str)[source]

Load Adot from a netCDF file.

Parameters:

fn (str) – File name to load the data from.

Returns:

Data loaded from the file.

Return type:

xr.DataArray

cedalion.io.forward_model.save_fluence(fn: str, fluence_all, fluence_at_optodes)[source]

Save forward model computation results (deprecated).

Deprecated since version Use: FluenceFile instead. This function uses a lossy compression algorithm to reduce file size.

Parameters:
  • fn – Path to the output HDF5 file.

  • fluence_all – Full volumetric fluence DataArray (dims: label, wavelength, i, j, k).

  • fluence_at_optodes – Optode-pair fluence DataArray (dims: optode1, optode2, wavelength).

cedalion.io.forward_model.load_fluence(fn: str)[source]

Load forward model computation results.

Parameters:

fn (str) – File name to load the data from.

Returns:

Fluence data loaded from the file.

Return type:

Tuple[xr.DataArray, xr.DataArray]

class cedalion.io.forward_model.FluenceFile(fname: str | Path, mode='r')[source]

Bases: object

Context-manager for reading and writing fluence HDF5 files.

Fluence files store the output of Monte Carlo photon simulations:

  • fluence_all: the full volumetric fluence for each optode and wavelength, shape (n_optodes, n_wavelengths, i, j, k), stored with LZF compression.

  • fluence_at_optodes: the fluence sampled at all optode positions, shape (n_optodes, n_optodes, n_wavelengths).

Use as a context manager to ensure the underlying HDF5 file is flushed and closed even if an exception occurs:

with FluenceFile("fluence.h5", mode="w") as ff:
    ff.create_fluence_dataset(optodes, wavelengths, shape, units)
    ...
file[source]

The underlying open h5py.File object.

optode_labels[source]

List of optode label strings (populated on read/create).

wavelengths[source]

List of wavelength floats (populated on read/create).

create_fluence_dataset(
optode_pos: Annotated[DataArray, DataArraySchema(dims='label', coords='label', 'label', 'type')],
wavelengths: ndarray,
fluence_shape: tuple[int, int, int],
units: str,
)[source]

Create and initialise the fluence_all dataset in the HDF5 file.

Must be called once after opening in write mode, before any calls to set_fluence_by_label() or set_fluence_by_index().

Parameters:
  • optode_pos – Labeled optode positions; labels and types are stored as dataset attributes.

  • wavelengths – Array of wavelength values (nm).

  • fluence_shape – Voxel grid shape (ni, nj, nk) for the fluence volume.

  • units – Physical units string for the fluence values (e.g. "mm^-2").

get_fluence(label: str, wavelength: float) → ndarray[source]

Return the volumetric fluence for one optode and wavelength.

Parameters:
  • label – Optode label string.

  • wavelength – Wavelength value (must match one stored in the file).

Returns:

NumPy array of shape (ni, nj, nk).

set_fluence_by_label(label: str, wavelength: float, fluence: ndarray)[source]

Write the volumetric fluence for one optode and wavelength (by label).

Parameters:
  • label – Optode label string.

  • wavelength – Wavelength value.

  • fluence – Array of shape (ni, nj, nk) to store.

set_fluence_by_index(i_label: int, i_wl: int, fluence: ndarray)[source]

Write the volumetric fluence for one optode and wavelength (by index).

Parameters:
  • i_label – Zero-based optode index.

  • i_wl – Zero-based wavelength index.

  • fluence – Array of shape (ni, nj, nk) to store.

get_fluence_at_optodes()[source]

Return the optode-pair fluence as an xr.DataArray.

Returns:

xr.DataArray with dims (optode1, optode2, wavelength).

set_fluence_at_optodes(fluence_at_optodes: DataArray)[source]

Store the optode-pair fluence dataset.

Parameters:

fluence_at_optodes – DataArray with dims (optode1, optode2, wavelength) containing the fluence sampled at each optode position.

get_fluence_all()[source]

Return the full volumetric fluence as an xr.DataArray.

Returns:

xr.DataArray with dims (label, wavelength, i, j, k) and label, type, and wavelength coordinates.

cedalion.io.nirs module

Read Homer2/AtlasViewer .nirs MATLAB files into Recording objects.

cedalion.io.nirs.read_nirs(fname: Path | str)[source]

Read a Homer2/AtlasViewer .nirs MATLAB file into a Recording.

Parameters:

fname – Path to the .nirs file.

Returns:

Recording containing the amplitude time series, 3-D optode geometry, stimulus events, and (if present) auxiliary channels.

cedalion.io.photogrammetry module

Module for reading photogrammetry output file formats.

cedalion.io.photogrammetry.read_photogrammetry_einstar(fn)[source]

Read optodes and fiducials from photogrammetry pipeline.

This method reads the output file as returned by the photogrammetry pipeline using an einstar device.

Parameters:

fn (str) – The filename of the einstar photogrammetry output file.

Returns:

A tuple containing:
  • fiducials (cedalion.LabeledPoints): The fiducials as a cedalion

    LabeledPoints object.

  • optodes (cedalion.LabeledPoints): The optodes as a cedalion LabeledPoints

    object.

Return type:

tuple

cedalion.io.photogrammetry.read_einstar(fn)[source]

Read optodes and fiducials from einstar devices.

Parameters:

fn (str) – The filename of the einstar photogrammetry output file.

Returns:

A tuple containing:
  • fiducials (OrderedDict): The fiducials as an OrderedDict.

  • optodes (OrderedDict): The optodes as an OrderedDict.

Return type:

tuple

cedalion.io.photogrammetry.opt_fid_to_xr(fiducials, optodes)[source]

Convert OrderedDicts fiducials and optodes to cedalion LabeledPoints objects.

Parameters:
  • fiducials (OrderedDict) – The fiducials as an OrderedDict.

  • optodes (OrderedDict) – The optodes as an OrderedDict.

Returns:

A tuple containing:
  • fiducials (cedalion.LabeledPoints): The fiducials as a cedalion

    LabeledPoints object.

  • optodes (cedalion.LabeledPoints): The optodes as a cedalion LabeledPoints

    object.

Return type:

tuple

cedalion.io.probe_geometry module

Module for reading and writing probe geometry files.

cedalion.io.probe_geometry.load_tsv(
tsv_fname: str,
crs: str = None,
units: str = None,
) → DataArray[source]

Load a tsv file containing optodes or landmarks.

Parameters:
  • tsv_fname – Path to the tsv file.

  • crs – Coordinate reference system of the points if not in the file header.

  • units – Units of the points if not in the file header.

Returns:

xr.DataArray containing the optodes or landmarks with label, type, and positional dimensions.

cedalion.io.probe_geometry.export_to_tsv(tsv_filename, points)[source]

Export optodes, fiducials, landmarks, electrodes, or measurement lists to tsv.

Parameters:
  • tsv_filename – Path to the output tsv file.

  • points – Points to save. Either an xr.DataArray (optodes / landmarks / electrodes) or a pd.DataFrame (measurement list).

cedalion.io.probe_geometry.read_mrk_json(fname: str, crs: str) → DataArray[source]

Read a JSON file containing landmarks (3D Slicer .mrk.json format).

Parameters:
  • fname – Path to the JSON file.

  • crs – Coordinate reference system of the landmarks.

Returns:

xr.DataArray containing landmark positions with label and type coordinates, quantified with pint units.

cedalion.io.probe_geometry.save_mrk_json(fname: str, landmarks: DataArray, crs: str)[source]

Save landmarks to a 3D Slicer .mrk.json file.

Parameters:
  • fname – Path to the output JSON file.

  • landmarks – Landmark positions as an xr.DataArray with label coordinate.

  • crs – Coordinate reference system name to embed in the file.

cedalion.io.probe_geometry.read_digpts(fname: str, units: str = 'mm') → DataArray[source]

Read a file containing digitized 3D points.

Each line must have the format label: x y z.

Parameters:
  • fname – Path to the digitized-points file.

  • units – Physical units of the coordinates (default: "mm").

Returns:

xr.DataArray with dimensions ["label", "pos"], quantified with pint units.

cedalion.io.probe_geometry.read_einstar_obj(fname: str) → TrimeshSurface[source]

Read a textured triangle mesh generated by Einstar 3D scanners.

Parameters:

fname – Path to the .obj mesh file.

Returns:

TrimeshSurface in the "digitized" CRS with millimetre units.

cedalion.io.probe_geometry.read_fieldtrip_elc(
fname: Path | str,
) → Annotated[DataArray, DataArraySchema(dims='label', coords='label', 'label', 'type')][source]

Read electrode positions from a FieldTrip .elc file.

Parameters:

fname – Path to the .elc file.

Returns:

LabeledPoints with electrode positions, label and type coordinates, and pint units derived from the file header.

cedalion.io.probe_geometry.read_sd(
fname: Path | str,
crs='av',
) → Annotated[DataArray, DataArraySchema(dims='label', coords='label', 'label', 'type')][source]

Read optode positions from a Homer/AtlasViewer .mat SD file.

Parameters:
  • fname – Path to the .mat SD file.

  • crs – Coordinate reference system label to assign (default: "av").

Returns:

LabeledPoints with source, detector, and landmark positions.

cedalion.io.snirf module

Contains functionality for handling .snirf files.

class cedalion.io.snirf.DataType(value)[source]

Bases: Enum

SNIRF data type codes as defined in the SNIRF specification.

CW_AMPLITUDE = 1[source]
CW_FLUORESCENCE_AMPLITUDE = 51[source]
FD_AC_AMPLITUDE = 101[source]
FD_PHASE = 102[source]
FD_FLUORESCENCE_AMPLITUDE = 151[source]
FD_FLUORESCENCE_PHASE = 152[source]
TDG_AMPLITUDE = 201[source]
TDG_FLUORESCENCE_AMPLITUDE = 251[source]
TDM_AMPLITUDE = 301[source]
TDM_FLUORESCENCE_AMPLITUDE = 351[source]
DCS_G2 = 401[source]
DCS_BFI = 410[source]
PROCESSED = 99999[source]
class cedalion.io.snirf.DataTypeLabel(value)[source]

Bases: StrEnum

SNIRF data type label strings as defined in the SNIRF specification.

DOD = 'dOD'[source]
DMEAN = 'dMean'[source]
DVAR = 'dVar'[source]
DSKEW = 'dSkew'[source]
MUA = 'mua'[source]
MUSP = 'musp'[source]
HBO = 'HbO'[source]
HBR = 'HbR'[source]
HBT = 'HbT'[source]
H2O = 'H2O'[source]
LIPID = 'Lipid'[source]
BFI = 'BFi'[source]
HRF_DOD = 'HRF dOD'[source]
HRF_DMEAN = 'HRF dMean'[source]
HRF_DVAR = 'HRF dVar'[source]
HRF_DSKEW = 'HRF dSkew'[source]
HRF_HBO = 'HRF HbO'[source]
HRF_HBR = 'HRF HbR'[source]
HRF_HBT = 'HRF HbT'[source]
HRF_BFI = 'HRF BFi'[source]
RAW_SATORI = 'RAW'[source]
RAW_NIRX = 'raw-DC'[source]
MOMENTS_KERNEL = 'Time Domain - Moments - Amplitude'[source]
class cedalion.io.snirf.ReadSnirfOptions(squeeze_aux: bool, crs: str | None, time_units: str | None)[source]

Bases: object

Helper class to pass options through read_snirf subroutines.

squeeze_aux[source]

If True, squeeze the aux data to remove dimensions of size 1.

Type:

bool

crs[source]

Name of the geo3D coordinate reference system.

Type:

str | None

time_units[source]

If provided, overrides the time coordinate units read from the file’s metaDataTags.

Type:

str | None

squeeze_aux: bool[source]
crs: str | None[source]
time_units: str | None[source]
cedalion.io.snirf.assign_data_type_group(
data_type: DataType,
data_type_label: DataTypeLabel,
data_type_index: int,
nirs_element: NirsElement,
) → str[source]

Map a (data_type, data_type_label, data_type_index) triple to a group string.

The SNIRF standard allows different data types to share the same data element (e.g. Satori stores processing results this way; Kernel stores temporal moments in one element). Content must be grouped before being packaged into separate DataArrays. This function maps each measurement-list row to a canonical group label used as a key in CANONICAL_NAMES.

Parameters:
  • data_type – Parsed DataType enum value.

  • data_type_label – Parsed DataTypeLabel enum value (may be None).

  • data_type_index – Integer index from the measurement list (may be None).

  • nirs_element – The enclosing NIRS element; used to resolve moment orders for Kernel-style TD data.

Returns:

A group label string such as "unprocessed raw" or "processed concentrations".

Raises:

ValueError – If the combination of arguments is not recognised.

cedalion.io.snirf.parse_data_type(value) → DataType | None[source]

Parse a raw measurement-list data-type value into a DataType enum.

Parameters:

value – Raw integer value from the SNIRF measurement list (or None).

Returns:

Corresponding DataType member, or None if value is None or not recognised (a warning is logged in that case).

cedalion.io.snirf.parse_data_type_label(value) → DataTypeLabel | None[source]

Parse a raw measurement-list data-type label into a DataTypeLabel.

Parameters:

value – Raw string value from the SNIRF measurement list (or None).

Returns:

Corresponding DataTypeLabel member, or None if value is None or not recognised (a warning is logged in that case).

cedalion.io.snirf.parse_data_type_index(value) → int | None[source]

Parse a raw measurement-list data-type index to an integer.

Parameters:

value – Raw value from the SNIRF measurement list (or None).

Returns:

Integer index, or None if value is None.

cedalion.io.snirf.reduce_ndim_sourceLabels(sourceLabels: ndarray) → list[source]

Deal with multidimensional source labels.

snirf supports multidimensional source labels but we don’t. This function tries to reduce n-dimensional source labels to a unique common prefix to obtain only one label per source.

Parameters:

sourceLabels (np.ndarray) – The source labels to reduce.

Returns:

The reduced source labels.

Return type:

list

cedalion.io.snirf.labels_and_positions(probe, dim: int = 3)[source]

Extract 3D coordinates of optodes and landmarks from a nirs probe variable.

Parameters:
  • probe – Nirs probe geometry variable, see snirf docs (Tucker et al. [TDK+22]).

  • dim (int) – Must be either 2 or 3.

Returns:

A tuple containing the source, detector, and landmark labels/positions.

Return type:

tuple

cedalion.io.snirf.geometry_from_probe(nirs_element: NirsElement, dim: int, crs: str)[source]

Extract 3D coordinates of optodes and landmarks from probe information.

Parameters:
  • nirs_element (NirsElement) – Nirs data element as specified in the snirf documentation (Tucker et al. [TDK+22]).

  • dim (int) – Must be either 2 or 3.

  • crs – the name of coordinate reference system

Returns:

A DataArray containing the 3D coordinates of optodes and

landmarks, with dimensions ‘label’ and ‘pos’ and coordinates ‘label’ and ‘type’.

Return type:

xr.DataArray

cedalion.io.snirf.measurement_list_to_dataframe(
measurement_list: MeasurementList,
drop_none: bool = False,
) → DataFrame[source]

Converts a snirf MeasurementList object to a pandas DataFrame.

Parameters:
  • measurement_list – MeasurementList object from the snirf file.

  • drop_none (bool) – If True, drop columns that are None for all rows.

Returns:

DataFrame containing the measurement list information.

Return type:

pd.DataFrame

cedalion.io.snirf.meta_data_tags_to_dict(
nirs_element: NirsElement,
) → OrderedDict[str, Any][source]

Converts the metaDataTags of a nirs element to a dictionary.

Parameters:

nirs_element (NirsElement) – Nirs data element as specified in the snirf documentation (Tucker et al. [TDK+22]).

Returns:

Dictionary containing the metaDataTags information.

Return type:

OrderedDict[str, Any]

cedalion.io.snirf.stim_to_dataframe(stim: Stim)[source]

Converts a snirf Stim object to a pandas DataFrame.

Parameters:

stim (Stim) – Stim object as specified in the snirf documentation (Tucker et al. [TDK+22]).

Returns:

DataFrame containing the stimulus information.

Return type:

pd.DataFrame

cedalion.io.snirf.read_aux(
nirs_element: NirsElement,
opts: ReadSnirfOptions,
) → OrderedDict[str, DataArray][source]

Reads the aux data from a nirs element into a dictionary of DataArrays.

Parameters:
  • nirs_element (NirsElement) – Nirs data element as specified in the snirf documentation (Tucker et al. [TDK+22]).

  • opts – options passed to read_snirf.

Returns:

Dictionary containing the aux data

Return type:

result (OrderedDict[str, xr.DataArray])

cedalion.io.snirf.add_number_to_name(name: str, keys: list[str])[source]

Changes name to name_<number>.

Number appended to name is the smallest number that makes the new name unique with respect to the list of keys.

Parameters:
  • name (str) – Name to which a number should be added.

  • keys (list[str]) – List of keys to which the new name should be compared.

Returns:

New name with number added.

Return type:

str

cedalion.io.snirf.read_data_elements(
data_element: DataElement,
nirs_element: NirsElement,
stim: DataFrame,
opts: ReadSnirfOptions,
) → list[tuple[str, TypeAliasForwardRef('cdt.NDTimeSeries')]][source]

Reads the data elements from a nirs element into a list of DataArrays.

Parameters:
  • data_element (DataElement) – DataElement obj. from the snirf file.

  • nirs_element (NirsElement) – Nirs data element as specified in the snirf documentation (Tucker et al. [TDK+22]).

  • stim (pd.DataFrame) – DataFrame containing the stimulus information.

  • opts – Options passed to read_snirf.

Returns:

List of tuples containing the canonical name

of the data element and the DataArray.

Return type:

list[tuple[str, NDTimeSeries]]

cedalion.io.snirf.read_nirs_element(
nirs_element: NirsElement,
opts: ReadSnirfOptions,
)[source]

Reads a single nirs element from a .snirf file into a Recording object.

Parameters:
  • nirs_element – Nirs data element as specified in the snirf documentation (Tucker et al. [TDK+22]).

  • opts – Options passed to read_snirf.

Returns:

Recording object containing the data from the nirs element.

Return type:

rec (Recording)

cedalion.io.snirf.read_snirf(
fname: Path | str,
crs: str = 'pos',
squeeze_aux: bool = False,
time_units: str | None = None,
) → list[Recording][source]

Reads a .snirf file into a list of Recording objects.

Parameters:
  • fname – Path to .snirf file

  • crs – the name of the geo3D’s coordinate reference system

  • squeeze_aux – If True, squeeze the aux data to remove dimensions of size 1.

  • time_units – If provided, this sets the units of the time coordinates. This is useful, when the snirf file specifies time units incorrectly or not at all.

Returns:

List of Recording objects containing the data from the nirs elements in the .snirf file.

Return type:

list[Recording]

cedalion.io.snirf.denormalize_measurement_list(
df_ml: DataFrame,
nirs_element: NirsElement,
)[source]

Enriches measurement list DataFrame with additional information.

Parameters:
  • df_ml (pd.DataFrame) – DataFrame containing the measurement list information.

  • nirs_element (NirsElement) – Nirs data element as specified in the snirf documentation (Tucker et al. [TDK+22]).

Returns:

DataFrame containing the measurement list information with

additional columns for channel, source, detector, wavelength and chromo.

Return type:

pd.DataFrame

cedalion.io.snirf.measurement_list_from_stacked(
stacked_array,
data_type,
trial_types,
stacked_channel='snirf_channel',
source_labels=None,
detector_labels=None,
wavelengths=None,
)[source]

Create a measurement list from a stacked array.

Parameters:
  • stacked_array (xr.DataArray) – Stacked array containing the data.

  • data_type (str) – Data type of the data.

  • trial_types (list[str]) – List of trial types.

  • stacked_channel (str) – Name of the channel dimension in the stacked array.

  • source_labels (list[str]) – List of source labels.

  • detector_labels (list[str]) – List of detector labels.

  • wavelengths (list[float]) – List of wavelengths.

Returns:

A tuple containing the source labels, detector labels, wavelengths, and

the measurement list.

Return type:

tuple

cedalion.io.snirf.write_snirf(
fname: Path | str,
recordings: Recording | list[Recording],
)[source]

Write one or more recordings to a .snirf file.

Parameters:
  • fname (Path | str) – Path to .snirf file.

  • recordings (Recording | list[Recording]) – Recording object(s) to write to the file.

cedalion.io.snirf.compress_snirf(
input: Path | str,
output: Path | str,
compression='gzip',
compression_opts=6,
chunks=True,
shuffle=True,
)[source]

Copy a SNIRF file with HDF5 compression applied where possible.

Parameters:
  • input – Path to the source SNIRF file.

  • output – Path for the compressed output file.

  • compression – HDF5 compression filter name (default "gzip").

  • compression_opts – Compression level; for gzip this is 0–9 (default 6).

  • chunks – Enable HDF5 chunked storage, required for compression (default True).

  • shuffle – Apply the byte-shuffle filter before compression to improve ratio (default True).

cedalion.io.utils module

HDF5/xarray serialisation helpers for cedalion I/O.

cedalion.io.utils.xarray_to_hdfgroup(
f: File,
array: DataArray,
name: str,
)[source]

Serialise an xr.DataArray into an HDF5 group.

Writes the array values, dimension names, and 1-D coordinates into a group at f[name]. String coordinates are stored with an HDF5 variable-length string dtype; numeric coordinates are stored as-is.

Parameters:
  • f – Open, writable HDF5 file object.

  • array – DataArray to serialise. All coordinates must be 1-D.

  • name – HDF5 group path to create (e.g. "fluence/scalp").

cedalion.io.utils.xarray_from_hdfgroup(f: File, path: str)[source]

Deserialise an xr.DataArray from an HDF5 group written by xarray_to_hdfgroup().

Parameters:
  • f – Open HDF5 file object.

  • path – HDF5 group path (e.g. "fluence/scalp").

Returns:

xr.DataArray reconstructed from the stored values, dims, and coordinates.

Module contents