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')[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.

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.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.

This method uses a lossy compression algorithm to reduce file size.

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

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]
get_fluence(label: str, wavelength: float) ndarray[source]
set_fluence_by_label(label: str, wavelength: float, fluence: ndarray)[source]
set_fluence_by_index(i_label: int, i_wl: int, fluence: ndarray)[source]
get_fluence_at_optodes()[source]
set_fluence_at_optodes(fluence_at_optodes: DataArray)[source]
get_fluence_all()[source]

cedalion.io.nirs module

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

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 (str) – Path to the tsv file.

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

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

  • Returns

  • -------

  • xr.DataArray – Optodes or landmarks as a Data

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

Export optodes, fiducials, landmarks, electodes, measurement lists to a tsv file.

Parameters:
  • tsv_filename (str) – Path to the output file.

  • points (xr.DataArray, pd.DataFrame) – Points to save.

Return type:

None

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

Read a JSON file containing landmarks.

Parameters:
  • fname (str) – Path to the JSON file.

  • crs (str) – Coordinate reference system of the landmarks.

  • Returns

  • -------

  • xr.DataArray – Landmarks as a DataArray.

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

Save landmarks to a JSON file.

Parameters:
  • fname (str) – Path to the output file.

  • landmarks (xr.DataArray) – Landmarks to save.

  • crs (str) – Coordinate system of the landmarks.

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

Read a file containing digitized points.

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

  • units (str) – Units of the points.

  • Returns

  • -------

  • xr.DataArray – Digitized points as a DataArray.

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

Read a textured triangle mesh generated by Einstar devices.

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

  • Returns

  • -------

  • TrimeshSurface – Triangle

cedalion.io.snirf module

Contains functionality for handling .snirf files.

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

Bases: Enum

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

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]
cedalion.io.snirf.assign_data_type_group(
data_type: DataType,
data_type_label: DataTypeLabel,
data_type_index: int,
nirs_element: NirsElement,
) str[source]

Define groupings of data_type, data_type_label and data_type_index.

The snirf standard allows to put different data types into the same data element. Satori does this to store processing results. Kernel stores different moments in the same data element. When reading such data elements, their content must be grouped by data type and the groups will be individually packaged in DataArrays.

To this end, combinations of data_type, data_type_label and data_type_index are mapped to a data_type_group string.

cedalion.io.snirf.parse_data_type(value) DataType | None[source]
cedalion.io.snirf.parse_data_type_label(value) DataTypeLabel | None[source]
cedalion.io.snirf.parse_data_type_index(value) int | None[source]
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: dict[str, Any],
) 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 (dict[str, Any]) –

    Options for reading the aux data. The following options are supported: - squeeze_aux (bool): If True, squeeze the aux data to remove

    dimensions of size 1.

Returns:

Dictionary containing the aux data

Return type:

result (OrderedDict[str, xr.DataArray])

cedalion.io.snirf.add_number_to_name(name, keys)[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,
) 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.

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, opts)[source]

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

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

  • opts (dict[str, Any]) –

    Options for reading the data element. The following options are supported: - squeeze_aux (bool): If True, squeeze the aux data to remove

    dimensions of size 1.

    • crs (str): name of the geo?d’s coordinate reference system.

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,
) 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.

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.

Module contents