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'},
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,
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
Utilities for converting fNIRS datasets to the BIDS standard.
Provides functions to organise raw SNIRF files into a BIDS directory tree,
generate BIDS-compliant filenames, create required sidecar files
(dataset_description.json, participants.tsv/.json,
_scans.tsv, _sessions.tsv), and read/write optode positions in the
BIDS _optodes.tsv / _coordsystem.json format.
References
Gorgolewski et al. [GAC+16], Luke et al. [LOC+25]
- cedalion.io.bids.find_files_with_pattern(
- start_dir: str | Path,
- pattern: str,
Recursively finds all files matching the given pattern.
Searches in the specified directory and subdirectories.
- Parameters:
start_dir – The directory to start the search from.
pattern – The pattern to match filenames against.
- Returns:
A list of file paths (as strings) of all files that match the pattern.
- cedalion.io.bids.create_bids_standard_filenames(
- row: Series,
Generates a BIDS compliant file name and its parent directory path.
Constructs a filename and directory path following the BIDS naming convention for a specific subject, session, task, acquisition, and run. The filename includes
_nirs.snirfas the extension and the directory is nested under anirssubdirectory.- Parameters:
row –
A row of a Pandas DataFrame with the following columns:
"sub": The subject identifier (e.g.,"01")."ses": The session identifier (e.g.,"01"), can be NaN."task": The task name or identifier (e.g.,"rest")."acq": The acquisition identifier, can be NaN."run": The run identifier (e.g.,"1"), can be NaN.
- Returns:
A tuple of
(bids_filename, parent_directory_path).
- cedalion.io.bids.copy_rename_snirf(row: Series, dataset_path: str, bids_dir: str)[source]
Copies and renames a .snirf into 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:
row (pd.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_path (str) – The path to the directory containing the original .snirf file(s) to be copied.
bids_dir (str) – 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 dataset_path and extracts acquisition times.
Looks for all _scans.tsv files in dataset_path, reads them into a DataFrame, and processes the filename and acq_time columns. If acq_time does not exist in the merged DataFrame, it is added with
Nonevalues. If no _scans.tsv files are found, an empty DataFrame with columns filename_org and acq_time is returned.- Parameters:
dataset_path (str) – The path to the dataset where the _scans.tsv files are located.
- Returns:
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, orNoneif the column does not exist in the original files.
- Return type:
pd.DataFrame
- cedalion.io.bids.search_for_acq_time_in_snirf_files(
- row: Series,
- dataset_path: str,
Extracts acquisition time from SNIRF files if missing in the _scans.tsv file.
Checks if acq_time is
NaNin the input row. If missing, loads the corresponding SNIRF file, extracts the measurement date and time, and returns it as an ISO 8601 timestamp string.- Parameters:
row – A row from
mapping_dfcontainingcurrent_nameandacq_timecolumns.dataset_path – Path to the dataset where the SNIRF files are located.
- Returns:
The acquisition timestamp extracted from the SNIRF file, or the existing
acq_timevalue if it is not missing.
- cedalion.io.bids.search_for_sessions_acq_time(dataset_path: str) DataFrame[source]
Searches _sessions.tsv files in the dataset path and returns session times.
Looks for all _sessions.tsv files in dataset_path, reads them into DataFrames, and extracts the subject ID and session acquisition time. If acq_time does not exist in the input files, it is added with
Nonevalues. Subject IDs are extracted from filenames using a regular expression.- Parameters:
dataset_path – The path to the dataset where _sessions.tsv files are located.
- Returns:
"ses": The session identifier (extracted from the filenames)."sub": The subject ID extracted from the filename."ses_acq_time": The session acquisition time, orNoneifacq_timedoes not exist in the original files.
- Return type:
A DataFrame with the following columns
- cedalion.io.bids.create_scan_files(group_df: DataFrame, bids_dir: str) None[source]
Creates and saves a _scans.tsv file per subject/session in the BIDS directory.
Generates a _scans.tsv for each group (by subject and session) in group_df. The file contains two columns: filename (relative path to the NIRS file) and acq_time (acquisition time).
- Parameters:
group_df – A grouped DataFrame for a particular subject and session. Must include at least the
bids_nameandacq_timecolumns.bids_dir – The path to the BIDS directory where _scans.tsv will be saved.
- cedalion.io.bids.create_session_files(group_df: DataFrame, bids_dir: str) None[source]
Creates and saves a _sessions.tsv file per subject in the BIDS directory.
Generates a _sessions.tsv for each subject in group_df. The file contains two columns: ses (session identifier) and acq_time (session acquisition time).
- Parameters:
group_df – A grouped DataFrame for a particular subject. Must include at least the
sesandses_acq_timecolumns.bids_dir – The path to the BIDS directory where _sessions.tsv will be saved.
- cedalion.io.bids.create_data_description(
- dataset_path: str,
- bids_dir: str,
- extra_meta_data: str | None = None,
Creates or updates dataset_description.json in the BIDS directory.
Checks for an existing dataset_description.json in dataset_path and updates it with relevant metadata. Additional metadata from extra_meta_data is merged in if provided. Missing required keys are filled with default values.
- Parameters:
dataset_path – The path to the dataset where dataset_description.json is located.
bids_dir – The path to the BIDS directory where the updated dataset_description.json will be saved.
extra_meta_data – Path to a JSON file with additional metadata to include. Defaults to
None.
- cedalion.io.bids.check_coord_files(bids_dir: str) None[source]
Checks for and updates
*_coordsystem.jsonfiles in a BIDS directory.Searches for files matching
*_coordsystem.jsonin bids_dir. IfNIRSCoordinateSystemis empty, it is set to"Other". Coordinate units are normalized to SI abbreviations (e.g."millimeter"→"mm"); unrecognized units are set to"n/a".- Parameters:
bids_dir – The path to the BIDS directory where
*_coordsystem.jsonfiles are located.
- cedalion.io.bids.create_participants_tsv(
- bids_dir: str,
- mapping_df: DataFrame,
- fields: List[str] | None = None,
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,
Creates or updates the BIDS participants.tsv and participants.json files.
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 participants by ID.
The corresponding participants.json is also updated or created based on the TSV’s columns. If no valid participants.tsv is found, falls back to generating new files from mapping_df.
- Parameters:
bids_dir – Path to the BIDS directory where output files will be written.
mapping_df – Used to create participants.tsv if no existing file is found.
participants_tsv_path – Path to an existing participants.tsv file.
participants_json_path – Path to an existing participants.json file.
fields – Fields to include in the schema. If
None, a default set is used.
- cedalion.io.bids.edit_events(row: Series, bids_dir: str) None[source]
Edits a BIDS
_events.tsvfile in place based on values in row.Updates the
"duration"and/or"trial_type"columns of the corresponding_events.tsvfile.- Parameters:
row –
A row from the mapping DataFrame with the following keys:
"cond": Serialised list of keys for mapping trial types, orNone."cond_match": Serialised list of replacement values, orNone."duration": Duration to write into every event, orNone."bids_name": Base name of the BIDS file used to locate the_events.tsv."parent_path": Relative path to the directory containing the_events.tsv.
bids_dir – The root directory of the BIDS dataset.
- cedalion.io.bids.sort_events(row: Series, bids_dir: str) None[source]
Sorts the events in a BIDS
_events.tsvfile by onset time.Locates the corresponding
_events.tsvfile for the given row, reads it, sorts events by the"onset"column, and overwrites the original file.- Parameters:
row – A row from a BIDS file metadata DataFrame. Must include
"bids_name"and"parent_path"keys.bids_dir – The root directory of the BIDS dataset.
- cedalion.io.bids.save_source(dataset_path: str, destination_path: str) None[source]
Copies the dataset into a
sourcedatafolder in destination_path.If a
sourcedatasubfolder already exists inside dataset_path, only that subfolder is copied. Otherwise the entire dataset is copied.- Parameters:
dataset_path – Path to the original dataset.
destination_path – Directory where the
sourcedatafolder will be created.
- cedalion.io.bids.export_to_bids_optodes_tsv(
- tsv_filename,
- points: Annotated[DataArray, DataArraySchema(dims='label', coords='label', 'label', 'type')],
- units='mm',
- float_format: str | None = None,
Export to a bids-conform _optodes.tsv.
- Parameters:
tsv_filename – Path to the output tsv file.
points – LabeledPoints to save.
units – coordinate units.
float_format – Format string for floating point numbers.
- cedalion.io.bids.load_from_bids_optodes_tsv(
- tsv_filename: Path | str,
Load optodes and landmarks from a BIDS *_optodes.tsv and its *_coordsystem.json.
The coordinate system name, units, and anatomical landmarks are read from the accompanying
*_coordsystem.jsonfile. The JSON is expected at the same path as the TSV, with_optodes.tsvreplaced by_coordsystem.json.- Parameters:
tsv_filename – Path to the BIDS
*_optodes.tsvfile.- Returns:
LabeledPoints with sources, detectors, and (if present) landmarks.
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:
FluenceFileinstead. 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:
objectContext-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) ...
- create_fluence_dataset(
- optode_pos: Annotated[DataArray, DataArraySchema(dims='label', coords='label', 'label', 'type')],
- wavelengths: ndarray,
- fluence_shape: tuple[int, int, int],
- units: str,
Create and initialise the
fluence_alldataset in the HDF5 file.Must be called once after opening in write mode, before any calls to
set_fluence_by_label()orset_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).
cedalion.io.nirs module
Read Homer2/AtlasViewer .nirs MATLAB files into Recording objects.
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,
Load a tsv file containing optodes or landmarks.
This function reads tsv-files with a column layout that differs from the NIRS-BIDS standard.
- 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.
This function writes tsv-files with a column layout that differs from the NIRS-BIDS standard.
- Parameters:
tsv_filename – Path to the output tsv file.
points – Points to save. Either an
xr.DataArray(optodes / landmarks / electrodes) or apd.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.jsonformat).- Parameters:
fname – Path to the JSON file.
crs – Coordinate reference system of the landmarks.
- Returns:
xr.DataArray containing landmark positions with
labelandtypecoordinates, 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.jsonfile.- Parameters:
fname – Path to the output JSON file.
landmarks – Landmark positions as an xr.DataArray with
labelcoordinate.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
.objmesh file.- Returns:
TrimeshSurface in the
"digitized"CRS with millimetre units.
- cedalion.io.probe_geometry.read_fieldtrip_elc(
- fname: Path | str,
Read electrode positions from a FieldTrip
.elcfile.- Parameters:
fname – Path to the
.elcfile.- Returns:
LabeledPoints with electrode positions,
labelandtypecoordinates, and pint units derived from the file header.
- cedalion.io.probe_geometry.read_sd(
- fname: Path | str,
- crs='av',
Read optode positions from a Homer/AtlasViewer
.matSD file.- Parameters:
fname – Path to the
.matSD 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:
EnumSNIRF data type codes as defined in the SNIRF specification.
- class cedalion.io.snirf.DataTypeLabel(value)[source]
Bases:
StrEnumSNIRF data type label strings as defined in the SNIRF specification.
- class cedalion.io.snirf.ReadSnirfOptions(squeeze_aux: bool, crs: str | None, time_units: str | None)[source]
Bases:
objectHelper class to pass options through read_snirf subroutines.
- cedalion.io.snirf.assign_data_type_group(
- data_type: DataType,
- data_type_label: DataTypeLabel,
- data_type_index: int,
- nirs_element: NirsElement,
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
DataTypeenum value.data_type_label – Parsed
DataTypeLabelenum value (may beNone).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
DataTypeenum.- Parameters:
value – Raw integer value from the SNIRF measurement list (or
None).- Returns:
Corresponding
DataTypemember, orNoneifvalueisNoneor 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
DataTypeLabelmember, orNoneifvalueisNoneor 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
NoneifvalueisNone.
- 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,
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,
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,
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,
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,
Reads a single nirs element from a .snirf file into a Recording object.
- cedalion.io.snirf.read_snirf(
- fname: Path | str,
- crs: str = 'pos',
- squeeze_aux: bool = False,
- time_units: str | None = None,
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,
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,
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.compress_snirf(
- input: Path | str,
- output: Path | str,
- compression='gzip',
- compression_opts=6,
- chunks=True,
- shuffle=True,
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,
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.