cedalion package
Subpackages
- cedalion.data package
- Module contents
get()get_ninja_cap_probe()get_ninja_uhd_cap_probe()get_snirf_test_data()get_colin27_segmentation()get_colin27_parcel_file()get_icbm152_segmentation()get_icbm152_parcel_file()get_fingertapping()get_fingertappingDOT()get_fingertapping_snirf_path()get_multisubject_fingertapping_snirf_paths()get_multisubject_fingertapping_path()get_photogrammetry_example_scan()get_precomputed_fluence()get_precomputed_sensitivity()get_nn22_resting_state()get_snirf2bids_example_dataset()get_fieldtrip_colin27_landmarks()get_spa_fnirs()HeadModelFilesHeadModelFiles.basedirHeadModelFiles.mask_filesHeadModelFiles.landmarks_ras_fileHeadModelFiles.brain_vertex_coordinatesHeadModelFiles.scalp_surface_objHeadModelFiles.brain_surface_objHeadModelFiles.freesurfer_surface_objHeadModelFiles.inflated_surface_objHeadModelFiles.parcel_colorsHeadModelFiles.voxel_to_vertex_mappingHeadModelFiles.load_parcel_colors()HeadModelFiles.load_voxel_to_vertex_mapping()HeadModelFiles.load_brain_vertex_coordinates()
get_colin27_headmodel_files()get_icbm152_headmodel_files()get_colin27_freesurfer_directory()get_icbm152_freesurfer_directory()
- Module contents
- cedalion.dataclasses package
- Submodules
- cedalion.dataclasses.accessors module
- cedalion.dataclasses.geometry module
PointTypeSurfaceVoxelsTrimeshSurfaceTrimeshSurface.meshTrimeshSurface.crsTrimeshSurface.unitsTrimeshSurface.meshTrimeshSurface.verticesTrimeshSurface.nverticesTrimeshSurface.nfacesTrimeshSurface.apply_transform()TrimeshSurface.decimate()TrimeshSurface.smooth()TrimeshSurface.get_vertex_normals()TrimeshSurface.fix_vertex_normals()TrimeshSurface.from_vtksurface()
VTKSurfaceSimpleMeshPycortexSurfacePycortexSurface.meshPycortexSurface.verticesPycortexSurface.nverticesPycortexSurface.nfacesPycortexSurface.apply_transform()PycortexSurface.decimate()PycortexSurface.get_vertex_normals()PycortexSurface.pptsPycortexSurface.connectedPycortexSurface.adjPycortexSurface.face_normalsPycortexSurface.vertex_normalsPycortexSurface.face_areasPycortexSurface.cotangent_weightsPycortexSurface.laplace_operatorPycortexSurface.avg_edge_lengthPycortexSurface.surface_gradient()PycortexSurface.geodesic_distance()PycortexSurface.geodesic_path()PycortexSurface.graphPycortexSurface.iter_surfedgesPycortexSurface.from_trimeshsurface()PycortexSurface.from_vtksurface()
affine_transform_from_numpy()robust_geodesic_distance()
- cedalion.dataclasses.recording module
RecordingRecording.timeseriesRecording.masksRecording.geo3dRecording.geo2dRecording.stimRecording.aux_tsRecording.aux_objRecording.head_modelRecording.meta_dataRecording.timeseriesRecording.masksRecording.geo3dRecording.geo2dRecording.stimRecording.aux_tsRecording.aux_objRecording.head_modelRecording.meta_dataRecording.get_timeseries()Recording.set_timeseries()Recording.get_mask()Recording.set_mask()Recording.get_timeseries_type()Recording.source_labelsRecording.detector_labelsRecording.wavelengthsRecording.trial_types
- cedalion.dataclasses.schemas module
- Module contents
- cedalion.dot package
- Submodules
- cedalion.dot.forward_model module
- cedalion.dot.head_model module
TwoSurfaceHeadModelTwoSurfaceHeadModel.segmentation_masksTwoSurfaceHeadModel.brainTwoSurfaceHeadModel.scalpTwoSurfaceHeadModel.landmarksTwoSurfaceHeadModel.t_ijk2rasTwoSurfaceHeadModel.t_ras2ijkTwoSurfaceHeadModel.voxel_to_vertex_brainTwoSurfaceHeadModel.voxel_to_vertex_scalpTwoSurfaceHeadModel.crsTwoSurfaceHeadModel.apply_transform()TwoSurfaceHeadModel.save()TwoSurfaceHeadModel.load()TwoSurfaceHeadModel.align_and_snap_to_scalp()TwoSurfaceHeadModel.segmentation_masksTwoSurfaceHeadModel.brainTwoSurfaceHeadModel.scalpTwoSurfaceHeadModel.landmarksTwoSurfaceHeadModel.t_ijk2rasTwoSurfaceHeadModel.t_ras2ijkTwoSurfaceHeadModel.voxel_to_vertex_brainTwoSurfaceHeadModel.voxel_to_vertex_scalpTwoSurfaceHeadModel.from_segmentation()TwoSurfaceHeadModel.from_surfaces()TwoSurfaceHeadModel.crsTwoSurfaceHeadModel.apply_transform()TwoSurfaceHeadModel.save()TwoSurfaceHeadModel.load()TwoSurfaceHeadModel.align_and_snap_to_scalp()TwoSurfaceHeadModel.snap_to_scalp_voxels()TwoSurfaceHeadModel.scale_to_landmarks()TwoSurfaceHeadModel.scale_to_headsize()TwoSurfaceHeadModel.get_brain_mni152_coords()
get_standard_headmodel()get_inflated_cortex_surface()
- cedalion.dot.image_recon module
- cedalion.dot.tissue_properties module
- cedalion.dot.utils module
- Module contents
- cedalion.geometry package
- cedalion.io package
- Submodules
- cedalion.io.anatomy module
- cedalion.io.bids module
read_events_from_tsv()check_for_bids_field()get_snirf2bids_mapping_csv()find_files_with_pattern()create_bids_standard_filenames()copy_rename_snirf()search_for_acq_time_in_scan_files()search_for_acq_time_in_snirf_files()search_for_sessions_acq_time()create_scan_files()create_session_files()create_data_description()check_coord_files()create_participants_tsv()create_participants_json()create_participants_files()edit_events()sort_events()save_source()
- cedalion.io.forward_model module
save_Adot()load_Adot()save_fluence()load_fluence()FluenceFileFluenceFile.fileFluenceFile.optode_labelsFluenceFile.wavelengthsFluenceFile.create_fluence_dataset()FluenceFile.get_fluence()FluenceFile.set_fluence_by_label()FluenceFile.set_fluence_by_index()FluenceFile.get_fluence_at_optodes()FluenceFile.set_fluence_at_optodes()FluenceFile.get_fluence_all()
- cedalion.io.nirs module
- cedalion.io.photogrammetry module
- cedalion.io.probe_geometry module
- cedalion.io.snirf module
DataTypeDataType.CW_AMPLITUDEDataType.CW_FLUORESCENCE_AMPLITUDEDataType.FD_AC_AMPLITUDEDataType.FD_PHASEDataType.FD_FLUORESCENCE_AMPLITUDEDataType.FD_FLUORESCENCE_PHASEDataType.TDG_AMPLITUDEDataType.TDG_FLUORESCENCE_AMPLITUDEDataType.TDM_AMPLITUDEDataType.TDM_FLUORESCENCE_AMPLITUDEDataType.DCS_G2DataType.DCS_BFIDataType.PROCESSED
DataTypeLabelDataTypeLabel.DODDataTypeLabel.DMEANDataTypeLabel.DVARDataTypeLabel.DSKEWDataTypeLabel.MUADataTypeLabel.MUSPDataTypeLabel.HBODataTypeLabel.HBRDataTypeLabel.HBTDataTypeLabel.H2ODataTypeLabel.LIPIDDataTypeLabel.BFIDataTypeLabel.HRF_DODDataTypeLabel.HRF_DMEANDataTypeLabel.HRF_DVARDataTypeLabel.HRF_DSKEWDataTypeLabel.HRF_HBODataTypeLabel.HRF_HBRDataTypeLabel.HRF_HBTDataTypeLabel.HRF_BFIDataTypeLabel.RAW_SATORIDataTypeLabel.RAW_NIRXDataTypeLabel.MOMENTS_KERNEL
ReadSnirfOptionsassign_data_type_group()parse_data_type()parse_data_type_label()parse_data_type_index()reduce_ndim_sourceLabels()labels_and_positions()geometry_from_probe()measurement_list_to_dataframe()meta_data_tags_to_dict()stim_to_dataframe()read_aux()add_number_to_name()read_data_elements()read_nirs_element()read_snirf()denormalize_measurement_list()measurement_list_from_stacked()write_snirf()
- cedalion.io.utils module
- Module contents
- cedalion.math package
- cedalion.mlutils package
- cedalion.models package
- cedalion.nirs package
- cedalion.sigdecomp package
- cedalion.sigproc package
- cedalion.sim package
- cedalion.vis package
Submodules
cedalion.errors module
Cedalion-specific exceptions.
- exception cedalion.errors.CRSMismatchError[source]
Bases:
ValueErrorError when coordinate reference systems do not match.
- classmethod unexpected_crs(expected_crs: str, found_crs: str)[source]
Construct error for a coordinate system that differs from the expected one.
- Parameters:
expected_crs – Name of the coordinate reference system that was required.
found_crs – Name of the coordinate reference system that was encountered.
- Returns:
Ready-to-raise exception instance.
- Return type:
- classmethod wrong_transform(current_crs: str, transform_crs: tuple[str])[source]
Construct error when an affine transform’s CRS does not match the object’s.
- Parameters:
current_crs – CRS name of the object being transformed.
transform_crs – CRS names encoded in the transform (source, target).
- Returns:
Ready-to-raise exception instance.
- Return type:
cedalion.physunits module
Builds on pint_xarray’s unit registry.
cedalion.plots module
cedalion.tasks module
cedalion.testing module
Utilitiy functions for tests.
- cedalion.testing.temporary_filename(suffix: str = None) Iterator[Path][source]
Context that creates a temporary file, returns its name and deletes it on exit.
Using this context to create a temporay files works around the problem that on Windows an open temporary files may not be reopened again.
Adapted from https://stackoverflow.com/a/57701186.
- Parameters:
suffix – filename extension
- Yields:
The path of the temporary file.
cedalion.typing module
Type aliases for Cedalion dataclasses.
Cedalion relies as much as possible on generic data types (like xarray DataArrays). We then use type aliases and annotations to augment these data types with additional information about the data they carry. For DataArrays there is a basic mechanism to specify and validate data schemas that specify dimension and coordinate names. This way we can distinguish between time series DataArrays (NDTimeSeries) and DataArrays representing points in space (LabeledPoints). By using these aliases in type hints we indicate to user which kind of DataArray is expected.
Parameters with physical units are represented by cedalion.Quantity. Aliases are defined to indicate the dimensionality of quantities.
- cedalion.typing.LabeledPoints[source]
DataArrays representing labeled points in space.
alias of
Annotated[DataArray,DataArraySchema(dims=(‘label’,), coords=((‘label’, (‘label’, ‘type’)),))]
- cedalion.typing.NDTimeSeries[source]
DataArrays representing time series.
alias of
Annotated[DataArray,DataArraySchema(dims=(‘time’,), coords=((‘time’, (‘time’, ‘samples’)),))]
- cedalion.typing.QLength[source]
Quantities with units of length
alias of
Annotated[Quantity, ‘[length]’]
cedalion.utils module
Utility functions.
- cedalion.utils.zero_padded_numbers(numbers: list[int], prefix: str = '') list[str][source]
Format integers as zero-padded strings sized to the largest value.
For example,
[0, 1, 13]becomes["00", "01", "13"]. The padding width is determined by the highest absolute value in the list.- Parameters:
numbers – List of integers to format.
prefix – Optional string prepended to each formatted number.
- Returns:
List of zero-padded strings, one per input number.
- cedalion.utils.deprecated_api(message)[source]
Issue a
DeprecationWarningwith the given message.- Parameters:
message – Human-readable description of what is deprecated and what to use instead.
- cedalion.utils.deprecated(reason: str)[source]
Decorator that marks a function as deprecated.
Wraps the decorated function so that every call emits a
DeprecationWarningnaming the function and the reason for deprecation.- Parameters:
reason – Explanation of why the function is deprecated and, where applicable, what should be used instead.
- Returns:
A decorator that wraps the target function.
cedalion.validators module
Validators for common data structures.
cedalion.vtktutils module
Conversion utilities between VTK, PyVista, and Trimesh mesh representations.
cedalion.xrutils module
Utility functions for xarray objects.
- cedalion.xrutils.pinv(array: DataArray) DataArray[source]
Calculate the pseudoinverse of a 2D xr.DataArray.
- FIXME: handles unitless and quantified DataArrays but not
DataArrays with units in their attrs.
- Parameters:
array (xr.DataArray) – Input array
- Returns:
Pseudoinverse of the input array
- Return type:
array_inv (xr.DataArray)
- cedalion.xrutils.norm(
- array: DataArray,
- dim: str,
Calculate the vector norm along a given dimension.
Extends the behavior of numpy.linalg.norm to xarray DataArrays.
- Parameters:
array (xr.DataArray) – Input array
dim (str) – Dimension along which to calculate the norm
- Returns:
Array with the norm along the specified dimension
- Return type:
normed (xr.DataArray)
- cedalion.xrutils.mask(
- array: DataArray,
- initval: bool,
Create a boolean mask DataArray with the same shape as array.
- Parameters:
array – Template DataArray whose shape, dims, and coords are copied.
initval – Initial boolean value to fill the mask with (
TrueorFalse).
- Returns:
A boolean DataArray with the same shape and coordinates as array.
- cedalion.xrutils.apply_mask(
- data_array: DataArray,
- mask: DataArray,
- operator: str,
- dim_collapse: str,
Apply a boolean mask to a DataArray according to the defined
operator.- Parameters:
data_array – Input NDTimeSeries (xr.DataArray).
mask – Boolean mask array whose dimensions must be a subset of
data_array’s dimensions.operator – How to apply the mask.
"nan"inserts NaN where the mask isFalse;"drop"removes those elements entirely.dim_collapse – Mask dimension to collapse to, merging boolean values along all other dimensions before applying. Pass
"none"to skip collapsing. For example, collapsing to"channel"will drop or NaN an entire channel if it isFalsealong any other dimension.
- Returns:
A tuple
(masked_data_array, masked_elements)wheremasked_data_arrayis the input array with the mask applied, andmasked_elementsis a list of the masked label values (whendim_collapseis not"none") or the string"N/A"otherwise.
- cedalion.xrutils.convolve(
- data_array: DataArray,
- kernel: ndarray,
- dim: str,
Convolve a DataArray with a 1-D kernel along the specified dimension.
Uses
np.convolvein"same"mode so the output has the same length as the input along dim. Pint units are preserved.- Parameters:
data_array – Input DataArray. May be unit-quantified.
kernel – 1-D convolution kernel.
dim – Name of the dimension along which to convolve.
- Returns:
Convolved DataArray with the same shape, dims, and units as data_array.
- Raises:
ValueError – If dim is not a dimension of data_array.
- cedalion.xrutils.spatial_dim(data_array: DataArray) str[source]
Return the name of the spatial dimension present in data_array.
Checks for the dimensions
"channel","parcel", and"vertex"in that order and returns the first one found.- Parameters:
data_array – DataArray to inspect.
- Returns:
Name of the spatial dimension (
"channel","parcel", or"vertex").- Raises:
ValueError – If none of the known spatial dimensions are present.
- cedalion.xrutils.other_dim(data_array: DataArray, *dims: str) str[source]
Get the dimension name not listed in
dims.Checks that there is exactly one more dimension in
data_arraythan the number of names supplied indimsand returns its name.- Parameters:
data_array – Input DataArray.
*dims – Names of dimensions to exclude.
- Returns:
Name of the single remaining dimension not listed in
dims.- Raises:
ValueError – If
data_arraydoes not have exactlylen(dims) + 1dimensions, or if any of the supplieddimsare not present.
- cedalion.xrutils.coords_from_other(
- source: DataArray,
- dims: list[str] = None,
- **aux_coords,
Create a dictionary of coordinates from source for matching dims in target.
- Parameters:
source – the DataArray to copy the coordinates from.
dims – a list of dimensions names. If specified, copy only coords for those dims.
aux_coords – additional key-value pairs to add to the resulting coords dict.
- Returns:
A dictionary that can be passed to DataArray.assign_coords.
- cedalion.xrutils.unit_stripping_is_error(is_error: bool = True)[source]
Promote
UnitStrippedWarningto an exception (or revert that promotion).Useful for debugging: once raised as an error, the debugger can pinpoint the exact cedalion or third-party call that silently drops pint units.
- Parameters:
is_error – If
True(default), convert the warning to an error. IfFalse, remove the error filter so the warning is emitted normally.
- cedalion.xrutils.unit_stripping_is_quiet(is_quiet: bool = True)[source]
Suppress
UnitStrippedWarningglobally (or restore the default behaviour).Not recommended for production code. Prefer
unit_stripping_is_error()to locate and fix the source of the warning rather than silencing it.- Parameters:
is_quiet – If
True(default), add an"ignore"filter for the warning. IfFalse, remove any such filter.
- cedalion.xrutils.drop_duplicate_dimensions(
- array: DataArray,
Remove constant dimensions from array, keeping only those that vary.
After stacking and unstacking, coordinate arrays are sometimes attributed to multiple dimensions even though their values only change along a single one. This function drops any dimension where all values are identical (i.e. the coordinate is effectively scalar along that dimension).
- Parameters:
array – DataArray that may contain constant dimensions introduced by stacking/unstacking operations.
- Returns:
DataArray with constant dimensions removed and their scalar coordinates dropped.
- cedalion.xrutils.unstack(
- array: DataArray,
- unstack_dim: str,
- stacked_dims: tuple[str],
Unstack a stacked DataArray.
This function unstacks a DataArray in which dimensions ‘stacked_dims’ have been stacked into the dimension ‘unstack_dim’. The function further processes unstacked coordinate arrays, so that they are attributed only to their respective dimension.
- Parameters:
array – the stacked DataArray
unstack_dim – the dimension to unstack
stacked_dims – The dimensions that were stacked together in the order given to DataArray.stack.
- Returns:
The unstacked array.
- cedalion.xrutils.contract(
- a1: DataArray,
- a2: DataArray,
- dim: str | list[str],
Apply xr.dot after asserting compatible shapes.
xr.dot will silently multiply arrays along dimensions which differ in shape if these arrays have an overlap in coordinates. This function requires an exact match in coordinates before calling xr.dot.
- Parameters:
a1 – first operand
a2 – second operand
dim – dimension(s) to contract over
- Returns:
the result of xr.dot.
- cedalion.xrutils.transpose_like(
- a: DataArray,
- target: DataArray,
- dim_map: dict[str, str] | None = None,
Transpose a so its dimension order matches that of target.
- Parameters:
a – DataArray to reorder.
target – DataArray whose dimension order is used as the reference.
dim_map – Optional mapping from dimension names in a to their corresponding names in target, for dimensions that have been renamed between the two arrays.
- Returns:
View of a with dimensions reordered to match target.
- Raises:
ValueError – If a dimension of a cannot be found in target (even after applying dim_map).
- cedalion.xrutils.dot_dataarray_csr(a: ~xarray.core.dataarray.DataArray, b: <module 'scipy.sparse' from '/home/runner/miniconda3/envs/cedalion/lib/python3.11/site-packages/scipy/sparse/__init__.py'>, bdims: list[str, str]) DataArray[source]
Multiply a dense DataArray by a sparse matrix along their shared dimension.
The shared dimension is inferred from the overlap between a’s dims and bdims. All other dimensions of a are kept intact. The result has the same non-contracted dimensions as a plus the remaining dimension of b.
- Parameters:
a – Dense DataArray. Must share exactly one dimension with bdims.
b – Sparse matrix (CSR or compatible SciPy sparse format).
bdims – Two-element list naming the row and column dimensions of b, e.g.
["vertex", "channel"].
- Returns:
Dense DataArray resulting from the contraction. Dimension order matches the original ordering in a (with the contracted dim replaced by the remaining dim of b).
- Raises:
ValueError – If a and b do not share exactly one dimension, or if the sizes along the shared dimension do not match.
- cedalion.xrutils.check_units(array: DataArray, dimension: str) bool[source]
Return whether array has physical units compatible with dimension.
Works for both quantified DataArrays (
array.pint.unitsis set) and dequantified ones (units stored inarray.attrs["units"]).- Parameters:
array – DataArray to check.
dimension – Pint dimensionality string, e.g.
"[length]","[time]","[concentration]".
- Returns:
Trueif the array’s units are dimensionally compatible with dimension,Falseif the array carries no unit information.