cedalion.dataclasses package

Submodules

cedalion.dataclasses.accessors module

class cedalion.dataclasses.accessors.CedalionAccessor(xarray_obj)

Bases: object

Accessor for time series data stored in xarray DataArrays.

freq_filter(fmin, fmax, butter_order=4)

Applys a Butterworth filter.

Parameters:
  • fmin (float) – The lower cutoff frequency.

  • fmax (float) – The upper cutoff frequency.

  • butter_order (int) – The order of the Butterworth filter.

Returns:

The filtered time series.

Return type:

result (xarray.DataArray)

property sampling_rate

Return the sampling rate of the time series.

The sampling rate is calculated as the reciprocal of the mean time difference

between consecutive samples.

to_epochs(df_stim, trial_types, before, after)

Extract epochs from the time series based on stimulus events.

Parameters:
  • df_stim (pandas.DataFrame) – DataFrame containing stimulus events.

  • trial_types (list) – List of trial types to include in the epochs.

  • before (float) – Time in seconds before stimulus event to include in epoch.

  • after (float) – Time in seconds after stimulus event to include in epoch.

Returns:

Array containing the extracted epochs.

Return type:

xarray.DataArray

class cedalion.dataclasses.accessors.PointsAccessor(xarray_obj)

Bases: object

add(label, coordinates, type, group=None)
Return type:

DataArray

apply_transform(transform)
common_labels(other)

Return labels contained in both LabledPointClouds.

Return type:

List[str]

property crs
remove(label)
rename(translations)
set_crs(value)
to_homogeneous()
class cedalion.dataclasses.accessors.StimAccessor(pandas_obj)

Bases: object

Accessor for stimulus DataFrames.

conditions()
rename_events(rename_dict)

Renames trial types in the DataFrame based on the provided dictionary.

Parameters:

rename_dict (dict) – A dictionary with the old trial type as key and the new trial type as value.

to_xarray(time)

cedalion.dataclasses.geometry module

class cedalion.dataclasses.geometry.PointType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

Bases: Enum

DETECTOR = 2
LANDMARK = 3
SOURCE = 1
UNKNOWN = 0
class cedalion.dataclasses.geometry.PycortexSurface(mesh, crs, units)

Bases: Surface

Provides the geodesic functionality of Pycortex.

References

Functions in this class are based on the implementation in Pycortex (Gao et al. [GHLG15]). Gao JS, Huth AG, Lescroart MD and Gallant JL (2015) Pycortex: an interactive surface visualizer for fMRI. Front. Neuroinform. 9:23. doi: 10.3389/fninf.2015.00023

property adj: csr_matrix

Sparse vertex adjacency matrix.

apply_transform(transform)
Return type:

PycortexSurface

property avg_edge_length

Average length of all edges in the surface.

property connected: csr_matrix

Sparse matrix of vertex-face associations.

property cotangent_weights: ndarray

Cotangent of angle opposite each vertex in each face.

decimate(face_count)
Return type:

PycortexSurface

property face_areas: ndarray

Area of each face.

property face_normals: ndarray

Normal vector for each face.

classmethod from_trimeshsurface(tri_mesh)
classmethod from_vtksurface(vtk_surface)
geodesic_distance(verts, m=1.0, fem=False)

Calcualte the inimum mesh geodesic distance (in mm).

The geodesic distance is calculated from each vertex in surface to any vertex in the collection verts.

Geodesic distance is estimated using heat-based method (see ‘Geodesics in Heat’, Crane et al, 2012). Diffusion of heat along the mesh is simulated and then used to infer geodesic distance. The duration of the simulation is controlled by the parameter m. Larger values of m will smooth & regularize the distance computation. Smaller values of m will roughen and will usually increase error in the distance computation. The default value of 1.0 is probably pretty good.

This function caches some data (sparse LU factorizations of the laplace-beltrami operator and the weighted adjacency matrix), so it will be much faster on subsequent runs.

