cedalion.dataclasses package

Submodules

cedalion.dataclasses.accessors module

Accessors for Cedalion data types.

class cedalion.dataclasses.accessors.CedalionAccessor(xarray_obj)[source]

Bases: object

Accessor for time series data stored in xarray DataArrays.

property sampling_rate[source]

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: pd.DataFrame,
trial_types: list[str],
before: cdt.QTime,
after: cdt.QTime,
)[source]

Extract epochs from the time series based on stimulus events.

Parameters:
  • df_stim – DataFrame containing stimulus events.

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

  • before – Time before stimulus event to include in epoch.

  • after – Time after stimulus event to include in epoch.

Returns:

Array containing the extracted epochs.

Return type:

xarray.DataArray

freq_filter(fmin, fmax, butter_order=4)[source]

Apply a Butterworth bandpass 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)

class cedalion.dataclasses.accessors.PointsAccessor(xarray_obj)[source]

Bases: object

Accessor for LabeledPoints DataArrays.

Attached as the .points attribute on any DataArray that carries a "label" dimension and coordinate (i.e. a labeled point cloud such as geo3d or geo2d).

to_homogeneous()[source]

Return the point cloud augmented with a homogeneous coordinate of 1.

Appends a column of ones so that affine transforms can be applied with a single matrix multiplication. Units are preserved.

Returns:

LabeledPoints DataArray with shape (n_points, n_coords + 1).

rename(translations: Dict[str, str])[source]

Rename point labels according to a translation dictionary.

Parameters:

translations – Mapping from old label strings to new label strings. Labels not present in the mapping are kept unchanged.

Returns:

LabeledPoints DataArray with updated "label" coordinate.

common_labels(
other: DataArray,
) List[str][source]

Return labels present in both this and other LabeledPoints arrays.

Parameters:

other – Second LabeledPoints DataArray. Must have a "label" dimension and coordinate.

Returns:

Sorted list of label strings shared by both point clouds.

apply_transform(transform: cdt.AffineTransform | np.ndarray)[source]

Apply an affine transform to this point cloud.

Accepts either a cedalion AffineTransform (a 4×4 xr.DataArray with CRS-named dimensions and pint units) or a plain 4×4 numpy.ndarray.

Parameters:

transform – 4×4 affine transformation. If an xr.DataArray, the source CRS must match the current CRS of the point cloud.

Returns:

Transformed LabeledPoints DataArray in the new coordinate system.

Raises:
  • CRSMismatchError – If a DataArray transform’s source CRS does not match the current point cloud CRS.

  • ValueError – If transform is not a DataArray or ndarray.

property crs[source]

Name of the coordinate reference system dimension (the non-label dim).

Returns:

String name of the spatial dimension, e.g. "pos", "ras".

set_crs(value: str)[source]

Return a copy of this point cloud with the CRS dimension renamed.

Parameters:

value – New name for the spatial dimension.

Returns:

LabeledPoints DataArray with the CRS dimension renamed to value.

add(
label: str | List[str],
coordinates: ArrayLike,
type: PointType | List[PointType],
group: str | List[str] = None,
) cdt.LabeledPoints[source]

Append one or more points to this point cloud.

Parameters:
  • label – Label string (single point) or list of label strings.

  • coordinates – Coordinates of the new point(s). Shape (3,) for a single point or (n, 3) for multiple points.

  • typePointType (single point) or list thereof for multiple points.

  • group – Optional group string or list of group strings.

Returns:

New LabeledPoints DataArray with the added point(s) concatenated.

Raises:

KeyError – If a label already exists in the point cloud.

remove(label)[source]
class cedalion.dataclasses.accessors.StimAccessor(pandas_obj)[source]

Bases: object

Accessor for stimulus DataFrames.

rename_events(rename_dict)[source]

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.

conditions()[source]

Return the unique trial-type labels in the stimulus DataFrame.

Returns:

Array of unique trial-type strings.

to_xarray(time: DataArray)[source]
class cedalion.dataclasses.accessors.SMCallableWrapper(accessor, attr_name)[source]

Bases: object

Wraps a callable attribute of a statsmodels result object.

