coco_pipe.dim_reduction.evaluation.geometry =========================================== .. py:module:: coco_pipe.dim_reduction.evaluation.geometry .. autoapi-nested-parse:: Trajectory geometry metrics and smoothing utilities. This module provides small, generic helpers for analyzing ordered trajectories in embedded spaces. The functions are reducer-agnostic and operate on standard NumPy arrays rather than domain-specific container types. Functions --------- moving_average Smooth a one-dimensional timecourse with a valid-mode moving average. trajectory_acceleration Compute instantaneous acceleration magnitude from second-order derivatives. trajectory_speed Compute instantaneous speed from first-order trajectory differences. trajectory_curvature Compute geometric curvature from first- and second-order derivatives. trajectory_dispersion Compute within-group trajectory spread across time. trajectory_displacement Compute displacement from the initial trajectory state across time. trajectory_path_length Compute total or cumulative path length. trajectory_separation Compute time-resolved group separation across time using a selected method. trajectory_tortuosity Compute the ratio between path length and net displacement. trajectory_turning_angle Compute local turning angles between consecutive trajectory segments. Author: Hamza Abdelhedi (hamza.abdelhedi@umontreal.ca) Functions --------- .. autoapisummary:: coco_pipe.dim_reduction.evaluation.geometry.moving_average coco_pipe.dim_reduction.evaluation.geometry.trajectory_acceleration coco_pipe.dim_reduction.evaluation.geometry.trajectory_speed coco_pipe.dim_reduction.evaluation.geometry.trajectory_curvature coco_pipe.dim_reduction.evaluation.geometry.trajectory_path_length coco_pipe.dim_reduction.evaluation.geometry.trajectory_displacement coco_pipe.dim_reduction.evaluation.geometry.trajectory_tortuosity coco_pipe.dim_reduction.evaluation.geometry.trajectory_turning_angle coco_pipe.dim_reduction.evaluation.geometry.trajectory_dispersion coco_pipe.dim_reduction.evaluation.geometry.trajectory_separation Module Contents --------------- .. py:function:: moving_average(arr: numpy.ndarray, window: int) -> numpy.ndarray Smooth a one-dimensional array with a valid-mode moving average. :param arr: Input array to smooth. :type arr: np.ndarray of shape (n_samples,) :param window: Size of the smoothing window. Must be a positive integer no larger than the array length. :type window: int :returns: Smoothed array. The output length is ``n_samples - window + 1``. If ``window == 1``, a copy of the input is returned. :rtype: np.ndarray :raises ValueError: If ``arr`` is not one-dimensional, if ``window`` is not positive, or if ``window`` is larger than the input length. .. seealso:: :obj:`trajectory_speed` First-order trajectory dynamics without smoothing. :obj:`trajectory_turning_angle` Local directional changes along a trajectory. .. rubric:: Examples >>> import numpy as np >>> moving_average(np.array([1, 2, 3, 4, 5]), window=3) array([2., 3., 4.]) .. py:function:: trajectory_acceleration(traj: numpy.ndarray, dt: float = 1.0) -> numpy.ndarray Calculate instantaneous acceleration magnitude. :param traj: Trajectory array. The second-to-last axis is interpreted as time and the last axis as coordinates. :type traj: np.ndarray of shape (..., n_times, n_dims) :param dt: Uniform time step between consecutive samples. :type dt: float, default=1.0 :returns: Acceleration-magnitude timecourse aligned with the input time axis. :rtype: np.ndarray of shape (..., n_times) :raises ValueError: If ``traj`` has fewer than two dimensions, contains fewer than three time points, or if ``dt <= 0``. .. seealso:: :obj:`trajectory_speed` First-order trajectory dynamics. :obj:`trajectory_curvature` Geometric bending of a trajectory. :obj:`trajectory_turning_angle` Local directional changes between segments. .. rubric:: Examples >>> import numpy as np >>> t = np.linspace(0.0, 2.0, 3) >>> traj = np.stack([t**2, np.zeros_like(t)], axis=1) >>> trajectory_acceleration(traj, dt=1.0).shape (3,) .. py:function:: trajectory_speed(traj: numpy.ndarray, dt: float = 1.0) -> numpy.ndarray Calculate instantaneous trajectory speed. :param traj: Trajectory array. The second-to-last axis is interpreted as time and the last axis as coordinates. :type traj: np.ndarray of shape (..., n_times, n_dims) :param dt: Uniform time step between consecutive samples. :type dt: float, default=1.0 :returns: Instantaneous speed timecourse. The final value is padded with the last computed speed so that the output length matches the number of time points. :rtype: np.ndarray of shape (..., n_times) :raises ValueError: If ``traj`` has fewer than two dimensions, contains fewer than two time points, or if ``dt <= 0``. .. rubric:: Notes This function computes the norm of the first difference along the time axis, divided by ``dt``. .. seealso:: :obj:`trajectory_acceleration` Second-order trajectory dynamics. :obj:`trajectory_path_length` Total or cumulative traveled distance. :obj:`trajectory_displacement` Distance from the initial state across time. .. rubric:: Examples >>> import numpy as np >>> traj = np.array([[0.0, 0.0], [1.0, 0.0], [2.0, 0.0]]) >>> trajectory_speed(traj) array([1., 1., 1.]) .. py:function:: trajectory_curvature(traj: numpy.ndarray) -> numpy.ndarray Calculate geometric curvature of a trajectory. :param traj: Trajectory array. The second-to-last axis is interpreted as time and the last axis as coordinates. :type traj: np.ndarray of shape (..., n_times, n_dims) :returns: Curvature timecourse aligned with the input time axis. :rtype: np.ndarray of shape (..., n_times) :raises ValueError: If ``traj`` has fewer than two dimensions or fewer than two time points. .. rubric:: Notes For vector-valued trajectories, curvature is computed from first and second derivatives using the generalized formula ``sqrt(||v||^2 ||a||^2 - (v . a)^2) / ||v||^3``. The implementation assumes uniformly spaced samples. .. seealso:: :obj:`trajectory_turning_angle` Discrete local directional change. :obj:`trajectory_tortuosity` Path inefficiency relative to net displacement. :obj:`trajectory_speed` First-order trajectory dynamics. .. rubric:: Examples >>> import numpy as np >>> t = np.linspace(0, 2 * np.pi, 100) >>> traj = np.stack([np.cos(t), np.sin(t)], axis=1) >>> k = trajectory_curvature(traj) >>> k.shape (100,) .. py:function:: trajectory_path_length(traj: numpy.ndarray, *, cumulative: bool = False) -> numpy.ndarray Calculate trajectory path length. :param traj: Trajectory array. The second-to-last axis is interpreted as time and the last axis as coordinates. :type traj: np.ndarray of shape (..., n_times, n_dims) :param cumulative: If ``True``, return cumulative path length aligned with the input time axis. Otherwise return total path length for each trajectory. :type cumulative: bool, default=False :returns: Total path length with shape ``(...)`` when ``cumulative=False``, or cumulative path length with shape ``(..., n_times)`` when ``cumulative=True``. :rtype: np.ndarray .. seealso:: :obj:`trajectory_displacement` Distance from the initial state across time. :obj:`trajectory_tortuosity` Ratio of path length to net displacement. :obj:`trajectory_speed` First-order local motion magnitude. .. rubric:: Examples >>> import numpy as np >>> traj = np.array([[0.0, 0.0], [1.0, 0.0], [2.0, 0.0]]) >>> trajectory_path_length(traj) np.float64(2.0) .. py:function:: trajectory_displacement(traj: numpy.ndarray) -> numpy.ndarray Calculate displacement from the initial state across time. :param traj: Trajectory array. The second-to-last axis is interpreted as time and the last axis as coordinates. :type traj: np.ndarray of shape (..., n_times, n_dims) :returns: Euclidean displacement from the first time point at each time index. :rtype: np.ndarray of shape (..., n_times) .. seealso:: :obj:`trajectory_path_length` Total or cumulative traveled distance. :obj:`trajectory_tortuosity` Ratio of traveled distance to final displacement. .. rubric:: Examples >>> import numpy as np >>> traj = np.array([[0.0, 0.0], [1.0, 0.0], [1.0, 1.0]]) >>> trajectory_displacement(traj) array([0. , 1. , 1.41421356]) .. py:function:: trajectory_tortuosity(traj: numpy.ndarray, eps: float = 1e-08) -> numpy.ndarray Calculate trajectory tortuosity. Tortuosity is defined as total path length divided by net displacement from the initial to the final state. :param traj: Trajectory array. The second-to-last axis is interpreted as time and the last axis as coordinates. :type traj: np.ndarray of shape (..., n_times, n_dims) :param eps: Small constant used to identify near-zero displacement. :type eps: float, default=1e-8 :returns: Tortuosity for each trajectory. Stationary trajectories return ``1.0``; trajectories with nonzero path length but near-zero net displacement return ``np.inf``. :rtype: np.ndarray of shape (...) .. seealso:: :obj:`trajectory_path_length` Total traveled distance along the path. :obj:`trajectory_displacement` Net displacement from start to end. :obj:`trajectory_curvature` Local geometric bending. .. rubric:: Examples >>> import numpy as np >>> traj = np.array([[0.0, 0.0], [1.0, 0.0], [2.0, 0.0]]) >>> trajectory_tortuosity(traj) np.float64(1.0) .. py:function:: trajectory_turning_angle(traj: numpy.ndarray) -> numpy.ndarray Calculate local turning angles between consecutive trajectory segments. :param traj: Trajectory array. The second-to-last axis is interpreted as time and the last axis as coordinates. :type traj: np.ndarray of shape (..., n_times, n_dims) :returns: Turning-angle timecourse in radians. The first and last time points are padded with the nearest interior angle to preserve length. :rtype: np.ndarray of shape (..., n_times) .. seealso:: :obj:`trajectory_curvature` Continuous geometric bending. :obj:`trajectory_speed` Local motion magnitude. :obj:`trajectory_path_length` Total or cumulative traveled distance. .. rubric:: Examples >>> import numpy as np >>> traj = np.array([[0.0, 0.0], [1.0, 0.0], [1.0, 1.0]]) >>> trajectory_turning_angle(traj) array([1.57079633, 1.57079633, 1.57079633]) .. py:function:: trajectory_dispersion(traj: numpy.ndarray, labels: Optional[numpy.ndarray] = None) -> Dict[str, numpy.ndarray] | numpy.ndarray Calculate within-group trajectory dispersion across time. :param traj: Trial trajectory tensor. :type traj: np.ndarray of shape (n_trials, n_times, n_dims) :param labels: Optional group label for each trial. If omitted, a single global dispersion timecourse is returned. :type labels: np.ndarray of shape (n_trials,), optional :returns: Global dispersion timecourse when ``labels`` is omitted, otherwise a mapping from label to dispersion timecourse. :rtype: np.ndarray or dict[str, np.ndarray] .. seealso:: :obj:`trajectory_separation` Unified separation entrypoint. :obj:`trajectory_separation` Use ``method="within_between_ratio"`` for normalized separation. .. rubric:: Examples >>> import numpy as np >>> traj = np.zeros((2, 3, 2)) >>> traj[1, :, 0] = 1.0 >>> trajectory_dispersion(traj) array([0.5, 0.5, 0.5]) .. py:function:: trajectory_separation(traj: numpy.ndarray, labels: numpy.ndarray, method: str = 'centroid', **kwargs) -> Dict[Tuple[str, str], numpy.ndarray] Calculate time-resolved separation between labeled trajectory groups. :param traj: Trajectory tensor containing one trajectory per trial. :type traj: np.ndarray of shape (n_trials, n_times, n_dims) :param labels: Class label for each trial. :type labels: np.ndarray of shape (n_trials,) :param method: "distributional", "margin"}, default="centroid" Separation definition to compute. :type method: {"centroid", "within_between_ratio", "mahalanobis", :param \*\*kwargs: Additional keyword arguments forwarded to the selected separation method. :type \*\*kwargs: dict :returns: Mapping from label pairs to separation timecourses of shape ``(n_times,)``. :rtype: dict[tuple[str, str], np.ndarray] :raises ValueError: If the inputs are invalid or if an unsupported separation method is requested. .. rubric:: Notes This is the high-level separation entrypoint for trajectory-group comparison. It dispatches to the more specific separation primitives in this module. Supported methods: - ``"centroid"``: Euclidean distance between label centroids. - ``"within_between_ratio"``: Between-centroid distance normalized by within-group dispersion. - ``"mahalanobis"``: Covariance-aware centroid separation. - ``"distributional"``: Energy-distance separation between trial clouds. - ``"margin"``: Nearest-cross minus nearest-within margin separation. .. seealso:: :obj:`trajectory_dispersion` Within-group spread used by some separation methods. .. rubric:: Examples >>> import numpy as np >>> traj = np.zeros((4, 5, 2)) >>> labels = np.array(["A", "A", "B", "B"]) >>> sep = trajectory_separation(traj, labels, method="centroid") >>> list(sep.keys()) [('A', 'B')]