The time taken by this function is independent of the number of vertices in verts.

Parameters:
  • verts – 1D array-like of ints Set of vertices to compute distance from. This function returns the shortest distance to any of these vertices from every vertex in the surface.

  • m – float, optional Reverse Euler step length. The optimal value is likely between 0.5 and 1.5. Default is 1.0, which should be fine for most cases.

  • fem – bool, optional Whether to use Finite Element Method lumped mass matrix. Wasn’t used in Crane 2012 paper. Doesn’t seem to help any.

Returns:

1D ndarray, shape (total_verts,) Geodesic distance (in mm) from each vertex in the surface to the closest vertex in verts.

geodesic_path(a, b, max_len=1000, d=None, **kwargs)

Finds the shortest path between two points a and b.

This shortest path is based on geodesic distances across the surface. The path starts at point a and selects the neighbor of a in the graph that is closest to b. This is done iteratively with the last vertex in the path until the last point in the path is b.

Other Parameters in kwargs are passed to the geodesic_distance function to alter how geodesic distances are actually measured

Parameters:
  • a – int Vertex that is the start of the path

  • b – int Vertex that is the end of the path

  • d – array array of geodesic distances, will be computed if not provided

  • max_len – int, optional, default=1000 Maximum path length before the function quits. Sometimes it can get stuck in loops, causing infinite paths.

  • m – float, optional Reverse Euler step length. The optimal value is likely between 0.5 and 1.5. Default is 1.0, which should be fine for most cases.

  • fem – bool, optional Whether to use Finite Element Method lumped mass matrix. Wasn’t used in Crane 2012 paper. Doesn’t seem to help any.

  • kwargs – other arugments are passed to self.geodesic_distance

Returns:

list

List of the vertices in the path from a to b

Return type:

path

get_vertex_normals(points)
property laplace_operator

Laplace-Beltrami operator for this surface.

A sparse adjacency matrix with edge weights determined by the cotangents of the angles opposite each edge. Returns a 4-tuple (B, D, W, V) where D is the ‘lumped mass matrix’, W is the weighted adjacency matrix, and V is a diagonal matrix that normalizes the adjacencies. The ‘stiffness matrix’, A, can be computed as V - W.

The full LB operator can be computed as D^{-1} (V - W).

B is the finite element method (FEM) ‘mass matrix’, which replaces D in FEM analyses.

See ‘Discrete Laplace-Beltrami operators for shape analysis and segmentation’ by Reuter et al., 2009 for details.

mesh: SimpleMesh
property nfaces: int
property nvertices: int
property ppts: ndarray

3D matrix of points in each face.

n faces x 3 per face x 3 coords per point.

surface_gradient(scalars, at_verts=True)

Gradient of a function with values scalars at each vertex on the surface.

If at_verts, returns values at each vertex. Otherwise, returns values at each face.

Parameters:
  • scalars – 1D ndarray, shape (total_verts,) a scalar-valued function across the cortex.

  • at_verts – bool, optional If True (default), values will be returned for each vertex. Otherwise, values will be returned for each face.

Returns:

2D ndarray, shape (total_verts,3) or (total_polys,3)

Contains the x-, y-, and z-axis gradients of the given scalars at either each vertex (if at_verts is True) or each face.

Return type:

gradu

property vertex_normals: ndarray

Normal vector for each vertex (average of normals for neighboring faces).

property vertices: Annotated[DataArray, DataArraySchema(dims='label', coords='label', 'label', 'type')]
class cedalion.dataclasses.geometry.SimpleMesh(pts, polys)

Bases: object

polys: ndarray
pts: ndarray
class cedalion.dataclasses.geometry.Surface(mesh, crs, units)

Bases: ABC