When StatsModelsAccessor resolves a callable attribute (e.g. summary()), it returns one of these wrappers. Calling the wrapper applies the method to every element in the 2-D array of result objects and collects the outputs into an xr.DataArray.

class cedalion.dataclasses.accessors.StatsModelsAccessor(array: DataArray)[source]

Bases: object

Accessor for DataArrays containing statsmodel results.

map(func: Callable, name: str = 'map')[source]

Applies a callable to each object in the array and returns a xr.DataArray.

Parameters:
  • func – a Callable that expects one argument, the object

  • name – used to name dimensions in the result array

Returns:

an xr.DataArray whose first to dimensions match our array and that holds in each cell the result of the function call.

regressor_variances()[source]

Return the variance of each regressor coefficient across all models.

Extracts the diagonal of the covariance matrix of parameter estimates for each model in the array.

Returns:

DataArray with the same first two dims as the results array plus a "regressor" dimension.

Raises:

NotImplementedError – If the underlying result objects are ContrastResults (which carry no parameter estimates).

t_values()[source]

Returns the t-values from each model result as a DataArray.

Returns:

An xarray.DataArray containing the t-values from each model result.

p_values()[source]

Return the p-values from each hypothesis test in the result objects.

Returns:

DataArray with the same first two dims as the results array plus a "hypothesis" dimension containing the p-values.

Raises:

NotImplementedError – If the result objects do not expose a pvalue attribute.

cedalion.dataclasses.geometry module

Dataclasses for representing geometric objects.

class cedalion.dataclasses.geometry.PointType(value)[source]

Bases: Enum

Categorical label for points in a LabeledPoints array.

Used as the "type" coordinate to distinguish optode types, anatomical landmarks, and EEG electrodes within the same point cloud.

UNKNOWN = 0[source]
SOURCE = 1[source]
DETECTOR = 2[source]
LANDMARK = 3[source]
ELECTRODE = 4[source]
class cedalion.dataclasses.geometry.Surface(
mesh: ~typing.Any,
crs: str,
units: ~pint.registry.Unit,
vertex_coords: dict[str,
~numpy._typing._array_like._Buffer | ~numpy._typing._array_like._SupportsArray[~numpy.dtype[~typing.Any]] | ~numpy._typing._nested_sequence._NestedSequence[~numpy._typing._array_like._SupportsArray[~numpy.dtype[~typing.Any]]] | bool | int | float | complex | str | bytes | ~numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]] = <factory>,
)[source]

Bases: ABC

Abstract base class for 3-D triangulated surfaces.

Concrete subclasses (TrimeshSurface, VTKSurface, PycortexSurface) wrap different mesh backends while sharing a common interface for coordinate access, KD-tree queries, and affine transforms.

mesh[source]

Backend mesh object (type depends on subclass).

Type:

Any

crs[source]

Name of the coordinate reference system (e.g. "ras").

Type:

str

units[source]

Physical units of the vertex coordinates.

Type:

pint.registry.Unit

vertex_coords[source]

Optional dict of extra per-vertex coordinate arrays (e.g. parcel labels) to attach as xarray coordinates.

Type:

dict[str, numpy._typing._array_like._Buffer | numpy._typing._array_like._SupportsArray[numpy.dtype[Any]] | numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]] | bool | int | float | complex | str | bytes | numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]

mesh: Any[source]
crs: str[source]
units: Unit[source]
vertex_coords: dict[str, _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes]][source]
abstract property vertices: Annotated[DataArray, DataArraySchema(dims='label', coords='label', 'label', 'type')][source]

Vertices of the mesh as a LabeledPoints array.

abstract property nvertices: int[source]

Number of vertices in the mesh.

abstract property nfaces: int[source]

Number of triangular faces in the mesh.

abstractmethod copy()[source]
abstractmethod apply_transform(transform: DataArray)[source]

Return a new surface with all vertices transformed by transform.

Parameters:

transform – 4×4 affine AffineTransform.

Returns:

A new surface instance of the same concrete type.

property kdtree[source]

KD-tree built lazily from vertex coordinates for fast spatial queries.

