sarcasm.motion
Attributes
Classes
Class for tracking and analysis of sarcomere motion at line of interest LOI |
Module Contents
- sarcasm.motion.logger
- class sarcasm.motion.Motion(file_path: str, loi_name: str, restart: bool = False, auto_save: bool = True)[source]
Bases:
sarcasm.core.SarcAsMClass for tracking and analysis of sarcomere motion at line of interest LOI
- loi_data
- loi_file
- loi_name
- loi_folder
- auto_save = True
- __load_analysed_data_or_create(restart: bool)
- __create_loi_data()
- __get_loi_data_file_name(is_temp_file=False) str
- detekt_peaks(thres: float = 0.2, min_dist: float = 1.4, width: int = 0.5)[source]
Detect peaks of z-band intensity profiles
- Parameters:
thres (float) – Threshold for peak finder
min_dist (float) – Minimal distance of z-band peaks in µm
width (float) – Width of interval around peak for precise determination of peak center, in µm.
- track_z_bands(search_range: float = 1, memory_tracking: int = 10, memory_interpol: int = 3, t_range: Tuple[int, int] | None = None, z_range: Tuple[int, int] | None = None, min_length: float = 1, filter_params: Tuple[int, int] = (13, 7), equilibrium_weight: float = 0.3, use_lap_tracker: bool = True)[source]
Track peaks of intensity profile over time using LAP-based 1D tracking optimized for periodic motion
- Parameters:
search_range (float) – Maximum allowed distance for peak matching between frames (in µm)
memory_tracking (int) – Number of frames to keep track of missing peaks before starting a new trajectory
memory_interpol (int) – Maximum gap size (in frames) to interpolate missing detections in trajectories
t_range (Tuple[int, int] or None) – If not None, select time-interval of data, in frames
z_range (Tuple[int, int] or None) – If not None, select range of z-bands by index
min_length (float) – Minimal length of z-band trajectory in seconds. Shorter trajectories are removed.
filter_params (Tuple[int, int]) – Window length and polynomial order for Savitzky-Golay filter to smooth z positions
equilibrium_weight (float) – Weight factor (0-1) for equilibrium position prediction. Higher values make tracking more stable by pulling peaks toward their expected equilibrium positions.
use_lap_tracker (bool) – If True, use LAP-based tracker optimized for periodic 1D motion. If False, use basic nearest-neighbor.
- _track_z_bands_lap(peaks: List[numpy.ndarray], search_range: float, memory: int, equilibrium_weight: float = 0.3) numpy.ndarray[source]
Track z-bands using simple frame-to-frame nearest neighbor matching with equilibrium anchoring.
SIMPLE APPROACH: No new tracks after initialization. Z-bands are fixed structures that don’t appear/disappear during imaging - only the initial frame matters for track count.
- Parameters:
peaks (List[np.ndarray]) – List of peak positions for each frame
search_range (float) – Maximum allowed distance for matching (in µm)
memory (int) – Number of frames to remember missing peaks
equilibrium_weight (float) – Weight for equilibrium position in cost calculation (0 = pure spatial, 1 = pure equilibrium)
- Returns:
z_pos – 2D array of z-band trajectories (n_bands x n_frames)
- Return type:
np.ndarray
- static _greedy_assignment(cost_matrix: numpy.ndarray) Tuple[List[int], List[int]][source]
Greedy assignment fallback when Hungarian algorithm fails. Assigns tracks to detections by iteratively choosing the minimum cost pairing.
- Parameters:
cost_matrix (np.ndarray) – Cost matrix (n_tracks x n_detections)
- Returns:
row_ind, col_ind – Lists of matched track and detection indices
- Return type:
Tuple[List[int], List[int]]
- _track_z_bands_simple(peaks: List[numpy.ndarray], search_range: float, memory: int) numpy.ndarray[source]
Simple nearest-neighbor tracking as fallback.
- Parameters:
peaks (List[np.ndarray]) – List of peak positions for each frame
search_range (float) – Maximum allowed distance for matching
memory (int) – Number of frames to remember missing peaks
- Returns:
z_pos – 2D array of z-band trajectories
- Return type:
np.ndarray
- detect_analyze_contractions(model: str | None = None, threshold: float = 0.3, slen_lims: Tuple[float, float] = (1.2, 3), n_sarcomeres_min: int = 4, buffer_frames: int = 3, contr_time_min: float = 0.2, merge_time_max: float = 0.05)[source]
Detect contractions from contraction time-series using convolutional neural network and analyze beating
Predict contractions / contraction state (0 = quiescent, 1 = contracting) from sarcomere lengths (average or percentile)
- Optimize state by morphological closing and opening (minimal time of contraction cycle=contr_time_min,
merge contractions closer than merge_time_max). Remove cycles at very beginning or end (buffer_frames).
- Characterize state: obtain start times of contr. cycles (start_contractions_frame in frames, start_contr in s),
number of cycles (n_contr), label contraction cycles (1 to n_contr), duration of contr. cycles (time_contractions)
- Parameters:
model (str) – Neural network parameters (.pt file)
threshold (float) – Binary threshold for contraction state (0, 1) after prediction
slen_lims (tuple(float, float)) – Minimal and maximal sarcomere lengths, sarcomere outside interval are set to NaN
n_sarcomeres_min (int) – Minimal number of sarcomeres, if lower, contraction state is set to 0.
buffer_frames (int) – Remove contraction cycles / contractions within “buffer_frames” frames to start and end of time-series
contr_time_min (float) – Minimal time of contraction in seconds. If smaller, contraction is removed.
merge_time_max (float) – Maximal time between two contractions. If smaller, two contractions are merged to one.
- get_trajectories(slen_lims: Tuple[float, float] = (1.2, 3.0), filter_params_vel: Tuple[int, int] = (13, 5), dilate_contr: float = 0, equ_lims: Tuple[float, float] = (1.5, 2.3))[source]
Calculate sarcomere lengths (single and avg) and filter too large and too small values (slen_lims).
- Calculate sarcomere velocities (single and avg), prior smoothing of s’lengths with Savitzky-Golay filter
(filter_params_vel)
Calculate sarcomere equilibrium lengths (equ) and delta_slen
- Parameters:
slen_lims (tuple(float, float)) – Lower and upper limits of sarcomere lengths, values outside are set to nan
filter_params_vel (tuple(int, int)) – Window length and poly order for Savitky-Golay filter for smoothing of delta_slen prior to differentiation to obtain sarcomere velocities
dilate_contr (float) – Dilation time (in seconds) of contraction time-series to shorten time-interval during diastole at which the sarcomere equilibrium lengths are determined
equ_lims (tuple(float, float)) – Lower and upper limits of sarcomere equilibrium lengths, values outside are set to nan
- analyze_trajectories(custom_perc: List[Tuple[float, float]] | None = None)[source]
Analyze sarcomere single and average trajectories (extrema of sarcomeres contraction and velocity) and sarcomere popping
- Parameters:
custom_perc (List[Tuple[float, float]] or None, optional) – A list of tuples where each tuple contains two percentages (p0, p1) representing custom percentage points to analyze contraction, e.g., the time from p0% to p1% contraction of individual and average sarcomere length change. If p0<p1, the shortening is analyzed, if p1<p0, the elongation is analyzed. If not provided, defaults to None.
- calculate_surplus_motion_index()[source]
Calculate surplus motion index (SMI) for sarcomere motion: average distance traveled by individual sarcomeres contractions divided by distance traveled by sarcomere average
- analyze_popping(thres_popping: float = 0.25)[source]
Analyze sarcomere popping - popping if elongation of individual sarcomere is larger than thres_popping
- Parameters:
thres_popping (float) – Threshold above which sarcomere is identified as popping, in µm beyond equilibrium length
- analyze_correlations()[source]
Computes the Pearson correlation coefficients for sarcomere motion patterns (∆SL and V) across different contraction cycles and between sarcomeres within the same cycle to analyze static and stochastic heterogeneity in sarcomere dynamics.
It calculates the average serial (r_s) and mutual (r_m) correlation coefficients, and introduces the ratio R of serial to mutual correlations to distinguish between static and stochastic heterogeneity. The function updates the instance’s loi_data with correlation data, including the calculated R values, and stores the data if auto_save is enabled.
- Returns:
- Updates self.loi_data with the following keys:
’corr_delta_slen’ (ndarray or None): Correlation matrix for sarcomere length changes.
’corr_vel’ (ndarray or None): Correlation matrix for sarcomere velocities.
’corr_delta_slen_serial’ (float or NaN): Average serial correlation for sarcomere length changes.
’corr_delta_slen_mutual’ (float or NaN): Average mutual correlation for sarcomere length changes.
’corr_vel_serial’ (float or NaN): Average serial correlation for sarcomere velocities.
’corr_vel_mutual’ (float or NaN): Average mutual correlation for sarcomere velocities.
’ratio_delta_slen_mutual_serial’ (float or NaN): Ratio of mutual to serial correlation for sarcomere length changes.
’ratio_vel_mutual_serial’ (float or NaN): Ratio of mutual to serial correlation for sarcomere velocities.
- Return type:
None
- analyze_oscillations(min_scale: float = 6, max_scale: float = 180, num_scales: int = 60, wavelet: str = 'morl', freq_thres: float = 2, plot: bool = False)[source]
Analyze the oscillation frequencies of average and individual sarcomere length changes.
- Parameters:
min_scale (float, optional) – Minimum scale to use for the wavelet transform (default is 6).
max_scale (float, optional) – Maximum scale to use for the wavelet transform (default is 150).
num_scales (int, optional) – Number of scales to use for the wavelet transform (default is 100).
wavelet (str, optional) – Type of wavelet to use for the wavelet transform (default is ‘morl’ = Morlet wavelet).
freq_thres (float, optional) – Frequency threshold in Hz for distinguishing low-freq. oscillations at beating rate, and high-freq. oscillations.
plot (bool, optional) – If True, a plot illustrating the analysis is shown.
- Return type:
None
- static predict_contractions(z_pos: numpy.ndarray, slen: numpy.ndarray, weights: str, threshold: float = 0.33)[source]
Predict contractions from motion of z-bands and sarcomere lengths, then calculate mean state and threshold to get more accurate estimation of contractions
- Parameters:
z_pos (ndarray) – Time-series of Z-band positions
slen (ndarray) – Time-series of sarcomere lengths
weights (str) – Neural network parameters (.pt file)
threshold (float) – Binary threshold for contraction state (0, 1)
- static wavelet_analysis_oscillations(data: numpy.ndarray, frametime: float, min_scale: float = 6, max_scale: float = 150, num_scales: int = 100, wavelet: str = 'morl')[source]
Perform a wavelet transform of the data.
- Parameters:
data (array_like) – 1-D input signal.
frametime (float) – Sampling period of the signal.
min_scale (float, optional) – Minimum scale to use for the wavelet transform (default is 6).
max_scale (float, optional) – Maximum scale to use for the wavelet transform (default is 150).
num_scales (int, optional) – Number of scales to use for the wavelet transform (default is 200).
wavelet (str, optional) – Type of wavelet to use for the wavelet transform (default is ‘morl’).
- Returns:
cfs (ndarray) – Continuous wavelet transform coefficients.
frequencies (ndarray) – Corresponding frequencies for each scale.