abstract apply_transform(transform)
crs: str
property kdtree
mesh: Any
abstract property nfaces: int
abstract property nvertices: int
snap(points)
units: Unit
abstract property vertices: Annotated[DataArray, DataArraySchema(dims='label', coords='label', 'label', 'type')]
class cedalion.dataclasses.geometry.TrimeshSurface(mesh, crs, units)

Bases: Surface

apply_transform(transform)
Return type:

TrimeshSurface

decimate(face_count)

Use quadric decimation to reduce the number of vertices.

Parameters:

face_count (int) – the number of faces of the decimated mesh

Return type:

TrimeshSurface

Returns:

The surface with a decimated mesh

fix_vertex_normals()
classmethod from_vtksurface(vtk_surface)
get_vertex_normals(points)

Get normals of vertices closest to the provided points.

mesh: Trimesh
property nfaces: int
property nvertices: int
smooth(lamb)

Apply a Taubin filter to smooth this surface.

Return type:

TrimeshSurface

property vertices: Annotated[DataArray, DataArraySchema(dims='label', coords='label', 'label', 'type')]
class cedalion.dataclasses.geometry.VTKSurface(mesh, crs, units)

Bases: Surface

apply_transform(transform)
decimate(reduction, **kwargs)

Use VTK’s decimate_pro method to reduce the number of vertices.

Parameters:
  • reduction (float) – Reduction factor. A value of 0.9 will leave 10% of the original number of vertices.

  • **kwargs – additional keyword arguments are passed to decimate_pro

Return type:

VTKSurface

Returns:

The surface with a decimated mesh

classmethod from_trimeshsurface(tri_mesh)
mesh: vtkPolyData
property nfaces: int
property nvertices: int
property vertices: Annotated[DataArray, DataArraySchema(dims='label', coords='label', 'label', 'type')]
cedalion.dataclasses.geometry.affine_transform_from_numpy(transform, from_crs, to_crs, from_units, to_units)
Return type:

DataArray

cedalion.dataclasses.recording module

class cedalion.dataclasses.recording.Recording(timeseries=<factory>, masks=<factory>, geo3d=<factory>, geo2d=<factory>, stim=<factory>, aux_ts=<factory>, aux_obj=<factory>, head_model=None, meta_data=<factory>, _measurement_lists=<factory>)

Bases: object

Main container for analysis objects.

The Recording class holds timeseries adjunct objects in ordered dictionaries. It maps to the NirsElement in the snirf format but it also holds additional attributes (masks, headmodel, aux_obj) for which there is no corresponding entity in the snirf format.

aux_obj: OrderedDict[str, Any]
aux_ts: OrderedDict[str, Annotated[DataArray]]
property detector_labels
geo2d: Annotated[DataArray]
geo3d: Annotated[DataArray]
get_mask(key=None)
Return type:

DataArray

get_timeseries(key=None)
Return type:

DataArray

get_timeseries_type(key)
head_model: Optional[Any] = None
masks: OrderedDict[str, DataArray]
meta_data: OrderedDict[str, Any]
set_mask(key, value, overwrite=False)
set_timeseries(key, value, overwrite=False)
property source_labels
stim: DataFrame
timeseries: OrderedDict[str, Annotated[DataArray]]
property trial_types
property wavelengths

cedalion.dataclasses.schemas module

class cedalion.dataclasses.schemas.DataArraySchema(dims, coords)

Bases: object

coords: tuple[tuple[str, tuple[str]]]
dims: tuple[str]
validate(data_array)
exception cedalion.dataclasses.schemas.ValidationError

Bases: Exception

cedalion.dataclasses.schemas.build_labeled_points(coordinates=None, crs='pos', units='1', labels=None, types=None)
cedalion.dataclasses.schemas.build_stim_dataframe()
cedalion.dataclasses.schemas.build_timeseries(data, dims, time, channel, value_units, time_units, other_coords={})
cedalion.dataclasses.schemas.validate_schemas(func)
cedalion.dataclasses.schemas.validate_stim_schema(df)

Module contents

Common classes.