snap(
points: Annotated[DataArray, DataArraySchema(dims='label', coords='label', 'label', 'type')],
)[source]

Project points onto their nearest vertex on this surface.

Parameters:

points – LabeledPoints array in the same CRS and units as this surface.

Returns:

LabeledPoints array with the same labels as points but coordinates replaced by those of the closest surface vertex.

Raises:
  • CRSMismatchError – If points are not in the same CRS as the surface.

  • ValueError – If points have different units from the surface.

class cedalion.dataclasses.geometry.Voxels(voxels: ndarray, crs: str, units: Unit)[source]

Bases: object

3D voxels represented by a np.array.

voxels[source]

The voxels.

Type:

np.ndarray

crs[source]

The coordinate reference system of the voxels.

Type:

str

units[source]

The units of the voxels.

Type:

pint.Unit

voxels: ndarray[source]
crs: str[source]
units: Unit[source]
property vertices: Annotated[DataArray, DataArraySchema(dims='label', coords='label', 'label', 'type')][source]
property nvertices: int[source]
apply_transform(
transform: DataArray,
) Voxels[source]
property kdtree[source]
class cedalion.dataclasses.geometry.TrimeshSurface(
mesh: ~trimesh.base.Trimesh,
crs: str,
units: ~pint.registry.Unit,
vertex_coords: dict[str,
~numpy._typing._array_like._Buffer | ~numpy._typing._array_like._SupportsArray[~numpy.dtype[~typing.Any]] | ~numpy._typing._nested_sequence._NestedSequence[~numpy._typing._array_like._SupportsArray[~numpy.dtype[~typing.Any]]] | bool | int | float | complex | str | bytes | ~numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]] = <factory>,
)[source]

Bases: Surface

A surface represented by a trimesh object.

mesh[source]

The trimesh object representing the surface.

Type:

trimesh.Trimesh

crs[source]

The coordinate reference system of the surface.

Type:

str

units[source]

The units of the surface.

Type:

pint.Unit

mesh: Trimesh[source]
property vertices: Annotated[DataArray, DataArraySchema(dims='label', coords='label', 'label', 'type')][source]

Vertices of the mesh as a LabeledPoints array.

property nvertices: int[source]

Number of vertices in the mesh.

property nfaces: int[source]

Number of triangular faces in the mesh.

copy() TrimeshSurface[source]
apply_transform(
transform: DataArray,
) TrimeshSurface[source]

Apply an affine transformation to this surface.

Parameters:

transform (cdt.AffineTransform) – The affine transformation to apply.

Returns:

The transformed surface.

Return type:

TrimeshSurface

decimate(
face_count: int,
) TrimeshSurface[source]

Use quadric decimation to reduce the number of vertices.

Parameters:

face_count – the number of faces of the decimated mesh

Returns:

The surface with a decimated mesh

smooth(lamb: float) TrimeshSurface[source]

Apply a Taubin smoothing filter to the mesh.

Parameters:

lamb – Taubin lambda parameter controlling the amount of smoothing (typically between 0 and 1).

Returns:

A new TrimeshSurface with a smoothed mesh.

get_vertex_normals(
points: Annotated[DataArray, DataArraySchema(dims='label', coords='label', 'label', 'type')],
normalized=True,
)[source]

Return vertex normals at surface vertices nearest to points.

Parameters:
  • points – LabeledPoints query positions in the same CRS and units as this surface.

  • normalized – If True (default), return unit-length normals.

Returns:

DataArray of shape (n_points, 3) containing the normal vectors at the nearest surface vertices.

Raises:

ValueError – If normalization is requested but any normal has zero length.

fix_vertex_normals()[source]

Flip any vertex normals that point inward (towards the mesh centroid).

Returns:

A new TrimeshSurface with consistently outward-pointing vertex normals.

classmethod from_vtksurface(vtk_surface: VTKSurface)[source]
class cedalion.dataclasses.geometry.VTKSurface(
mesh: ~vtkmodules.vtkCommonDataModel.vtkPolyData,
crs: str,
units: ~pint.registry.Unit,
vertex_coords: dict[str,
~numpy._typing._array_like._Buffer | ~numpy._typing._array_like._SupportsArray[~numpy.dtype[~typing.Any]] | ~numpy._typing._nested_sequence._NestedSequence[~numpy._typing._array_like._SupportsArray[~numpy.dtype[~typing.Any]]] | bool | int | float | complex | str | bytes | ~numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]] = <factory>,
)[source]

