optimap.activation¶
Activation map computation module.
- optimap.activation.find_activations(signal, method='maximum_derivative', interpolate=False, falling_edge=False, show=True, fps=None, ax=None, **kwargs)[source]¶
Computes activation times or detects activation events using different methods.
A versatile function that identifies when activation events occur in time series data.
Two different methods are available:
maximum_derivative: Computes activation times based the peaks in the temporal derivative of the signal \(dV/dt\). See
optimap.activation.find_activations_dvdt()
for details.threshold_crossing: Computes activation times based on the signal crossing a specified threshold in desired direction. See
optimap.activation.find_activations_threshold()
for details.
The function can handle 1D signals, 2D traces (T, N), or 3D videos (averaged over all spatial dimensions to compute 1D signal).
If
falling_edge
is set to True, it expects negative activation (i.e., the signal falls below the threshold).By default, the function returns the _closest_ frame index to the condition. If
interpolate
is set to True, the function will return a fractional frame using interpolation.- Parameters:
signal (np.ndarray) – The 1D signal.
method (str) – The method to use for finding activations. Options are “maximum_derivative” or “threshold”.
falling_edge (bool) – If True, find activations which go negative (falling edge).
interpolate (bool) – If True, use linear interpolation to find the exact crossing point.
threshold (float) – If
method='threshold_crossing'
, the threshold value.min_duration (int) – If
method='threshold_crossing'
, the minimum duration of the crossing in frames. If set to 0, all crossings are returned.prominence (float) – If
method='maximum_derivative'
, the required prominence of peaks. If None, it will be calculated automatically based on the signal’s derivative statistics.height (float) – If
method='maximum_derivative'
, the minimum height of peaks. Default is None.min_distance (int) – If
method='maximum_derivative'
, the minimum distance between detected peaks in frames. Default is 10.window_size (int) – If
method='maximum_derivative'
, the size of the window used for derivative calculation. Default is 5.show (bool) – If True, the resulting activation times will be displayed.
fps (float) – Frames per second for time conversion for plotting.
ax (matplotlib.axes.Axes) – Axes on which to plot. If None, a new figure and axes is created.
**kwargs (dict) – Additional arguments passed to the underlying activation detection functions.
- Returns:
activations – Detected activation times.
- Return type:
ndarray
- optimap.activation.show_activations(signal, activations, fps=None, ax=None, linecolor='red', linestyle='--', **kwargs)[source]¶
Display a signal with vertical lines marking activation times.
This function creates a visualization of a time series with clear markers at each activation point, making it easy to identify when activation events occur.
- Parameters:
signal (array-like) – The 1D signal to display
activations (array-like) – List of activation points (frame indices)
fps (float, optional) – Frames per second for time conversion. If provided, x-axis will show time in seconds instead of frame numbers.
ax (matplotlib.axes.Axes, optional) – Axes on which to plot. If None, a new figure and axes is created.
linecolor (str, optional) – Color of the vertical lines marking activation times, by default “red”
linestyle (str, optional) – Line style of the vertical lines marking activation times, by default “–”
**kwargs (dict, optional) – Additional arguments passed to
show_traces()
.
- Returns:
The axes containing the plot
- Return type:
See also
find_activations
For detecting activation times in signals
- optimap.activation.compute_activation_map(video, method='maximum_derivative', falling_edge=False, interpolate=False, threshold=0.5, normalize_time=True, set_nan_for_inactive=True, show=True, **kwargs)[source]¶
Computes an activation map (or isochrone map) of local activation times from a video.
The activation map is a 2D image where each pixel represents the time (in terms of frame index) at which the pixel is considered activated.
The activation time is determined by
find_activations()
based on the specified method, which can be either “threshold_crossing” or “maximum_derivative”.threshold_crossing
: The activation time is the first frame where the pixel intensity surpasses a specified threshold.maximum_derivative
: The activation time is the where the maximum of the temporal derivative of the pixel intensity occurs.
Note
For the
threshold_crossing
method the video should be normalized to the range [0, 1]. This is not required for themaximum_derivative
method.For negative polarity signals (i.e. inverted action potentials), set
falling_edge=True
. The activation map is return in terms of discrete frame indices, ifinterpolate=True
fractions of frames are returned. Ifnormalize_time=True
(default), the minimum activation time across all pixels will be subtracted from the activation times.See
find_activations()
for further details andshow_activation_map()
for plotting.- Parameters:
video (np.ndarray) – A 3D array representing the video, with dimensions {t (time or frames), x (width), y (height)}.
method (str, optional) – Method to compute activation times. Options are “threshold_crossing” or “maximum_derivative”. Defaults to “maximum_derivative”.
falling_edge (bool, optional) – If True, the function will compute the time/frame when pixel intensity falls below the threshold, rather than surpassing it. Defaults to False.
interpolate (bool, optional) – If True, use linear interpolation to find the exact crossing point between frames. Defaults to False.
threshold (float, optional) – Intensity threshold for
threshold_crossing
method at which a pixel is considered activated. Defaults to 0.5.normalize_time (bool, optional) – If True, the minimum activation time across all pixels will be subtracted from the activation times. Defaults to True.
set_nan_for_inactive (bool, optional) – If True, pixels that never reach the activation threshold or meet all the criteria will be set to NaN. If False, set to np.inf. Defaults to True.
show (bool, optional) – If True, the resulting activation map will be displayed. Defaults to True.
**kwargs (dict, optional) – Additional arguments passed to
show_activation_map()
.
- Returns:
activation_map – 2D image of activation times
- Return type:
ndarray
- optimap.activation.show_activation_map(activation_map, vmin=0, vmax=None, fps=None, cmap='turbo', title='', show_contours=False, show_map=True, show_colorbar=True, colorbar_title=None, ax=None, contour_fmt=None, contour_levels=None, contour_fontsize=None, contour_linestyles=None, contour_args={}, contour_label_args={})[source]¶
Display an activation/isochrone map with optional contours.
Creates a color-coded visualization of activation timing across a 2D spatial region. Optional contour lines can be added to highlight regions that activate at the same time (isochrones).
- Parameters:
activation_map (2D ndarray) – The activation map to display. Values represent activation times.
vmin (float, optional) – Minimum value for the colormap, by default 0
vmax (float, optional) – Maximum value for the colormap, by default None (auto-determined from data)
fps (float, optional) – Show activation map times in milliseconds based on this frame rate, otherwise, it will be in frames.
cmap (str, optional) – Colormap to use for the activation map, by default “turbo”
title (str, optional) – Title for the plot, by default “”
show_contours (bool, optional) – Whether to overlay contour lines on the activation map, by default True
show_map (bool, optional) – Whether to display the activation map, by default True
show_colorbar (bool, optional) – Whether to display a colorbar, by default True
colorbar_title (str, optional) – Title for the colorbar, by default “Activation Time [ms]” if
fps
is provided, otherwise “Activation Time [frames]”ax (matplotlib.axes.Axes, optional) – Axes to plot on. If None, a new figure and axes is created, by default None
contour_fontsize (int or float, optional) – Font size for contour labels, by default None (auto-determined)
contour_fmt (str, optional) – Format string for contour labels e.g.
' %1.0f ms '
, by default None. Seematplotlib.pyplot.clabel()
for details.contour_levels (array-like, optional) – Specific contour levels to draw, by default None (auto-determined). See
matplotlib.pyplot.contour()
for details.contour_linestyles (str or list of str, optional) – Line style(s) for contour lines, by default None. See
matplotlib.pyplot.contour()
for details.contour_args (dict, optional) – Additional keyword arguments for matplotlib’s contour function, by default {}
contour_label_args (dict, optional) – Additional keyword arguments for contour label formatting, by default {}
- Returns:
The axes containing the plot
- Return type:
See also
compute_activation_map
For creating activation maps from video data
- optimap.activation.compute_cv(activation_map, positions=None, fps=None, space_scale=None, show=True, **kwargs)[source]¶
Compute conduction velocity (CV) between pairs of positions on an activation map.
The conduction velocity is calculated as the spatial distance between two points divided by the difference in activation times at those points.
- Parameters:
activation_map (2D array) – Activation map where values represent activation times in frames
positions (list or ndarray, optional) –
Position data in one of the following formats:
None: Interactive prompt to select two points (default)
List of N pairs of points: [(x1, y1), (x2, y2), (x3, y3), (x4, y4), …]
NumPy array with shape (N, 2, 2)
fps (float, optional) – Frames per second. If provided, converts time units from frames to seconds
space_scale (float, optional) – Spatial scale in mm/px. If provided, converts spatial units from pixels to cm
show (bool, optional) – Whether to display a plot showing the activation map and computed CV, by default True
**kwargs (dict, optional) – Additional keyword arguments passed to the select_cv_positions function if positions=None
- Returns:
Array of N conduction velocities.
- Units depend on fps and space_scale:
pixels/frame if both fps and space_scale are None
pixels/s if only fps is provided
cm/s if both fps and space_scale are provided
- Return type:
float or ndarray
Examples
>>> # Computing CV with user-selected points >>> cv = compute_cv(activation_map) >>> >>> # Computing CV with specific points in physical units >>> cv = compute_cv(activation_map, ... positions=[(10, 15), (40, 30)], ... fps=500, # 500 frames/s ... space_scale=10) # 10 mm/px
- optimap.activation.compute_cv_map(activation_map, method='bayly', fps=None, space_scale=None, show=True, vmin=0, vmax=None, **kwargs)[source]¶
Computes the local conduction velocity (CV) map from an activation map.
- Parameters:
activation_map (np.ndarray) – 2D NumPy array where each pixel represents the activation time. NaN values mean no activation.
method (str) – The method to use for computing the CV cmp. Currently only ‘bayly’ is supported.
fps (float) – Frames per second. If provided, converts time units from frames to seconds.
space_scale (float) – Spatial scale in mm/px. If provided, converts spatial units from pixels to cm.
show (bool) – Whether to display a plot showing the activation map and computed CV map.
- Returns:
Array of shape (rows, cols, 2) where the last dimension contains the x and y components of the local CV at each point.
- Return type:
np.ndarray
See also
compute_cv
Computes the conduction velocity between pairs of points.
compute_velocity_field
Computes the velocity field from an activation map.
- optimap.activation.compute_velocity_field(activation_map, method='bayly', **kwargs)[source]¶
Computes the velocity field from an isochronal activation map.
This function serves as a wrapper to call different algorithms for computing the velocity field, which represents the direction and magnitude (speed) of activation wavefront propagation at each point in the map.
- Available methods:
'bayly'
: Uses local second-order polynomial fitting to estimate the gradient of activation time and derive velocity. Use window_size parameter to … Seecompute_velocity_field_bayly()
and Bayly et al. [1998].'circle'
: Employs activation time differences across diameters of a local circle to determine velocity. Use radius parameter to … Seecompute_velocity_field_circle()
and Siles-Paredes et al. [2022].'gradient'
: Calculates velocity directly from the smoothed spatial gradient of the activation map (\(\\vec{v} = \\nabla T / |\\nabla T|^2\)). Simple and fast, but can be sensitive to noise and sharp gradients. Seecompute_velocity_field_gradient()
.
- Parameters:
activation_map (np.ndarray) – 2D NumPy array where each pixel represents the activation time.
method (str) – Method to compute the velocity field. Options are: [‘bayly’, ‘circle’, ‘gradient’].
**kwargs (dict) – Additional parameters for the selected method.
activation_map – 2D NumPy array where each pixel represents the activation time.
method – Method to compute the velocity field. Options are: [‘bayly’, ‘circle’, ‘gradient’].
**kwargs – Additional parameters for the selected method.
- Returns:
3D NumPy array of shape (rows, cols, 2)
- Return type:
np.ndarray
- optimap.activation.find_activations_threshold(signal, threshold=0.5, interpolate=False, falling_edge=False, min_duration=8, fps=None, show=True, ax=None)[source]¶
Find activation times by detecting threshold crossings in a 1D signal.
Identifies the exact moments when a signal crosses a specified threshold value. This is useful for computing local activation times or detecting events in a time series.
By default, it detects when the signal rises above the threshold, but can also detect when it falls below the threshold if
falling_edge=True
.The function returns the closest frame index where the signal crosses the threshold. If
interpolate
is set to True, the function will return the exact crossing point using linear interpolation.- Parameters:
signal (np.ndarray) – The 1D signal.
threshold (float, optional) – The threshold value. Default is 0.5.
interpolate (bool, optional) – If True, use linear interpolation to find the exact crossing point. Default is False.
falling_edge (bool, optional) – If True, find crossings from above to below the threshold. Default is False.
min_duration (int, optional) – Minimum duration of the crossing in frames. If set to 0, all crossings are returned. Default is 8.
fps (float, optional) – Frames per second for time conversion for plotting. Default is None.
show (bool, optional) – Whether to show the activation times. Default is True.
ax (matplotlib.axes.Axes, optional) – Axes to plot on. If None, a new figure and axes is created. Default is None.
- Return type:
np.ndarray
- optimap.activation.find_activations_dvdt(signal, falling_edge=False, single_activation=False, window_size=5, prominence=None, min_distance=None, height=None, interpolate=False, fps=None, show=True, ax=None)[source]¶
Find activation times of a 1D signal using the maximum derivative (dV/dt) method.
Detects moments of activation by identifying where a signal’s rate of change peaks. This approach is particularly effective for signals with sharp transitions, such as action potentials or other biological activation events.
For rising signals, the function finds where the positive derivative is maximized. For falling signals (set
falling_edge=True
), it finds where the negative derivative is maximized.If
single_activation
is set to True, the timepoint of the maximum derivative is returned. Otherwise, the function detects peaks in the derivative signal which correspond to activation times. The parametersprominence
,height
, andmin_distance
are used to control the peak detection process, see :func:scipy.signal.find_peaks
for details.The function uses Savitzky-Golay filter to smooth the derivative calculation. If
falling_edge
is set to True, it detects the maximum negative derivative (for negative polarity signals). Thewindow_size
parameter controls length of the moving window applied in the Savitzky-Golay filter, seescipy.signal.savgol_filter()
for details.- Parameters:
signal (array-like) – Input signal or array of signals.
falling_edge (bool, optional) – If True, detect maximum negative derivative (for negative polarity signals). Default is False.
single_activation (bool, optional) – If True, find only the timepoint of the maximum derivative. Default is False.
window_size (int, optional) – Size of the window used for derivative calculation. Default is 5.
prominence (float, optional) – Required prominence of peaks. If None, it will be calculated automatically based on the signal’s derivative statistics. Default is None.
min_distance (int, optional) – Minimum distance between detected peaks in frames. Default is None.
height (float, optional) – Minimum height of peaks. Default is None.
interpolate (bool, optional) – Whether to use interpolation for more precise activation time. Default is False.
fps (float, optional) – Frames per second, used for time axis when plotting. Default is None.
show (bool, optional) – Whether to show the detected activation times. Default is True.
ax (matplotlib.axes.Axes or list of Axes, optional) – Axes to plot on. If None, new figures are created. If a single axis is provided, it will be split into two subplots.
- Returns:
activations – Detected activation times.
- Return type:
ndarray
- optimap.activation.compute_velocity_field_gradient(activation_map, sigma=2, outlier_percentage=0)[source]¶
Compute a velocity field based on the gradient of the activation map.
This method estimates the velocity field by: 1. Smoothing the input activation map using a Gaussian filter to reduce noise. 2. Computing the velocity field \(\\nabla T / |\\nabla T|^2\) of the smoothed
activation time map \(T(x, y)\).
Optionally remove outlier vectors based on gradient magnitude.
Note: The result represents local velocity in pixels/frame.
- Parameters:
activation_map (np.ndarray) – 2D NumPy array (rows, cols) where each pixel represents the local activation time (LAT). NaN values can be present.
sigma (float, optional) – Standard deviation for the Gaussian smoothing applied to the activation map before gradient calculation. Larger values increase smoothing. Defaults to 2.0.
outlier_percentage (float or None, optional) – The percentage of gradient vectors to filter out as outliers, based on their magnitude. Specifically, vectors whose gradient magnitude exceeds the (100 - outlier_percentage) percentile are set to NaN. For example, outlier_percentage=0.1 removes the 0.1% of vectors with the largest magnitudes. Set to None or 0 to disable outlier removal. Defaults to 0.
- Returns:
3D NumPy array of shape (rows, cols, 2).
- Return type:
np.ndarray
See also
compute_velocity_field
General function calling different methods.
- optimap.activation.compute_velocity_field_bayly(activation_map, window_size=None, min_points_ratio=0.5)[source]¶
Calculates a velocity vector field from a 2D activation map using local polynomial fitting (Bayly’s method Bayly et al. [1998]).
For each point in the activation map, a local polynomial
$$ T(x,y) = ax^2 + by^2 + cxy + dx + ey + f $$
is fitted to the activation times in a square window around that point. The velocity vector is then computed as the gradient of the fitted polynomial at the center of the window.
- Parameters:
activation_map (np.ndarray) – 2D NumPy array where each element represents the activation time at that spatial location (grid point). NaN values can be used to indicate no activation.
window_size (int) – The side length of the square window (neighborhood) used for local polynomial fitting. Must be an odd integer >= 3. Defaults to 10% of the image size.
min_points_ratio (float) – The minimum fraction of non-NaN points required within a window to perform the fit (relative to window_size*window_size). Helps avoid fitting on sparse data. Defaults to 0.6.
- Returns:
Array of shape (rows, cols, 2) where the last dimension contains the x and y components of the velocity vector at each point.
- Return type:
np.ndarray
- optimap.activation.compute_velocity_field_circle(activation_map, radius=5, num_angles=180, angle_window_deg=30, smooth_sigma_deg=10.0, min_valid_speeds_ratio=0.25)[source]¶
Calculates a velocity vector field from a 2D activation map using the circle method Siles-Paredes et al. [2022].
Velocity vectors represent direction and speed (pixels/frames) of propagation.
- Parameters:
activation_map (np.ndarray) – 2D NumPy array (rows, cols) of local activation times (LAT). NaN values indicate masked areas.
radius (float, optional.) – Radius of the circle used for LAT comparisons, in pixels. Defaults to 5px.
num_angles (int, optional) – Number of diameters (angles from 0 to pi) to sample around the circle. Defaults to 180.
angle_window_deg (float, optional) – Total angular window width (in degrees) centered around the estimated propagation direction, used for averaging speeds. Defaults to 30 degrees.
smooth_sigma_deg (float or None, optional) – Standard deviation (in degrees) for Gaussian smoothing applied to the absolute speeds before finding the minimum, used to robustly determine the propagation direction. Set to None or 0 to disable smoothing. Defaults to 10.0.
min_valid_speeds_ratio (float, optional) – Minimum fraction of valid (non-NaN) instantaneous speeds required out of num_angles to compute a velocity vector at a point. Defaults to 0.25.
- Returns:
Array of shape (rows, cols, 2) where the last dimension contains the x and y components of the velocity vector at each point.
- Return type:
np.ndarray