Bases: Surface

A surface backed by a VTK vtkPolyData mesh.

mesh[source]

The underlying vtk.vtkPolyData object.

Type:

vtkmodules.vtkCommonDataModel.vtkPolyData

crs[source]

Name of the coordinate reference system.

Type:

str

units[source]

Physical units of the vertex coordinates.

Type:

pint.registry.Unit

mesh: vtkPolyData[source]
property vertices: Annotated[DataArray, DataArraySchema(dims='label', coords='label', 'label', 'type')][source]

Vertices of the mesh as a LabeledPoints array.

property nvertices: int[source]

Number of vertices in the mesh.

property nfaces: int[source]

Number of triangular faces in the mesh.

apply_transform(transform: DataArray)[source]

Return a new surface with all vertices transformed by transform.

Parameters:

transform – 4×4 affine AffineTransform.

Returns:

A new surface instance of the same concrete type.

copy()[source]
classmethod from_trimeshsurface(tri_mesh: TrimeshSurface)[source]
decimate(
reduction: float,
**kwargs,
) VTKSurface[source]

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

Parameters:
  • reduction – 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

Returns:

The surface with a decimated mesh

class cedalion.dataclasses.geometry.SimpleMesh(pts: ndarray, polys: ndarray)[source]

Bases: object

Lightweight mesh container for vertex positions and face indices.

pts[source]

Vertex positions, shape (n_vertices, 3).

Type:

numpy.ndarray

polys[source]

Triangle face indices, shape (n_faces, 3).

Type:

numpy.ndarray

pts: ndarray[source]
polys: ndarray[source]
class cedalion.dataclasses.geometry.PycortexSurface(
mesh: SimpleMesh,
crs: str,
units: Unit,
)[source]

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

mesh: SimpleMesh[source]
property vertices: Annotated[DataArray, DataArraySchema(dims='label', coords='label', 'label', 'type')][source]

Vertices of the mesh as a LabeledPoints array.

property nvertices: int[source]

Number of vertices in the mesh.

property nfaces: int[source]

Number of triangular faces in the mesh.

copy()[source]
apply_transform(
transform: DataArray,
) PycortexSurface[source]

Return a new surface with all vertices transformed by transform.

Parameters:

transform – 4×4 affine AffineTransform.

Returns:

A new surface instance of the same concrete type.

decimate(
face_count: int,
) PycortexSurface[source]
get_vertex_normals(
points: Annotated[DataArray, DataArraySchema(dims='label', coords='label', 'label', 'type')],
normalized=True,
)[source]
property ppts: ndarray[source]

3D matrix of points in each face.

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

property connected: csr_matrix[source]

Sparse matrix of vertex-face associations.

property adj: csr_matrix[source]

Sparse vertex adjacency matrix.

property face_normals: ndarray[source]

Normal vector for each face.

property vertex_normals: ndarray[source]

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

property face_areas: ndarray[source]

Area of each face.

property cotangent_weights: ndarray[source]

Cotangent of angle opposite each vertex in each face.

property laplace_operator[source]

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.

property avg_edge_length[source]

Average length of all edges in the surface.

surface_gradient(scalars, at_verts=True)[source]

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

geodesic_distance(verts, m=1.0, fem=False)[source]

Calcualte the minimum 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)[source]

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

property graph[source]

NetworkX undirected graph representing this Surface.

property iter_surfedges[source]
classmethod from_trimeshsurface(
tri_mesh: TrimeshSurface,
)[source]
classmethod from_vtksurface(vtk_surface: VTKSurface)[source]
cedalion.dataclasses.geometry.affine_transform_from_numpy(
transform: ndarray,
from_crs: str,
to_crs: str,
from_units: str,
to_units: str,
) DataArray[source]

Wrap a 4×4 numpy array as a cedalion AffineTransform.

The resulting DataArray has pint units of to_units / from_units and dimension names [to_crs, from_crs], matching the convention used throughout cedalion for affine transforms.

Parameters:
  • transform – 4×4 affine transformation matrix as a numpy array.

  • from_crs – Name of the source coordinate reference system.

  • to_crs – Name of the target coordinate reference system.

  • from_units – Unit string for the source space (e.g. "mm").

  • to_units – Unit string for the target space (e.g. "m").

Returns:

A 4×4 AffineTransform DataArray with dims [to_crs, from_crs] and units to_units / from_units.

cedalion.dataclasses.geometry.robust_geodesic_distance(
surface: TrimeshSurface,
seed_vertices: list[int] | int,
m: float = 10.0,
) ndarray[source]

Compute geodesic distances from seed vertices robustly across multiple submeshes.

Parameters:
  • surface (TrimeshSurface) – The surface.

  • seed_vertices (list[int] | int) – Seed vertices (single int or list of ints).

  • m (float) – Geodesic distance parameter.

Returns:

Distance array of shape (num_vertices,), inf for vertices

not reachable (not on the same submesh as any seed).

Return type:

np.ndarray

Initial Contributors:

cedalion.dataclasses.recording module

Recording class definition for timeseries data.

class cedalion.dataclasses.recording.Recording(
timeseries: ~collections.OrderedDict[str,
TypeAliasForwardRef('cdt.NDTimeSeries')] = <factory>,
masks: ~collections.OrderedDict[str,
~xarray.core.dataarray.DataArray] = <factory>,
geo3d: cdt.LabeledPoints = <factory>,
geo2d: cdt.LabeledPoints = <factory>,
stim: ~pandas.core.frame.DataFrame = <factory>,
aux_ts: ~collections.OrderedDict[str,
TypeAliasForwardRef('cdt.NDTimeSeries')] = <factory>,
aux_obj: ~collections.OrderedDict[str,
~typing.Any] = <factory>,
head_model: ~typing.Any | None = None,
meta_data: ~collections.OrderedDict[str,
~typing.Any] = <factory>,
_measurement_lists: ~collections.OrderedDict[str,
~pandas.core.frame.DataFrame] = <factory>,
)[source]

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.

timeseries[source]

A dictionary of timeseries objects. The keys are the names of the timeseries.

Type:

OrderedDict[str, NDTimeSeries]

masks[source]

A dictionary of masks. The keys are the names of the masks.

Type:

OrderedDict[str, xr.DataArray]

geo3d[source]

A labeled point cloud representing the 3D geometry of the recording.

Type:

LabeledPoints

geo2d[source]

A labeled point cloud representing the 2D geometry of the recording.

Type:

LabeledPoints

stim[source]

A dataframe containing the stimulus information.

Type:

pd.DataFrame

aux_ts[source]

A dictionary of auxiliary timeseries objects.

Type:

OrderedDict[str, NDTimeSeries]

aux_obj[source]

A dictionary of auxiliary objects.

Type:

OrderedDict[str, Any]

head_model[source]

A head model object.

Type:

Optional[Any]

meta_data[source]

A dictionary of meta data.

Type:

OrderedDict[str, Any]

timeseries: OrderedDict[str, NDTimeSeries][source]
masks: OrderedDict[str, xr.DataArray][source]
geo3d: LabeledPoints[source]
geo2d: LabeledPoints[source]
stim: pd.DataFrame[source]
aux_ts: OrderedDict[str, NDTimeSeries][source]
aux_obj: OrderedDict[str, Any][source]
head_model: Any | None = None[source]
meta_data: OrderedDict[str, Any][source]
get_timeseries(key: str | None = None) cdt.NDTimeSeries[source]

Get a timeseries object by key.

Parameters:

key (Optional[str]) – The key of the timeseries to retrieve. If None, the last timeseries is returned.

Returns:

The requested timeseries object.

Return type:

NDTimeSeries

set_timeseries(key: str, value: cdt.NDTimeSeries, overwrite: bool = False)[source]
get_mask(key: str | None = None) DataArray[source]

Get a mask by key.

Parameters:

key (Optional[str]) – The key of the mask to retrieve. If None, the last mask is returned.

Returns:

The requested mask.

Return type:

xr.DataArray

set_mask(
key: str,
value: DataArray,
overwrite: bool = False,
)[source]

Set a mask.

Parameters:
  • key (str) – The key of the mask to set.

  • value (xr.DataArray) – The mask to set.

  • overwrite (bool) – Whether to overwrite an existing mask with the same key. Defaults to False.

get_timeseries_type(key)[source]

Get the type of a timeseries.

Parameters:

key (str) – The key of the timeseries.

Returns:

The type of the timeseries.

Return type:

str

property source_labels[source]

Get the unique source labels from the timeseries.

Returns:

A list of unique source labels.

Return type:

list

property detector_labels[source]

Get the unique detector labels from the timeseries.

Returns:

A list of unique detector labels.

Return type:

list

property wavelengths[source]

Get the unique wavelengths from the timeseries.

Returns:

A list of unique wavelengths.

Return type:

list

property trial_types[source]

Get the unique trial types from the stimulus dataframe.

Returns:

A list of unique trial types.

Return type:

list

cedalion.dataclasses.schemas module

Data array schemas and utilities to build labeled data arrays.

exception cedalion.dataclasses.schemas.ValidationError[source]

Bases: Exception

class cedalion.dataclasses.schemas.DataArraySchema(dims: tuple[str], coords: tuple[tuple[str, tuple[str]]])[source]

Bases: object

dims: tuple[str][source]
coords: tuple[tuple[str, tuple[str]]][source]
validate(data_array: DataArray)[source]
cedalion.dataclasses.schemas.validate_schemas(func)[source]
cedalion.dataclasses.schemas.build_timeseries(
data: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes],
dims: List[str],
time: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes],
channel: List[str],
value_units: str,
time_units: str,
other_coords: dict[str, _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes]] = {},
)[source]

Build a labeled time series data array.

Parameters:
  • data (ArrayLike) – The data values.

  • dims (List[str]) – The dimension names.

  • time (ArrayLike) – The time values.

  • channel (List[str]) – The channel names.

  • value_units (str) – The units of the data values.

  • time_units (str) – The units of the time values.

  • other_coords (dict[str, ArrayLike]) – Additional coordinates.

Returns:

The labeled time series data array.

Return type:

da (xr.DataArray)

cedalion.dataclasses.schemas.empty_timeseries_from_measurement_list(
meas_list: DataFrame,
value_units: str = '1',
time_units: str = 's',
)[source]

Build a one-sample, NDTimeSeries with channels defined by a measurement list.

Parameters:
  • meas_list – Measurement list DataFrame.

  • value_units – Pint unit string for the data values. Defaults to dimensionless.

  • time_units – Pint unit string for the time coordinate. Defaults to seconds.

Returns:

Zero-filled array with dims (channel, wavelength, time).

Return type:

xr.DataArray

cedalion.dataclasses.schemas.build_labeled_points(
coordinates: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes] | None = None,
crs: str = 'pos',
units: Unit | str | None = '1',
labels: list[str] | None = None,
types: list[str] | None = None,
)[source]

Build a labeled point cloud data array.

Parameters:
  • coordinates (ArrayLike, optional) – The coordinates of the points. Default: None.

  • crs (str, optional) – The coordinate system. Defaults to “pos”.

  • units (Optional[pint.Unit | str], optional) – The units of the coordinates. Defaults to “1”.

  • labels (Optional[list[str]], optional) – The labels of the points. Defaults to None.

  • types (Optional[list[str]], optional) – The types of the points. Defaults to None.

Returns:

The labeled point cloud data array.

Return type:

xr.DataArray

cedalion.dataclasses.schemas.validate_stim_schema(df: DataFrame)[source]
cedalion.dataclasses.schemas.build_stim_dataframe()[source]
cedalion.dataclasses.schemas.get_spatial_dimension(array: DataArray) str[source]

Return the name of the spatial dimension.

Parameters:

array – the array of which the spatial dimension name is searched-for

Returns:

The name of the identified spatial dimension.

Module contents

Data classes used throughout cedalion.