sarcasm

Submodules

Attributes

__version__

Classes

SarcAsM

Base class for sarcomere structural and functional analysis.

Structure

Class to analyze sarcomere morphology.

Motion

Class for tracking and analysis of sarcomere motion at line of interest LOI

Utils

Miscellaneous utility functions

IOUtils

Utility functions for storing and loading IO data.

Plots

Class with plotting functions for Structure and Motion objects

PlotUtils

Helper function and parameters for plotting

MultiStructureAnalysis

Class for multi-tif-file comparison of structure.

MultiLOIAnalysis

Class for multi-LOI comparison.

Package Contents

sarcasm.__version__
class sarcasm.SarcAsM(filepath: str | os.PathLike, restart: bool = False, channel: int | None | Literal['RGB'] = None, auto_save: bool = True, use_gui: bool = False, device: torch.device | Literal['auto', 'mps', 'cuda', 'cpu'] = 'auto', **info: Dict[str, Any])[source]

Base class for sarcomere structural and functional analysis.

Parameters:
  • filepath (str | os.PathLike) – Path to the TIFF file for analysis.

  • restart (bool, optional) – If True, deletes existing analysis and starts fresh (default: False).

  • channel (int, None or Literal['RGB'], optional) – Specifies the channel with sarcomeres in multicolor stacks (default: None).

  • auto_save (bool, optional) – Automatically saves analysis results when True (default: True).

  • use_gui (bool, optional) – Indicates GUI mode operation (default: False).

  • device (Union[torch.device, Literal['auto']], optional) – Device for PyTorch computations. ‘auto’ selects CUDA/MPS if available (default: ‘auto’).

  • **info (Any) – Additional metadata as keyword arguments (e.g. cell_line=’wt’).

filepath

Absolute path to the input TIFF file.

Type:

str

base_dir

Base directory for analysis of the TIFF file.

Type:

str

data_dir

Directory for processed data storage.

Type:

str

analysis_dir

Directory for analysis results.

Type:

str

device

Active computation device for PyTorch operations.

Type:

torch.device

Dynamic Attributes (loaded on demand)
zbands

Z-band mask

Type:

ndarray

zbands_fast_movie

High-temporal resolution Z-band mask

Type:

ndarray

mbands

Sarcomere M-band mask

Type:

ndarray

orientation

Sarcomere orientation map

Type:

ndarray

cell_mask

Binary cell mask

Type:

ndarray

sarcomere_mask

Binary sarcomere mask

Type:

ndarray

meta_data_handler: sarcasm.meta_data_handler.MetaDataHandler
metadata: dict[str, Any]
filepath = b'.'
auto_save = True
channel = None
use_gui = False
restart = False
info
base_dir
data_dir
analysis_dir
file_zbands
file_zbands_fast_movie
file_mbands
file_orientation
file_cell_mask
file_sarcomere_mask
__getattr__(name: str) Any[source]

Dynamic loading of analysis result TIFFs

__dir__() list[str][source]

Augment autocomplete with dynamic attributes

__str__()[source]

Returns a pretty, concise string representation of the SarcAsM object.

open_base_dir()[source]

Opens the base directory of the tiff file in the file explorer.

property model_dir: str

Returns the path to the model directory.

read_imgs(frames: str | int | List[int] = None)[source]

Load tif file, and optionally select channel

remove_intermediate_tiffs() None[source]

Removes intermediate TIFF files while preserving the original input.

class sarcasm.Structure(filepath: str | os.PathLike, restart: bool = False, channel: int | None | Literal['RGB'] = None, auto_save: bool = True, use_gui: bool = False, device: torch.device | Literal['auto'] = 'auto', **info: Dict[str, Any])[source]

Bases: sarcasm.core.SarcAsM

Class to analyze sarcomere morphology.

data

A dictionary with structure data.

Type:

dict

__get_structure_data_file(is_temp_file: bool = False) str

Returns the path to the structure data file.

Parameters:

is_temp_file (bool, optional) – If True, returns the path to a temporary file. This temporary file is used to prevent creating corrupted data files due to aborted operations (e.g., exceptions or user intervention). The temporary file can be committed to a final file by renaming it. Default is False.

Returns:

The path to the structure data file, either temporary or final.

Return type:

str

commit() None[source]

Commit data by renaming the temporary file to the final data file.

store_structure_data(override: bool = True) None[source]

Store structure data in a JSON file.

Parameters:

override (bool, optional) – If True, override the file.

_load_structure_data() None[source]

Load structure data from the final data file; fall back to the temporary file if needed. :raises Exception: If no valid structure data could be loaded.

get_list_lois()[source]

Returns list of LOIs

detect_sarcomeres(frames: str | int | List[int] | numpy.ndarray = 'all', model_path: str = None, max_patch_size: Tuple[int, int] = (1024, 1024), normalization_mode: str = 'all', clip_thres: Tuple[float, float] = (0.0, 99.98), progress_notifier: bio_image_unet.progress.ProgressNotifier = ProgressNotifier.progress_notifier_tqdm())[source]

Predict sarcomeres (Z-bands, mbands, distance, orientation) with U-Net.

Parameters:
  • frames (Union[str, int, List[int], np.ndarray]) – Frames for sarcomere detection (‘all’ for all frames, int for a single frame, list or ndarray for selected frames). Defaults to ‘all’.

  • model_path (str, optional) – Path of trained network weights for U-Net. Default is None.

  • max_patch_size (tuple of int, optional) – Maximal patch dimensions for convolutional neural network (n_x, n_y). Default is (1024, 1024).

  • normalization_mode (str, optional) – Mode for intensity normalization for 3D stacks prior to prediction (‘single’: each image individually, ‘all’: based on histogram of full stack, ‘first’: based on histogram of first image in stack). Default is ‘all’.

  • clip_thres (tuple of float, optional) – Clip threshold (lower / upper) for intensity normalization. Default is (0., 99.8).

  • progress_notifier (ProgressNotifier, optional) – Progress notifier for inclusion in GUI. Default is ProgressNotifier.progress_notifier_tqdm().

Return type:

None

detect_z_bands_fast_movie(model_path: str | None = None, max_patch_size: Tuple[int, int, int] = (32, 256, 256), normalization_mode: str = 'all', clip_thres: Tuple[float, float] = (0.0, 99.8), progress_notifier: bio_image_unet.progress.ProgressNotifier = ProgressNotifier.progress_notifier_tqdm()) None[source]

Predict sarcomere z-bands with 3D U-Net for high-speed movies for improved temporal consistency.

Parameters:
  • model_path (str, optional) – Path of trained network weights for 3D U-Net. Default is None.

  • max_patch_size (tuple of int, optional) – Maximal patch dimensions for convolutional neural network (n_frames, n_x, n_y). Dimensions need to be divisible by 16. Default is (32, 256, 256).

  • normalization_mode (str, optional) – Mode for intensity normalization for 3D stacks prior to prediction (‘single’: each image individually, ‘all’: based on histogram of full stack, ‘first’: based on histogram of first image in stack). Default is ‘all’.

  • clip_thres (tuple of float, optional) – Clip threshold (lower / upper) for intensity normalization. Default is (0., 99.8).

  • progress_notifier (ProgressNotifier, optional) – Progress notifier for inclusion in GUI. Default is ProgressNotifier.progress_notifier_tqdm().

Return type:

None

analyze_cell_mask(frames: str | int | List[int] | numpy.ndarray = 'all', threshold: float = 0.1) None[source]

Analyzes the area occupied by cells in the given image(s) and calculates the average cell intensity and cell area ratio.

Parameters:
  • threshold (float, optional) – Threshold value for binarizing the cell mask image. Pixels with intensity above threshold are considered cell. Defaults to 0.1.

  • frames ({'all', int, list, np.ndarray}, optional) – Frames for z-band analysis (‘all’ for all frames, int for a single frame, list or ndarray for selected frames). Defaults to ‘all’.

analyze_z_bands(frames: str | int | List[int] | numpy.ndarray = 'all', threshold: float = 0.5, min_length: float = 0.2, median_filter_radius: float = 0.2, theta_phi_min: float = 0.4, a_min: float = 0.3, d_max: float = 3.0, d_min: float = 0.0, progress_notifier: bio_image_unet.progress.ProgressNotifier = ProgressNotifier.progress_notifier_tqdm()) None[source]

Segment and analyze sarcomere z-bands.

Parameters:
  • frames ({'all', int, list, np.ndarray}, optional) – Frames for z-band analysis (‘all’ for all frames, int for a single frame, list or ndarray for selected frames). Defaults to ‘all’.

  • threshold (float, optional) – Threshold for binarizing z-bands prior to labeling (0 - 1). Defaults to 0.1.

  • min_length (float, optional) – Minimal length of z-bands; smaller z-bands are removed (in µm). Defaults to 0.5.

  • median_filter_radius (float, optional) – Radius of kernel to smooth sarcomere orientation field. Default is 0.2 µm.

  • theta_phi_min (float, optional) – Minimal cosine of the angle between the pointed z-band vector and the connecting vector between ends of z-bands. Smaller values are not recognized as connections (for lateral alignment and distance analysis). Defaults to 0.25.

  • a_min (float, optional) – Minimal lateral alignment between z-band ends to create a lateral connection. Defaults to 0.3.

  • d_max (float, optional) – Maximal distance between z-band ends (in µm). Z-band end pairs with larger distances are not connected (for lateral alignment and distance analysis). Defaults to 5.0.

  • d_min (float, optional) – Minimal distance between z-band ends (in µm). Z-band end pairs with smaller distances are not connected. Defaults to 0.25.

  • progress_notifier (ProgressNotifier) – Wraps progress notification, default is progress notification done with tqdm

analyze_sarcomere_vectors(frames: str | int | List[int] | numpy.ndarray = 'all', threshold_mbands: float = 0.5, median_filter_radius: float = 0.25, linewidth: float = 0.2, interp_factor: int = 0, slen_lims: Tuple[float, float] = (1, 3), threshold_sarcomere_mask=0.1, backend='loky', progress_notifier: bio_image_unet.progress.ProgressNotifier = ProgressNotifier.progress_notifier_tqdm()) None[source]

Extract sarcomere orientation and length vectors.

Parameters:
  • frames ({'all', int, list, np.ndarray}, optional) – frames for sarcomere vector analysis (‘all’ for all frames, int for a single frame, list or ndarray for selected frames). Defaults to ‘all’.

  • threshold_mbands (float, optional) – Threshold to binarize sarcomere M-bands. Lower values might result in more false-positive sarcomere vectors. Defaults to 0.2.

  • median_filter_radius (float, optional) – Radius of kernel to smooth orientation field before assessing orientation at M-points, in µm (default 0.25 µm).

  • linewidth (float, optional) – Line width of profile lines to analyze sarcomere lengths, in µm (default is 0.3 µm).

  • interp_factor (int, optional) – Interpolation factor for profiles to calculate sarcomere length. Default to 4.

  • slen_lims (tuple of float, optional) – Sarcomere size limits in µm (default is (1, 3) µm).

  • threshold_sarcomere_mask (float) – Threshold to binarize sarcomere masks. Defaults to 0.1.

  • backend (str, optional) – Backend for parallelization of profile processing. Defaults to ‘loky’.

  • progress_notifier (ProgressNotifier) – Wraps progress notification, default is progress notification done with tqdm

Returns:

  • sarcomere_orientation_points (np.ndarray) – Sarcomere orientation values at midline points.

  • sarcomere_length_points (np.ndarray) – Sarcomere length values at midline points.

analyze_myofibrils(frames: str | int | List[int] | numpy.ndarray | None = None, ratio_seeds: float = 0.1, persistence: int = 3, threshold_distance: float = 0.5, n_min: int = 4, median_filter_radius: float = 0.5, progress_notifier: bio_image_unet.progress.ProgressNotifier = ProgressNotifier.progress_notifier_tqdm()) None[source]

Estimate myofibril lines by line growth algorithm and analyze length and curvature.

Parameters:
  • frames ({'all', int, list, np.ndarray}, optional) – frames for myofibril analysis (‘all’ for all frames, int for a single frame, list or ndarray for selected frames). If None, frames from sarcomere vector analysis are used. Defaults to None.

  • ratio_seeds (float, optional) – Ratio of sarcomere vector used as seeds for line growth. Defaults to 0.1.

  • persistence (int, optional) – Persistence of line (average vector length and orientation for prior estimation), needs to be > 0. Defaults to 3.

  • threshold_distance (float, optional) – Maximal distance for nearest neighbor estimation (in micrometers). Defaults to 0.3.

  • n_min (int, optional) – Minimal number of sarcomere line segments per line. Shorter lines are removed. Defaults to 5.

  • median_filter_radius (float, optional) – Filter radius for smoothing myofibril length map (in micrometers). Defaults to 0.5.

  • progress_notifier (ProgressNotifier) – Wraps progress notification, default is progress notification done with tqdm

analyze_sarcomere_domains(frames: str | int | List[int] | numpy.ndarray | None = None, d_max: float = 3, cosine_min: float = 0.65, leiden_resolution: float = 0.06, random_seed: int = 42, area_min: float = 20.0, dilation_radius: float = 0.3, progress_notifier: bio_image_unet.progress.ProgressNotifier = ProgressNotifier.progress_notifier_tqdm()) None[source]

Cluster sarcomeres into domains based on their spatial and orientational properties using the Leiden algorithm for community detection.

Parameters:
  • frames ({'all', int, list, np.ndarray}, optional) – frames for domain analysis (‘all’ for all frames, int for a single frame, list or ndarray for selected frames). If None, frames from sarcomere vector analysis are used. Defaults to None.

  • d_max (float) – Max. distance threshold for creating a network edge between vector ends

  • cosine_min (float) – Minimal absolute cosine between vector angles for creating a network edge between vector ends

  • leiden_resolution (float, optional) – Control parameter for domain size. If resolution is small, the algorithm favors larger domains. Greater resolution favors smaller domains. Defaults to 0.05.

  • random_seed (int, optional) – Random seed for Leiden algorithm, to ensure reproducibility. Defaults to 2.

  • area_min (float, optional) – Minimal area of domains/clusters (in µm^2). Defaults to 50.0.

  • dilation_radius (float, optional) – Dilation radius for refining domain area masks, in µm. Defaults to 0.3.

  • progress_notifier (ProgressNotifier) – Wraps progress notification, default is progress notification done with tqdm

_grow_lois(frame: int = 0, ratio_seeds: float = 0.1, persistence: int = 2, threshold_distance: float = 0.3, random_seed: None | int = None) None[source]

Find LOIs (lines of interest) using a line growth algorithm. The parameters **lims can be used to filter LOIs.

Parameters:
  • frame (int, optional) – Frame to select frame. Selects i-th frame of frames specified in sarcomere vector analysis. Defaults to 0.

  • ratio_seeds (float, optional) – Ratio of sarcomere vectors to take as seeds for line growth. Default 0.1.

  • persistence (int, optional) – Persistence of line (average vector length and orientation for prior estimation). Defaults to 2.

  • threshold_distance (float, optional) – Maximal distance for nearest neighbor estimation. Defaults to 0.5.

  • random_seed (int, optional) – Random seed for reproducibility. Defaults to None.

_filter_lois(number_lims: Tuple[int, int] = (10, 100), length_lims: Tuple[float, float] = (0, 200), sarcomere_mean_length_lims: Tuple[float, float] = (1, 3), sarcomere_std_length_lims: Tuple[float, float] = (0, 1), midline_mean_length_lims: Tuple[float, float] = (0, 50), midline_std_length_lims: Tuple[float, float] = (0, 50), midline_min_length_lims: Tuple[float, float] = (0, 50)) None[source]

Filters Lines of Interest (LOIs) based on various geometric and morphological criteria.

Parameters:
  • number_lims (tuple of int, optional) – Limits of sarcomere numbers in LOI (min, max). Defaults to (10, 100).

  • length_lims (tuple of float, optional) – Limits for LOI lengths (in µm) (min, max). Defaults to (0, 200).

  • sarcomere_mean_length_lims (tuple of float, optional) – Limits for mean length of sarcomeres in LOI (min, max). Defaults to (1, 3).

  • sarcomere_std_length_lims (tuple of float, optional) – Limits for standard deviation of sarcomere lengths in LOI (min, max). Defaults to (0, 1).

  • midline_mean_length_lims (tuple of float, optional) – Limits for mean length of the midline in LOI (min, max). Defaults to (0, 50).

  • midline_std_length_lims (tuple of float, optional) – Limits for standard deviation of the midline length in LOI (min, max). Defaults to (0, 50).

  • midline_min_length_lims (tuple of float, optional) – Limits for minimum length of the midline in LOI (min, max). Defaults to (0, 50).

_hausdorff_distance_lois(symmetry_mode: str = 'max') None[source]

Compute Hausdorff distances between all good LOIs.

Parameters:

symmetry_mode (str, optional) – Choose ‘min’ or ‘max’, whether min/max(H(loi_i, loi_j), H(loi_j, loi_i)). Defaults to ‘max’.

_cluster_lois(distance_threshold_lois: float = 40, linkage: str = 'single') None[source]

Agglomerative clustering of good LOIs using predefined Hausdorff distance matrix using scikit-learn.

Parameters:
  • distance_threshold_lois (float, optional) – The linkage distance threshold above which clusters will not be merged. Defaults to 40.

  • linkage ({'complete', 'average', 'single'}, optional) – Which linkage criterion to use. The linkage criterion determines which distance to use between sets of observations. The algorithm will merge the pairs of clusters that minimize this criterion. - ‘average’ uses the average of the distances of each observation of the two sets. - ‘complete’ or ‘maximum’ linkage uses the maximum distances between all observations of the two sets. - ‘single’ uses the minimum of the distances between all observations of the two sets. Defaults to ‘single’.

_fit_straight_line(add_length=1, n_lois=None)[source]

Fit linear lines to cluster points

Parameters:
  • add_length (float) – Elongate line at end with add_length (in length unit)

  • n_lois (int) – If int, only n longest LOIs are saved. If None, all are saved.

_longest_in_cluster(n_lois, frame)[source]
_random_from_cluster(n_lois, frame)[source]
_random_lois(n_lois, frame)[source]
create_loi_data(line: numpy.ndarray, linewidth: float = 0.65, order: int = 0, export_raw: bool = False) None[source]

Extract intensity kymograph along LOI and create LOI file from line.

Parameters:
  • line (np.ndarray) – Line start and end coordinates ((start_x, start_y), (end_x, end_y)) or list of segments [(x0, y0), (x1, y1), (x2, y2), …]

  • linewidth (float, optional) – Width of the scan in µm, perpendicular to the line. Defaults to 0.65.

  • order (int, optional) – The order of the spline interpolation, default is 0 if image.dtype is bool and 1 otherwise. The order has to be in the range 0-5. See skimage.transform.warp for details. Defaults to 0.

  • export_raw (bool, optional) – If True, intensity kymograph along LOI from raw microscopy image is additionally stored. Defaults to False.

detect_lois(frame: int = 0, n_lois: int = 4, ratio_seeds: float = 0.1, persistence: int = 4, threshold_distance: float = 0.5, mode: str = 'longest_in_cluster', random_seed: int | None = None, number_lims: Tuple[int, int] = (10, 50), length_lims: Tuple[float, float] = (0, 200), sarcomere_mean_length_lims: Tuple[float, float] = (1, 3), sarcomere_std_length_lims: Tuple[float, float] = (0, 1), midline_mean_length_lims: Tuple[float, float] = (0, 50), midline_std_length_lims: Tuple[float, float] = (0, 50), midline_min_length_lims: Tuple[float, float] = (0, 50), distance_threshold_lois: float = 40, linkage: str = 'single', linewidth: float = 0.65, order: int = 0, export_raw: bool = False) None[source]

Detects Regions of Interest (LOIs) for tracking sarcomere Z-band motion and creates kymographs.

This method integrates several steps: growing LOIs based on seed vectors, filtering LOIs based on specified criteria, clustering LOIs, fitting lines to LOI clusters, and extracting intensity profiles to generate kymographs.

Parameters:
  • frame (int) – The index of the frame to select for analysis.

  • n_lois (int) – Number of LOIs.

  • ratio_seeds (float) – Ratio of sarcomere vectors to take as seed vectors for initiating LOI growth.

  • persistence (int) – Persistence parameter influencing line growth direction and termination.

  • threshold_distance (float) – Maximum distance for nearest neighbor estimation during line growth.

  • mode (str) – Mode for selecting LOIs from identified clusters. - ‘fit_straight_line’ fits a straight line to all midline points in the cluster. - ‘longest_in_cluster’ selects the longest line of each cluster, also allowing curved LOIs. - ‘random_from_cluster’ selects a random line from each cluster, also allowing curved LOIs. - ‘random_line’ selects a set of random lines that fulfil the filtering criteria.

  • random_seed (int, optional) – Random seed for selection of random starting vectors for line growth algorithm, for reproducible outcomes. If None, no random seed is set, and outcomes in every run will differ.

  • number_lims (tuple of int) – Limits for the number of sarcomeres within an LOI (min, max).

  • length_lims (tuple of float) – Length limits for LOIs (in µm) (min, max).

  • sarcomere_mean_length_lims (tuple of float) – Limits for the mean length of sarcomeres within an LOI (min, max).

  • sarcomere_std_length_lims (tuple of float) – Limits for the standard deviation of sarcomere lengths within an LOI (min, max).

  • midline_mean_length_lims (tuple of float) – Limits for the mean length of the midline of vectors in LOI (min, max).

  • midline_std_length_lims (tuple of float) – Limits for the standard deviation of the midline length of vectors in LOI (min, max).

  • midline_min_length_lims (tuple of float) – Limits for the minimum length of the midline of vectors in LOI (min, max).

  • distance_threshold_lois (float) – Distance threshold for clustering LOIs. Clusters will not be merged above this threshold.

  • linkage (str) – Linkage criterion for clustering (‘complete’, ‘average’, ‘single’).

  • linewidth (float) – Width of the scan line (in µm), perpendicular to the LOIs.

  • order (int) – Order of spline interpolation for transforming LOIs (range 0-5).

  • export_raw (bool) – If True, exports raw intensity kymographs along LOIs.

Return type:

None

delete_lois()[source]

Delete all LOIs, their associated data files, and their directories.

full_analysis_structure(frames='all')[source]

Analyze sarcomere structure with default parameters at specified frames

Parameters:

frames ({'all', int, list, np.ndarray}) – frames for analysis (‘all’ for all frames, int for a single frame, list or ndarray for selected frames).

static segment_z_bands(image: numpy.ndarray, threshold: float = 0.15) Tuple[numpy.ndarray, numpy.ndarray][source]

Segment z-bands from U-Net result (threshold, make binary, skeletonize, label regions).

Parameters:
  • image (np.ndarray) – Input image from U-Net.

  • threshold (float, optional) – Threshold value for binarizing the image. Defaults to 0.15.

Returns:

  • labels (np.ndarray) – Labeled regions in the thresholded image.

  • labels_skel (np.ndarray) – Labeled regions in the skeletonized image.

static _analyze_z_bands(zbands: numpy.ndarray, labels: numpy.ndarray, labels_skel: numpy.ndarray, image_raw: numpy.ndarray, orientation_field: numpy.ndarray, pixelsize: float, min_length: float = 1.0, threshold: float = 0.1, median_filter_radius: float = 0.25, a_min: float = 0.3, theta_phi_min: float = 0.2, d_max: float = 4.0, d_min: float = 0.25) Tuple[source]

Analyzes segmented z-bands in a single frame, extracting metrics such as length, intensity, orientation, straightness, lateral distance, alignment, number of lateral neighbors per z-band, and characteristics of groups of lateral z-bands (length, alignment, size).

Parameters:
  • zbands (np.ndarray) – The segmented map of z-bands.

  • labels (np.ndarray) – The labeled image of z-bands.

  • labels_skel (np.ndarray) – The skeletonized labels of z-bands.

  • image_raw (np.ndarray) – The raw image.

  • orientation_field (np.ndarray) – Sarcomere orientation field.

  • pixelsize (float) – The size of pixels in the image.

  • min_length (float, optional) – The minimum length threshold for z-bands. Default is 1.0.

  • threshold (float, optional) – The threshold value for intensity. Default is 0.1.

  • median_filter_radius (float, optional) – Radius of kernel to smooth orientation field. Default is 0.2 µm.

  • a_min (float, optional) – The minimum value for alignment. Default is 0.25. Links with smaller alignment are set to np.nan.

  • theta_phi_min (float, optional) – The minimum dot product/cosine between the direction of a Z-band end and the direction of line from end to other Z-band end.

  • d_max (float, optional) – The maximum distance between z-band ends. Default is 5.0 µm. Larger distances are set to np.nan.

  • d_min (float, optional) – The minimum distance between z-band ends. Default is 0 µm. Smaller distances are set to np.nan.

Returns:

A comprehensive tuple containing arrays and values describing the analyzed properties of z-bands: - Lengths, intensities, straightness, ratio of intensities, average intensity, orientations,

orientational order parameter, list of z-band labels, processed labels image, number of lateral neighbors, lateral distances, lateral alignments, links between z-band ends, coordinates of z-band ends, linked groups of z-bands, and their respective sizes, lengths, and alignments.

Return type:

tuple

static get_sarcomere_vectors(zbands: numpy.ndarray, mbands: numpy.ndarray, orientation_field: numpy.ndarray, pixelsize: float, median_filter_radius: float = 0.25, slen_lims: Tuple[float, float] = (1, 3), interp_factor: int = 4, linewidth: float = 0.3, backend: str = 'loky') Tuple[numpy.ndarray | List, numpy.ndarray | List, numpy.ndarray | List, numpy.ndarray | List, numpy.ndarray | List, numpy.ndarray | List, numpy.ndarray | List][source]

Extract sarcomere orientation and length vectors.

Parameters:
  • zbands (np.ndarray) – 2D array representing the semantic segmentation map of Z-bands.

  • mbands (np.ndarray) – 2D array representing the semantic segmentation map of mbands.

  • orientation_field (np.ndarray) – 2D array representing the orientation field.

  • pixelsize (float) – Size of a pixel in micrometers.

  • median_filter_radius (float, optional) – Radius of kernel to smooth orientation field before assessing orientation at M-points, in µm (default 0.25 µm).

  • slen_lims (tuple of float, optional) – Sarcomere size limits in micrometers (default is (1, 3)).

  • interp_factor (int, optional) – Interpolation factor for profiles to calculate sarcomere length. Defaults to 4.

  • linewidth (float, optional) – Line width of profiles to calculate sarcomere length. Defaults to 0.3 µm.

Returns:

  • pos_vectors (np.ndarray) – Array of position vectors for sarcomeres.

  • sarcomere_orientation_vectors (np.ndarray) – Sarcomere orientation values at midline points.

  • sarcomere_length_vectors (np.ndarray) – Sarcomere length values at midline points.

  • sarcomere_mask (np.ndarray) – Mask indicating the presence of sarcomeres.

static cluster_sarcomeres(pos_vectors: numpy.ndarray, sarcomere_length_vectors: numpy.ndarray, sarcomere_orientation_vectors: numpy.ndarray, pixelsize: float, size: Tuple[int, int], d_max: float = 3, cosine_min: float = 0.65, leiden_resolution: float = 0.06, random_seed: int = 42, area_min: float = 20, dilation_radius: float = 0.3) Tuple[int, List, List, List, List, List, numpy.ndarray][source]

This function clusters sarcomeres into domains based on their spatial and orientational properties using the Leiden method for community detection in igraph. It considers sarcomere lengths, orientations, and positions along mbands to form networks of connected sarcomeres. Domains are then identified as communities within these networks, with additional criteria for minimum domain area and connectivity thresholds. Finally, this function quantifies the mean and std of sarcomere lengths, and the orientational order parameter and mean orientation of each domain.

Parameters:
  • pos_vectors (np.ndarray) – Array of sarcomere midline point positions in µm.

  • sarcomere_length_vectors (np.ndarray) – List of midline point sarcomere lengths

  • sarcomere_orientation_vectors (np.ndarray) – List of midline point sarcomere orientations, in radians

  • pixelsize (float) – Pixel size in µm

  • size (tuple(int, int)) – Shape of the image in pixels

  • d_max (float) – Max. distance threshold for creating a network edge between vector ends

  • cosine_min (float) – Minimal absolute cosine between vector angles for creating a network edge between vector ends

  • leiden_resolution (float) – Resolution parameter for the Leiden algorithm

  • random_seed (int) – Random seed for reproducibility

  • area_min (float) – Minimal area (in µm²) for a domain to be kept

  • dilation_radius (float) – Dilation radius for refining domain area masks (in µm)

Returns:

  • n_domains (int) – Number of domains

  • domains (list) – List of domain sets with point indices

  • area_domains (list) – List with domain areas

  • sarcomere_length_mean_domains (list) – Mean sarcomere length within each domain

  • sarcomere_length_std_domains (list) – Standard deviation of sarcomere length within each domain

  • sarcomere_oop_domains (list) – Orientational order parameter of sarcomeres in each domain

  • sarcomere_orientation_domains (list) – Main orientation of domains

  • mask_domains (ndarray) – Masks of domains with value representing domain label

static _grow_line(seed, points_t, sarcomere_length_vectors_t, sarcomere_orientation_vectors_t, nbrs, threshold_distance, pixelsize, persistence)[source]
static line_growth(points_t: numpy.ndarray, sarcomere_length_vectors_t: numpy.ndarray, sarcomere_orientation_vectors_t: numpy.ndarray, midline_length_vectors_t: numpy.ndarray, pixelsize: float, ratio_seeds: float = 0.1, persistence: int = 4, threshold_distance: float = 0.3, n_min: int = 5, random_seed: None | int = None)[source]

Line growth algorithm to determine myofibril lines perpendicular to sarcomere z-bands

Parameters:
  • points_t (np.ndarray) – List of midline point positions

  • sarcomere_length_vectors_t (list) – Sarcomere length at midline points

  • sarcomere_orientation_vectors_t (list) – Sarcomere orientation angle at midline points, in radians

  • midline_length_vectors_t (list) – Length of sarcomere mbands of midline points

  • pixelsize (float) – Pixel size in µm

  • ratio_seeds (float) – Ratio of sarcomere vectors to be takes as seeds for line growth

  • persistence (int) – Number of points to consider for averaging length and orientation.

  • random_seed (int, optional) – Random seed for reproducibility. Defaults to None.

Returns:

line_data – Dictionary with LOI data keys = (lines, line_features)

Return type:

dict

static kymograph_movie(movie: numpy.ndarray, line: numpy.ndarray, linewidth: int = 10, order: int = 0)[source]

Generate a kymograph using multiprocessing.

Parameters:
  • movie (np.ndarray, shape (N, H, W)) – The movie.

  • line (np.ndarray, shape (N, 2)) – The coordinates of the segmented line (N>1)

  • linewidth (int, optional) – Width of the scan in pixels, perpendicular to the line

  • order (int in {0, 1, 2, 3, 4, 5}, optional) – The order of the spline interpolation, default is 0 if image.dtype is bool and 1 otherwise. The order has to be in the range 0-5. See skimage.transform.warp for detail.

Returns:

return_value – Kymograph along segmented line

Return type:

ndarray

Notes

Adapted from scikit-image (https://scikit-image.org/docs/0.22.x/api/skimage.measure.html#skimage.measure.profile_line).

static process_frame(args)[source]
static __curved_line_profile_coordinates(points: numpy.ndarray, linewidth: int = 10)

Calculate the coordinates of a curved line profile composed of multiple segments with specified linewidth.

Parameters:
  • points (np.ndarray) – A list of points (y, x) defining the segments of the curved line.

  • linewidth (int, optional) – The width of the line in pixels.

Returns:

coords – The coordinates of the curved line profile. Shape is (2, N, linewidth), where N is the total number of points in the line.

Return type:

ndarray

static sarcomere_mask(points: numpy.ndarray, sarcomere_orientation_vectors: numpy.ndarray, sarcomere_length_vectors: numpy.ndarray, shape: Tuple[int, int], pixelsize: float, dilation_radius: float = 0.3) numpy.ndarray[source]

Calculates a binary mask of areas with sarcomeres.

Parameters:
  • points (ndarray) – Positions of sarcomere vectors in µm. (n_vectors, 2)

  • sarcomere_orientation_vectors (ndarray) – Orientations of sarcomere vectors.

  • sarcomere_length_vectors (ndarray) – Lengths of sarcomere vectors in µm.

  • shape (tuple) – Shape of the image, in pixels.

  • pixelsize (float) – Pixel size in µm.

  • dilation_radius (float, optional) – Dilation radius to close small holes in mask, in µm (default is 0.3).

Returns:

mask – Binary mask of sarcomeres.

Return type:

ndarray

static _analyze_domains(domains: List, pos_vectors: numpy.ndarray, sarcomere_orientation_vectors: numpy.ndarray, sarcomere_length_vectors: numpy.ndarray, size: Tuple[int, int], pixelsize: float, dilation_radius: float, area_min: float)[source]

Creates a domain mask, where each domain has a distinct label, and analyzes the individual domains.

Parameters:
  • domains (list) – List with domain labels for each vector. Each domain is labeled with a unique integer.

  • pos_vectors (ndarray) – Position vectors in micrometers.

  • sarcomere_orientation_vectors (ndarray) – Orientation angles in radians.

  • sarcomere_length_vectors (ndarray) – Sarcomere lengths in micrometers.

  • size (tuple of int) – Output map dimensions (height, width) in pixels.

  • pixelsize (float) – Physical size of one pixel in micrometers.

  • dilation_radius (float, optional) – Dilation radius for refining domain masks, in µm.

  • area_min (float, optional) – Minimal area of a domain in µm^2, smaller domains are discarded.

static create_myofibril_length_map(myof_lines: numpy.ndarray, myof_length: numpy.ndarray, pos_vectors: numpy.ndarray, sarcomere_orientation_vectors: numpy.ndarray, sarcomere_length_vectors: numpy.ndarray, size: tuple, pixelsize: float, median_filter_radius: float = 0.6) numpy.ndarray[source]

The create_myofibril_length_map function generates a 2D spatial map of myofibril lengths represented as pixel values. It achieves this by rasterizing myofibril line segments, assigning their corresponding lengths to the pixels they occupy, and averaging these values at overlapping pixels. The resulting map is optionally smoothed using a median filter to reduce noise and provide a more coherent spatial representation.

Parameters:
  • myof_lines (ndarray) – Line indices for myofibril structures.

  • myof_length (ndarray) – Length values for each myofibril line.

  • pos_vectors (ndarray) – Position vectors in micrometers.

  • sarcomere_orientation_vectors (ndarray) – Orientation angles in radians.

  • sarcomere_length_vectors (ndarray) – Sarcomere lengths in micrometers.

  • size (tuple of int) – Output map dimensions (height, width) in pixels.

  • pixelsize (float) – Physical size of one pixel in micrometers.

  • median_filter_radius (float, optional) – Filter radius in micrometers, by default 0.6.

Returns:

2D array of calculated myofibril lengths with NaN for empty regions.

Return type:

ndarray

class sarcasm.Motion(filename: str, loi_name: str, restart: bool = False, auto_save: bool = True)[source]

Bases: sarcasm.core.SarcAsM

Class 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()
static get_loi_name_from_file_name(filename) str[source]
__get_loi_data_file_name(is_temp_file=False) str
load_loi_data()[source]
store_loi_data()[source]

Save LOI data

commit()[source]
read_profile_data()[source]

Read z-band profile data

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 = 2, 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))[source]

Track peaks of intensity profile over time with Crocker-Grier algorithm from TrackPy package

Parameters:
  • search_range (float) – Search range for tracking algorithm (see documentation of trackpy package)

  • memory_tracking (int) – Memory for tracking algorithm, in frames (see documentation of trackpy package)

  • memory_interpol (int) – Memory (max interval) to interpolate gaps in trajectories, in frames (see documentation of trackpy package)

  • t_range (float[int, int]) – If not None, select time-interval of data, in frames

  • z_range (float[int, int]) – If not None, select range of z-bands

  • min_length (float) – Minimal length of z-band trajectory in seconds. Shorter trajectories will not be deleted but set to np.nan.

  • filter_params (tuple(float, float)) – Parameters window length and poly order of Savitzky-Golay filter to smooth z position

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

  1. Predict contractions / contraction state (0 = quiescent, 1 = contracting) from sarcomere lengths (average or percentile)

  2. 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).

  3. 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]
  1. Calculate sarcomere lengths (single and avg) and filter too large and too small values (slen_lims).

  2. Calculate sarcomere velocities (single and avg), prior smoothing of s’lengths with Savitzky-Golay filter

    (filter_params_vel)

  3. 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

full_analysis_loi()[source]

Full analysis of LOI with default parameters

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.

class sarcasm.Utils[source]

Miscellaneous utility functions

static get_device(print_device=False, no_cuda_warning=False)[source]

Determines the most suitable device (CUDA, MPS, or CPU) for PyTorch operations.

Parameters: - print_device (bool): If True, prints the device being used. - no_cuda_warning (bool): If True, prints a warning if neither CUDA nor MPS is available.

Returns: - torch.device: The selected device for PyTorch operations.

static today_date()[source]

Get today’s date in the format ‘YYYYMMDD’.

Returns:

Today’s date in ‘YYYYMMDD’ format.

Return type:

str

static get_tif_files_in_folder(folder: str) List[str][source]

Find all .tif files in a specified folder.

Parameters:

folder (str) – Path to the folder.

Returns:

List of file paths to the .tif files.

Return type:

list

static get_lois_of_file(filename_cell: str) List[Tuple[str, str]][source]

Get the lines of interests (LOIs) of a tif-file.

Parameters:

filename_cell (str) – Path to the file of the cell.

Returns:

List of tuples, each containing the cell file path and LOI filename.

Return type:

list

static open_folder(path: str)[source]

Open a folder in the file explorer.

Parameters:

path (str) – Path to the folder.

static two_sample_t_test(data: numpy.ndarray, alpha: float = 0.05) Tuple[numpy.ndarray, numpy.ndarray][source]

Pair-wise two sample t-test of multiple conditions.

Parameters:
  • data (array-like) – Input data for the t-test.

  • alpha (float, optional) – Significance level. Default is 0.05.

Returns:

p-values and significance levels for each pair of conditions.

Return type:

tuple

static nan_sav_golay(data: numpy.ndarray, window_length: int, polyorder: int, axis: int = 0) numpy.ndarray[source]

Apply a Savitzky-Golay filter to data with NaN values along the specified axis.

Parameters:
  • data (array-like) – Input data.

  • window_length (int) – Length of the filter window, must be odd and greater than polyorder.

  • polyorder (int) – Order of the polynomial used for the filtering.

  • axis (int, optional) – The axis along which to apply the filter. The default is 0 (first axis).

Returns:

Filtered data with NaN values preserved.

Return type:

array-like

static nan_low_pass(x: numpy.ndarray, N: int = 6, crit_freq: float = 0.25, min_len: int = 31) numpy.ndarray[source]

Apply a Butterworth low-pass filter to data with NaN values.

Parameters:
  • x (np.ndarray) – Input data.

  • N (int, optional) – Filter order. The higher the order, the steeper the spectral cutoff. Default is 6.

  • crit_freq (float, optional) – Maximum passed frequency. Default is 0.25.

  • min_len (int, optional) – Minimum length of data required to apply the filter. Default is 31.

Returns:

Filtered data with NaN values preserved.

Return type:

np.ndarray

static most_freq_val(array: numpy.ndarray, bins: int = 20) numpy.ndarray[Any, numpy.dtype[Any]][source]

Calculate the most frequent value in an array.

Parameters:
  • array (np.ndarray) – Input array.

  • bins (int, optional) – Number of bins for the histogram calculation. Default is 20.

Returns:

Most frequent value in the array.

Return type:

float

static weighted_avg_and_std(x: numpy.ndarray, weights: numpy.ndarray, axis: int = 0) Tuple[numpy.ndarray, numpy.ndarray][source]

Return the weighted average and standard deviation.

Parameters:
  • x (array-like) – Values.

  • weights (array-like) – Weights.

  • axis (int, optional) – Axis along which to compute the average and standard deviation. Default is 0.

Returns:

Weighted average and weighted standard deviation.

Return type:

tuple

static weighted_quantile(data: numpy.ndarray, weights: numpy.ndarray, quantile: float) float | numpy.ndarray[Any, numpy.dtype[Any]][source]

Compute the weighted quantile of a 1D numpy array.

Parameters:
  • data (np.ndarray) – Input array (one dimension array).

  • weights (np.ndarray) – Array with the weights of the same size of data.

  • quantile (float) – Desired quantile.

Returns:

result – Weighted quantile of data.

Return type:

np.ndarray

static column_weighted_quantiles(data: numpy.ndarray, weights: numpy.ndarray, quantiles: list) numpy.ndarray[source]

Compute the weighted quantile for each column of a 2D numpy array.

Parameters:
  • data (np.ndarray) – Input array (two dimension array).

  • weights (np.ndarray) – Array with the weights of the same size of data.

  • quantiles (list of float) – List with desired quantiles.

Returns:

result – 2D array with weighted quantiles of each data column.

Return type:

np.array

static custom_diff(x: numpy.ndarray, dt: float) numpy.ndarray[source]

Compute derivative of x using central differences.

This function computes the derivative of the input time-series x using central differences. At the edges of x, forward and backward differences are used. The time-series x can be either 1D or 2D.

Parameters:
  • x (ndarray) – The input time-series, must be 1D or 2D.

  • dt (float) – The time interval between pos_vectors in x.

Returns:

v – The derivative of x, has the same shape as x.

Return type:

ndarray

static process_profile(profile: numpy.ndarray, pixelsize: float, slen_lims: tuple = (1, 3), thres: float = 0.25, min_dist: float = 1, width: float = 0.5, interp_factor: int = 4) Tuple[float, float][source]

Find peak distance in a 1D intensity profile using interpolation and center of mass (COM).

This function detects peaks in a normalized 1D intensity profile, optionally interpolates the profile using Akima interpolation, and refines the peak positions using the center of mass within a local window.

Parameters:
  • profile (np.ndarray) – 1D intensity profile.

  • pixelsize (float) – Physical size per pixel.

  • slen_lims (tuple of float, optional) – (min, max) valid peak separation range, by default (1, 3).

  • thres (float, optional) – Peak detection height threshold (0-1), by default 0.25.

  • min_dist (float, optional) – Minimum peak separation in µm, by default 1.

  • width (float, optional) – Half-width of COM window in µm, by default 0.5.

  • interp_factor (int, optional) – Interpolation upsampling factor, by default 4. If ≤ 1, no interpolation is performed.

Returns:

  • slen_profile (float) – Peak separation distance in micrometer, or np.nan if invalid.

  • center_offsets (float) – Offset of the profile center in micrometer, or np.nan if invalid.

Notes

  • For interp_factor ≤ 1, no interpolation is performed and the original profile is used.

  • The function uses Akima1DInterpolator for smooth interpolation when requested.

  • Center of mass calculation is performed in a window around each detected peak for sub-pixel accuracy.

  • If less than two peaks are detected, or the separation is outside slen_lims, returns (np.nan, np.nan).

static peakdetekt(x_pos, y, thres=0.2, thres_abs=False, min_dist=10, width=6, interp_factor=6)[source]

A customized peak detection algorithm using scipy with Akima interpolation.

Parameters:
  • x_pos (ndarray) – An array containing the positions in µm.

  • y (ndarray) – The intensity profile.

  • thres (float, optional) – Threshold for the peak detection. Default is 0.3.

  • thres_abs (bool, optional) – Whether the peak detection threshold is absolute. Default is True.

  • min_dist (int, optional) – Minimum distance between detected peaks, in pixels. Default is 10.

  • width (int, optional) – Width of the region of interest around the detected peaks for the method of moments computation. Default is 6.

  • interp_factor (int, optional) – Factor by which to increase the resolution through interpolation. Default is 10.

Returns:

refined_peaks – An array containing the refined peak positions in µm.

Return type:

ndarray

static peak_by_first_moment(x: numpy.ndarray, y: numpy.ndarray)[source]

Calculate the peak of y using the first moment method.

Parameters:
  • x (numpy.ndarray) – The x-values of the data.

  • y (numpy.ndarray) – The y-values of the data.

Returns:

peak – The calculated peak value.

Return type:

float

static analyze_orientations(orientations: numpy.ndarray)[source]

Calculate the orientational order parameter and mean vector of non-polar elements in 2D. Orientations are expected to be in the range [0, pi]. See https://physics.stackexchange.com/questions/65358/2-d-orientational-order-parameter

Parameters:

orientations (numpy.ndarray) – Array of orientations. In radians.

Returns:

  • oop (float) – The calculated orientational order parameter.

  • angle (float) – The calculated mean vector angle.

static correct_phase_confocal(tif_file: str, shift_max=30)[source]

Correct phase shift for images of Leica confocal resonant scanner in bidirectional mode while conserving metadata.

Parameters:
  • tif_file (str) – Path to the input .tif file.

  • shift_max (int, optional) – Maximum allowed shift, by default 30.

static map_array(array: numpy.ndarray, from_values: List | numpy.ndarray, to_values: List | numpy.ndarray) numpy.ndarray[source]

Map a numpy array from one set of values to a new set of values.

Parameters:
  • array (numpy.ndarray) – The input 2D numpy array.

  • from_values (list) – List of original values.

  • to_values (list) – List of target values.

Returns:

out – The array with values mapped from ‘from_values’ to ‘to_values’.

Return type:

numpy.ndarray

static shuffle_labels(labels: numpy.ndarray, seed=0)[source]

Shuffle labels randomly

Parameters:
  • labels (numpy.ndarray) – The labels to be shuffled.

  • seed (int, optional) – The seed for the random number generator, by default 0.

Returns:

labels_shuffled – The input labels, randomly shuffled.

Return type:

numpy.ndarray

static convert_lists_to_arrays_in_dict(d)[source]
static find_closest(array, x)[source]
static max_orientation_change(angles)[source]
static get_orientation_angle_map(orientation_field: numpy.ndarray, use_median_filter: bool = True, radius: int = 3) numpy.ndarray[source]

Convert a polar vector field into a map of angles for sarcomere orientations.

The function supports both single-image and multi-image inputs. For single-image inputs, the expected shape is (2, H, W). For multi-image inputs, the expected shape is (N, 2, H, W), where N is the number of images.

Parameters:
  • orientation_field (numpy.ndarray) – Polar vector field(s). For a single image, a 3D array of shape (2, H, W). For multiple images, a 4D array of shape (N, 2, H, W).

  • use_median_filter (bool, optional) – Whether to apply a median filter to the resulting angle map. Default is True.

  • radius (int, optional) – Radius of the disk-shaped footprint for the median filter. Default is 3.

Returns:

A 2D or 3D array of angles in radians, mapped to the range [0, π]. If the input is a single image of shape (2, H, W), the output shape is (H, W). If the input contains multiple images of shape (N, 2, H, W), the output shape is (N, H, W).

Return type:

numpy.ndarray

static create_distance_map(sarc_obj)[source]

Creates distance map for sarcomeres from a Structure object. The distance map is 0 at Z-bands and 1 at M-bands.

Parameters:

sarc_obj (Structure) – An object of the Structure class.

Returns:

distance – A 2D array with normalized distances (0 to 1) along sarcomeres.

Return type:

numpy.ndarray

static interpolate_distance_map(image, N=50, method='linear')[source]

Interpolates NaN regions in a 2D image, filling only those regions whose size is less than or equal to a specified threshold.

Parameters:
  • image (numpy.ndarray) – A 2D array representing the input image. NaN values represent gaps to be filled.

  • N (int) – The maximum size (in pixels) of connected NaN regions to interpolate. Regions larger than this threshold will remain unaltered.

  • method (str, optional) – The interpolation method to use. Options are ‘linear’, ‘nearest’, and ‘cubic’. Default is ‘linear’.

Returns:

A 2D array with the same shape as the input image, where small NaN regions (size <= N) have been interpolated. Larger NaN regions are left unchanged.

Return type:

numpy.ndarray

static fast_profile_lines(image, start_points, end_points, linewidth=3, mode='constant', cval=0.0)[source]

Vectorized version of profile_line from scikit-image that processes multiple lines simultaneously.

Parameters:
  • image (ndarray) – The input image from which to sample the profile lines.

  • start_points (array_like) – An array of shape (N, 2) containing the starting coordinates of the lines.

  • end_points (array_like) – An array of shape (N, 2) containing the ending coordinates of the lines.

  • linewidth (int, optional) – The width of the profile line, in pixels. Default is 1.

  • mode (str, optional) – The mode parameter for map_coordinates. Default is ‘constant’.

  • cval (float, optional) – The value used for points outside the boundaries of the input image. Default is 0.0.

Returns:

result – A list containing the sampled profile values for each line.

Return type:

list of ndarray

static median_filter_numba(data, footprint)[source]
static nanmedian_filter_numba(data, window_size)[source]

Applies a nanmedian filter to a 2D array using a sliding window. The function computes the median of each window ignoring NaN values.

text :param data: 2D numpy array of float

Input array with possible NaN values.

Parameters:

window_size – int The size (assumed odd) of the square window.

Returns:

2D numpy array of the same shape as data containing the filtered result.

Return type:

out

class sarcasm.IOUtils[source]

Utility functions for storing and loading IO data.

static __serialize_field(field)
static __deserialize_field(field)
static json_serialize(obj, file_path)[source]
static json_deserialize(file_path)[source]
static __sparse_to_json_serializable(sparse_matrix)
static __json_serializable_to_sparse(json_data)
class sarcasm.Plots[source]

Class with plotting functions for Structure and Motion objects

static plot_stack_overlay(ax: matplotlib.axes.Axes, sarc_obj: sarcasm.structure.Structure | sarcasm.motion.Motion, frames, plot_func, offset=0.025, spine_color='w', xlim=None, ylim=None)[source]

Plot a stack of overlayed subplots on a given Axes object.

Parameters:
  • ax (matplotlib.axes.Axes) – The Axes object on which the stack should be plotted.

  • sarc_obj (Structure) – Data to be plotted in each subplot, which can be an instance of Structure or Motion.

  • frames (list) – The frames at which the subplots should be created.

  • plot_func (function) – The function used to plot the data in each subplot, e.g.

  • offset (float, optional) – The offset between each subplot. Defaults to 0.025.

  • spine_color (str, optional) – The color of the spines (borders) of each subplot. Defaults to ‘w’ (white).

  • xlim (tuple, optional) – The x-axis limits for each subplot. Defaults to None.

  • ylim (tuple, optional) – The y-axis limits for each subplot. Defaults to None.

static plot_loi_summary_motion(motion_obj: sarcasm.motion.Motion, number_contr=0, t_lim=(0, 12), t_lim_overlay=(-0.1, 2.9), filename=None)[source]

Plots a summary of the motion of the line of interest (LOI).

Parameters:
  • motion_obj (Motion) – The Motion object to plot.

  • number_contr (int, optional) – The number of contractions to plot. Defaults to 0.

  • t_lim (tuple of float, optional) – The time limits for the plot in seconds. Defaults to (0, 12).

  • t_lim_overlay (tuple of float, optional) – The time limits for the overlay plots in seconds. Defaults to (-0.1, 2.9)

  • filename (str, optional) – The filename to save the plot. Defaults to None.

static plot_loi_detection(sarc_obj: sarcasm.structure.Structure, frame: int = 0, filepath: str = None, cmap_z_bands='Greys')[source]

Plots all steps of automated LOI finding algorithm

Parameters:
  • sarc_obj (Structure) – Instance of Structure class

  • frame (int) – The time point to plot.

  • filepath (str) – Path to save the plot. If None, plot is not saved.

  • cmap_z_bands (str, optional) – Colormap of Z-bands. Defaults to ‘Greys’.

static plot_image(ax: matplotlib.axes.Axes, sarc_obj: sarcasm.structure.Structure | sarcasm.motion.Motion, frame: int = 0, cmap: str = 'grey', alpha: float = 1, clip_thrs: Tuple[float, float] = (1, 99), scalebar: bool = True, title: None | str = None, show_loi: bool = False, zoom_region: Tuple[int, int, int, int] = None, inset_bounds: Tuple[float, float, float, float] = (0.6, 0.6, 0.4, 0.4))[source]

Plots microscopy raw image of the sarcomere object.

Parameters:
  • ax (matplotlib.axes.Axes) – The axes to draw the plot on.

  • sarc_obj (Structure or Motion) – The sarcomere object to plot.

  • frame (int, optional) – The frame to plot. Defaults to 0.

  • cmap (matplotlib.cm.Colormap, optional) – The colormap to use. Defaults to ‘gray’.

  • alpha (float, optional) – The transparency to use. Defaults to 1.

  • clip_thrs (tuple, optional) – Clipping thresholds to normalize intensity, in percentiles. Defaults to (1, 99).

  • scalebar (bool, optional) – Whether to add a scalebar to the plot. Defaults to True.

  • title (str, optional) – The title for the plot. Defaults to None.

  • show_loi (bool, optional) – Whether to show the line of interest (LOI). Defaults to True.

  • zoom_region (tuple of int, optional) – The region to zoom in on, specified as (x1, x2, y1, y2). Defaults to None.

  • inset_bounds (tuple of float, optional) – Bounds of inset axis, specified as (x0, y0, width, height). Defaults to (0.6, 0.6, 0.4, 0.4).

static plot_z_bands(ax: matplotlib.pyplot.Axes, sarc_obj: sarcasm.structure.Structure | sarcasm.motion.Motion, frame=0, cmap='Greys_r', zero_transparent=False, alpha=1, scalebar=True, title=None, color_scalebar='w', show_loi=False, zoom_region: Tuple[int, int, int, int] = None, inset_bounds=(0.6, 0.6, 0.4, 0.4))[source]

Plots the Z-bands of the sarcomere object.

Parameters:
  • ax (matplotlib.axes.Axes) – The axes to draw the plot on.

  • sarc_obj (Structure or Motion) – The sarcomere object to plot.

  • frame (int, optional) – The frame to plot. Defaults to 0.

  • cmap (matplotlib.cm.Colormap, optional) – Colormap to use. Defaults to ‘Greys_r’.

  • alpha (float, optional) – Alpha value to change opacity of image. Defaults to 1

  • scalebar (bool, optional) – Whether to add a scalebar to the plot. Defaults to True.

  • title (str, optional) – The title for the plot. Defaults to None.

  • show_loi (bool, optional) – Whether to show the line of interest (LOI). Defaults to True.

  • zoom_region (tuple of int, optional) – The region to zoom in on, specified as (x1, x2, y1, y2). Defaults to None.

  • inset_bounds (tuple of float, optional) – Bounds of inset axis, specified as (x0, y0, width, height). Defaults to (0.6, 0.6, 0.4, 0.4).

plot_z_bands_midlines(sarc_obj: sarcasm.structure.Structure | sarcasm.motion.Motion, frame=0, cmap='berlin', alpha=1, scalebar=True, title=None, color_scalebar='w', show_loi=True, zoom_region: Tuple[int, int, int, int] = None, inset_bounds=(0.6, 0.6, 0.4, 0.4))[source]

Plots the Z-bands and midlines of the sarcomere object.

Parameters:
  • ax (matplotlib.axes.Axes) – The axes to draw the plot on.

  • sarc_obj (Structure or Motion) – The sarcomere object to plot.

  • frame (int, optional) – The frame to plot. Defaults to 0.

  • cmap (matplotlib.cm.Colormap, optional) – Colormap to use. Defaults to ‘Blues_r’.

  • alpha (float, optional) – Alpha value to change opacity of image. Defaults to 1

  • scalebar (bool, optional) – Whether to add a scalebar to the plot. Defaults to True.

  • title (str, optional) – The title for the plot. Defaults to None.

  • show_loi (bool, optional) – Whether to show the line of interest (LOI). Defaults to True.

  • zoom_region (tuple of int, optional) – The region to zoom in on, specified as (x1, x2, y1, y2). Defaults to None.

  • inset_bounds (tuple of float, optional) – Bounds of inset axis, specified as (x0, y0, width, height). Defaults to (0.6, 0.6, 0.4, 0.4).

static plot_cell_mask(ax: matplotlib.axes.Axes, sarc_obj: sarcasm.structure.Structure | sarcasm.motion.Motion, frame=0, threshold=0.5, cmap='gray', alpha=1, scalebar=True, title=None)[source]

Plots the cell mask of the sarcomere object.

Parameters:
  • ax (matplotlib.axes.Axes) – The axes to draw the plot on.

  • sarc_obj (Structure or Motion) – The sarcomere object to plot.

  • frame (int, optional) – The frame to plot. Defaults to 0.

  • threshold (float, optional) – Binarization threshold to use for cell mask. Defaults to 0.5.

  • cmap (matplotlib.colors.Colormap, optional) – The colormap to use. Defaults to ‘gray’

  • alpha (float, optional) – Transparency value to change opacity of mask. Defaults to 0.5.

  • scalebar (bool, optional) – Whether to add a scalebar to the plot. Defaults to True.

  • title (str, optional) – The title for the plot. Defaults to None.

static plot_z_segmentation(ax: matplotlib.axes.Axes, sarc_obj: sarcasm.structure.Structure, frame=0, scalebar=True, shuffle=True, title=None, zoom_region: Tuple[int, int, int, int] = None, inset_bounds=(0.6, 0.6, 0.4, 0.4))[source]

Plots the Z-band segmentation result of the sarcomere object.

Parameters:
  • ax (matplotlib.axes.Axes) – The axes to draw the plot on.

  • sarc_obj (Structure) – The instance of Structure class to plot.

  • frame (int, optional) – The frame to plot. Defaults to 0.

  • scalebar (bool, optional) – Whether to add a scalebar to the plot. Defaults to True.

  • shuffle (bool, optional) – Whether to shuffle the labels. Defaults to True.

  • title (str, optional) – The title for the plot. Defaults to None.

  • zoom_region (tuple of int, optional) – The region to zoom in on, specified as (x1, x2, y1, y2). Defaults to None.

  • inset_bounds (tuple of float, optional) – Bounds of inset axis, specified as (x0, y0, width, height). Defaults to (0.6, 0.6, 0.4, 0.4).

static plot_z_lateral_connections(ax: matplotlib.axes.Axes, sarc_obj: sarcasm.structure.Structure, frame=0, scalebar=True, markersize=1.5, markersize_inset=3, linewidth=0.25, linewidth_inset=0.5, plot_groups=True, shuffle=True, title=None, zoom_region: Tuple[int, int, int, int] = None, inset_bounds=(0.6, 0.6, 0.4, 0.4))[source]

Plots lateral Z-band connections of a Structure object.

Parameters:
  • ax (matplotlib.axes.Axes) – The axes to draw the plot on.

  • sarc_obj (Structure) – The instance of Structure object to plot.

  • frame (int, optional) – The frame to plot. Defaults to 0.

  • scalebar (bool, optional) – Whether to add a scalebar to the plot. Defaults to True.

  • markersize (int, optional) – The size of the markers of the Z-band ends. Defaults to 5.

  • markersize_inset (int, optional) – The size of the markers of the Z-band ends in the inset plot. Defaults to 5.

  • linewidth (int, optional) – The width of the connection lines. Defaults to 0.25.

  • linewidth – The width of the connection lines in the inset plot. Defaults to 0.5.

  • plot_groups (bool) – Whether to show the Z-bands of each lateral group with the same color. Defaults to True.

  • shuffle (bool, optional) – Whether to shuffle the labels. Defaults to True.

  • title (str, optional) – The title for the plot. Defaults to None.

  • zoom_region (tuple of int, optional) – The region to zoom in on, specified as (x1, x2, y1, y2). Defaults to None.

  • inset_bounds (tuple of float, optional) – Bounds of inset axis, specified as (x0, y0, width, height). Defaults to (0.6, 0.6, 0.4, 0.4).

static plot_sarcomere_orientation_field(ax1: matplotlib.axes.Axes, ax2: matplotlib.axes.Axes, sarc_obj: sarcasm.structure.Structure, frame=0, cmap='vanimo', scalebar=True, colorbar=True, shrink_colorbar=0.7, orient_colorbar='vertical', zoom_region: Tuple[int, int, int, int] = None, inset_bounds=(0.6, 0.6, 0.4, 0.4))[source]

Plots sarcomere orientation field of the sarcomere object.

Parameters:
  • ax1 (matplotlib.axes.Axes) – The axes to draw the plot on.

  • sarc_obj (object) – The instance of Structure class to plot.

  • frame (int, optional) – The frame to plot. Defaults to 0.

  • scalebar (bool, optional) – Whether to add a scalebar to the plot. Defaults to True.

  • colorbar (bool, optional) – Whether to add a colorbar to the plot. Defaults to True.

  • shrink_colorbar (float, optional) – The factor by which to shrink the colorbar. Defaults to 0.7.

  • orient_colorbar (str, optional) – The orientation of the colorbar (‘horizontal’ or ‘vertical’). Defaults to ‘vertical’.

  • zoom_region (tuple of int, optional) – The region to zoom in on, specified as (x1, x2, y1, y2). Defaults to None.

  • inset_bounds (tuple of float, optional) – Bounds of inset axis, specified as (x0, y0, width, height). Defaults to (0.6, 0.6, 0.4, 0.4).

static plot_sarcomere_mask(ax: matplotlib.axes.Axes, sarc_obj: sarcasm.structure.Structure, frame=0, cmap='viridis', threshold=0.1, show_z_bands=False, alpha=0.5, cmap_z_bands='gray', alpha_z_bands=1, clip_thrs=(1, 99.9), title=None, zoom_region: Tuple[int, int, int, int] = None, inset_bounds=(0.6, 0.6, 0.4, 0.4))[source]

Plots binary mask of sarcomeres, derived from sarcomere vectors.

Parameters:
  • ax (matplotlib.axes.Axes) – The axes to draw the plot on.

  • sarc_obj (Structure) – The instance of Structure class to plot.

  • frame (int, optional) – The frame to plot. Defaults to 0.

  • cmap (str, optional) – The colormap to use. Defaults to ‘viridis’

  • show_z_bands (bool, optional) – Whether to show Z-bands. If False, the raw image is shown. Defaults to False.

  • alpha (float, optional) – The transparency of sarcomere mask. Defaults to 0.5.

  • cmap_z_bands (bool, optional) – Colormap for Z-bands. Defaults to ‘gray’.

  • alpha_z_bands (float, optional) – Alpha value of Z-bands. Defaults to 1.

  • clip_thrs (tuple of float, optional) – Clipping threshold for image in background. Defaults to (1, 99.9). Only if show_z_bands is False.

  • title (str, optional) – The title for the plot. Defaults to None.

  • zoom_region (tuple of int, optional) – The region to zoom in on, specified as (x1, x2, y1, y2). Defaults to None.

  • inset_bounds (tuple of float, optional) – Bounds of inset axis, specified as (x0, y0, width, height). Defaults to (0.6, 0.6, 0.4, 0.4).

static plot_sarcomere_vectors(ax: matplotlib.axes.Axes, sarc_obj: sarcasm.structure.Structure, frame=0, color_arrows='k', color_points='darkgreen', s_points=0.5, linewidths=0.5, s_points_inset=0.5, linewidths_inset=0.5, scalebar=True, legend=False, show_image=False, cmap_z_bands='Purples', alpha_z_bands=1, title=None, zoom_region: Tuple[int, int, int, int] = None, inset_bounds=(0.6, 0.6, 0.4, 0.4))[source]

Plots quiver plot reflecting local sarcomere length and orientation based on sarcomere vector analysis result of the sarcomere object.

Parameters:
  • ax (matplotlib.axes.Axes) – The axes to draw the plot on.

  • sarc_obj (Structure) – The instance of Structure class to plot.

  • frame (int, optional) – The frame to plot. Defaults to 0.

  • color_arrows (str, optional) – The color of the arrows. Defaults to ‘mediumpurple’.

  • color_points (str, optional) – The color of the points. Defaults to ‘darkgreen’.

  • s_points (float, optional) – The size of midline points. Defaults to 0.5.

  • linewidths (float, optional) – The width of the arrow lines. Defaults to 0.0005.

  • s_points_inset (float, optional) – The size of midline points. Defaults to 0.5.

  • linewidths_inset (float, optional) – The width of the arrow lines in the inset plot. Defaults to 0.0001.

  • scalebar (bool, optional) – Whether to add a scalebar to the plot. Defaults to True.

  • legend (bool, optional) – Whether to add a legend to the plot. Defaults to False.

  • show_image (bool, optional) – Whether to show the image (True) or the Z-bands (False). Defaults to False.

  • cmap_z_bands (str, optional) – Colormap of Z-bands. Defaults to ‘Greys’.

  • alpha_z_bands (float, optional) – Alpha value of Z-bands. Defaults to 1.

  • title (str, optional) – The title for the plot. Defaults to None.

  • zoom_region (tuple of int, optional) – The region to zoom in on, specified as (x1, x2, y1, y2). Defaults to None.

  • inset_bounds (tuple of float, optional) – Bounds of inset axis, specified as (x0, y0, width, height). Defaults to (0.6, 0.6, 0.4, 0.4).

static plot_sarcomere_domains(ax: matplotlib.axes.Axes, sarc_obj: sarcasm.structure.Structure, frame=0, alpha=0.5, cmap='gist_rainbow', scalebar=True, plot_raw_data=False, cmap_z_bands='Greys', alpha_z_bands=1, title=None)[source]

Plots the sarcomere domains of the sarcomere object.

Parameters:
  • ax (matplotlib.axes.Axes) – The axes to draw the plot on.

  • sarc_obj (Structure) – The instance of Structure class to plot.

  • frame (int, optional) – The frame to plot. Defaults to 0.

  • alpha (float, optional) – The transparency of the domain masks. Defaults to 0.3.

  • cmap (str, optional) – The colormap to use. Defaults to ‘gist_rainbow’.

  • scalebar (bool, optional) – Whether to add a scalebar to the plot. Defaults to True.

  • plot_raw_data (bool, optional) – Whether to plot the raw data. Defaults to False.

  • cmap_z_bands (str, optional) – Colormap for Z-bands. Defaults to ‘Greys’.

  • alpha_z_bands (float, optional) – Transparency of Z-bands. Defaults to 1.

  • title (str, optional) – The title for the plot. Defaults to None.

static plot_myofibril_lines(ax: matplotlib.axes.Axes, sarc_obj: sarcasm.structure.Structure, frame=0, show_z_bands=True, linewidth=1, color_lines='r', linewidth_inset=3, alpha=0.2, cmap_z_bands='Greys', alpha_z_bands=1, scalebar=True, title=None, zoom_region=None, inset_bounds=(0.6, 0.6, 0.4, 0.4))[source]

Plots result of myofibril line growth algorithm of the sarcomere object.

Parameters:
  • ax (matplotlib.axes.Axes) – The axes to draw the plot on.

  • sarc_obj (Structure or Motion) – The sarcomere object to plot.

  • frame (int, optional) – The frame to plot. Defaults to 0.

  • show_z_bands (bool) – Whether or not to show Z-bands. Defaults to True

  • linewidth (float, optional) – The width of the lines. Defaults to 1.

  • color_lines (str) – Color of lines. Defaults to ‘r’

  • linewidth_inset (float, optional) – Thickness of the lines in inset. Defaults to 1.

  • alpha (float, optional) – The transparency of the lines. Defaults to 0.2.

  • cmap_z_bands (str, optional) – Colormap of Z-bands. Defaults to ‘Greys’.

  • alpha_z_bands (float, optional) – Transparency of Z-bands. Defaults to 1.

  • scalebar (bool, optional) – Whether to add a scalebar to the plot. Defaults to True.

  • title (str, optional) – The titlefor the plot. Defaults to None.

  • zoom_region (tuple of int, optional) – The region to zoom in on, specified as (x1, x2, y1, y2). Defaults to None.

  • inset_bounds (tuple of float, optional) – Bounds of inset axis, specified as (x0, y0, width, height). Defaults to (0.6, 0.6, 0.4, 0.4).

static plot_myofibril_length_map(ax: matplotlib.axes.Axes, sarc_obj: sarcasm.structure.Structure, frame=0, vmax=None, alpha=1, show_z_bands=False, cmap_z_bands='Greys', alpha_z_bands=1, colorbar=True, shrink_colorbar=0.7, orient_colorbar='vertical', scalebar=True, title=None, zoom_region: Tuple[int, int, int, int] = None, inset_bounds=(0.6, 0.6, 0.4, 0.4))[source]

Plots the spatial map of myofibril lengths for a given frame.

Parameters:
  • ax (matplotlib.axes.Axes) – The axes to draw the plot on.

  • sarc_obj (Structure) – The instance of Structure class to plot.

  • frame (int, optional) – The frame to plot. Defaults to 0.

  • vmax (float, optional) – Maximum value for the colormap. If None, the maximum value in the data is used. Defaults to None.

  • alpha (float, optional) – Transparency of the colormap. Defaults to 1.

  • show_z_bands (bool, optional) – Whether to show Z-band mask, else raw image is shown. Defaults to False.

  • cmap_z_bands (str, optional) – Colormap of Z-bands. Defaults to ‘Greys’.

  • alpha_z_bands (float, optional) – Transparency of Z-bands or raw image. Defaults to 1.

  • colorbar (bool, optional) – Whether to show the colorbar. Defaults to True.

  • shrink_colorbar (float, optional) – Shrinkage of the colorbar. Defaults to 0.7.

  • orient_colorbar (str, optional) – Orientation of the colorbar. Defaults to ‘vertical’.

  • scalebar (bool, optional) – Whether to add a scalebar to the plot. Defaults to True.

  • title (str, optional) – The title for the plot. Defaults to None.

  • zoom_region (tuple of int, optional) – The region to zoom in on, specified as (x1, x2, y1, y2). Defaults to None.

  • inset_bounds (tuple of float, optional) – Bounds of inset axis, specified as (x0, y0, width, height). Defaults to (0.6, 0.6, 0.4, 0.4).

static plot_lois(ax: matplotlib.axes.Axes, sarc_obj: sarcasm.structure.Structure | sarcasm.motion.Motion, color='darkorange', linewidth=2, alpha=0.5)[source]

Plot all LOI lines for Structure object and LOI line Motion object.

Parameters:
  • ax (matplotlib axis) – Axis on which to plot the LOI lines

  • sarc_obj (Structure or Motion) – Object of Structure or Motion class

  • color (str) – Color of lines

  • linewidth (float) – Width of lines

  • alpha (float) – Transparency of lines

static plot_histogram_structure(ax: matplotlib.axes.Axes, sarc_obj: sarcasm.structure.Structure, feature: str, frame: int = 0, bins: int = 20, density: bool = False, range: tuple | None = None, label: str | None = None, ylabel: str | None = None, rwidth: float = 0.6, color: str = 'darkslategray', edge_color: str = 'k', align: Literal['mid', 'left', 'right'] = 'mid', rotate_yticks: bool = False) None[source]

Plots the histogram of a specified structural feature from a sarcomere object on a given Axes.

Parameters:
  • ax (matplotlib.axes.Axes) – The axes on which to draw the histogram.

  • sarc_obj (Structure) – The instance of Structure class to plot.

  • feature (str) – The name of the structural feature to plot.

  • frame (int, optional) – The frame index from which to extract the data. Defaults to 0.

  • bins (int, optional) – The number of bins for the histogram. Defaults to 20.

  • density (bool, optional) – If True, the histogram is normalized to show the probability density rather than raw counts. Defaults to False.

  • range (tuple, optional) – The lower and upper range of the bins. If not provided, the range is determined from the data.

  • label (str, optional) – The label for the x-axis. If not specified, a default label based on the feature will be used.

  • ylabel (str, optional) – The label for the y-axis. Overrides the default label if provided.

  • rwidth (float, optional) – The relative width of the histogram bars. Defaults to 0.7.

  • color (str, optional) – The fill color of the histogram bars. Defaults to ‘darkslategray’.

  • edge_color (str, optional) – The color of the edges of the histogram bars. Defaults to ‘k’.

  • align (str, optional) – The alignment of the histogram bars. Defaults to ‘mid’.

  • rotate_yticks (bool, optional) – If True, rotates the y-axis tick labels by 90 degrees for improved readability. Defaults to False.

static plot_z_pos(ax: matplotlib.axes.Axes, motion_obj: sarcasm.motion.Motion, number_contr=None, show_contr=True, show_kymograph=False, color='k', t_lim=(None, None), y_lim=(None, None))[source]

Plots the z-band trajectories of the motion object.

Parameters:
  • ax (matplotlib.axes.Axes) – The axes to draw the plot on.

  • motion_obj (Motion) – The motion object to plot.

  • show_contr (bool, optional) – Whether to show the contractions. Defaults to True.

  • show_kymograph (bool, optional) – Whether to show the kymograph. Defaults to False.

  • color (str, optional) – The color of the plot. Defaults to ‘k’.

  • t_lim (tuple, optional) – The time limits for the plot. Defaults to (None, None).

  • y_lim (tuple, optional) – The y limits for the plot. Defaults to (None, None).

static plot_delta_slen(ax: matplotlib.axes.Axes, motion_obj: sarcasm.motion.Motion, frame=None, t_lim=(0, 12), y_lim=(-0.3, 0.4), n_rows=6, n_start=1, show_contr=True)[source]

Plots the change in sarcomere length over time for a motion object.

Parameters:
  • ax (matplotlib.axes.Axes) – The axes to draw the plot on.

  • motion_obj (Motion) – The motion object to plot.

  • frame (int or None, optional) – Show frame with vertical dashed line, in frames. Defaults to None.

  • t_lim (tuple, optional) – The time limits for the plot. Defaults to (0, 12).

  • y_lim (tuple, optional) – The y limits for the plot. Defaults to (-0.3, 0.4).

  • n_rows (int, optional) – The number of rows for the plot. Defaults to 6.

  • n_start (int, optional) – The starting index for the plot. Defaults to 1.

  • show_contr (bool, optional) – Whether to show the systoles. Defaults to True.

static plot_overlay_delta_slen(ax: matplotlib.axes.Axes, motion_obj: sarcasm.motion.Motion, number_contr=None, t_lim=(0, 1), y_lim=(-0.35, 0.5), show_contr=True)[source]

Plots the sarcomere length change over time for a motion object, overlaying multiple trajectories.

Parameters:
  • ax (matplotlib.axes.Axes) – The axes to draw the plot on.

  • motion_obj (Motion) – The motion object to plot.

  • number_contr (int, optional) – The number of contractions to overlay. If None, all contractions are overlaid. Defaults to None.

  • t_lim (tuple, optional) – The time limits for the plot. Defaults to (0, 1).

  • y_lim (tuple, optional) – The y limits for the plot. Defaults to (-0.35, 0.45).

  • show_contr (bool, optional) – Whether to show the contractions. Defaults to True.

static plot_overlay_velocity(ax, motion_obj: sarcasm.motion.Motion, number_contr=None, t_lim=(0, 0.9), y_lim=(-9, 12), show_contr=True)[source]

Plots overlay of sarcomere velocity time series of the motion object

Parameters:
  • ax (matplotlib.axes.Axes) – The axes to draw the plot on.

  • motion_obj (Motion) – The motion object to plot.

  • number_contr (int, optional) – The number of contractions to overlay. If None, all contractions are overlaid. Defaults to None.

  • t_lim (tuple, optional) – The time limits for the plot. Defaults to (0, 0.9).

  • y_lim (tuple, optional) – The y limits for the plot. Defaults to (-7, 10).

  • show_contr (bool, optional) – Whether to show the contractions. Defaults to True.

static plot_phase_space(ax: matplotlib.axes.Axes, motion_obj: sarcasm.motion.Motion, t_lim=(0, 4), number_contr=None, frame=None)[source]

Plots sarcomere trajectory in length-change velocity phase space

Parameters:
  • ax (matplotlib.axes.Axes) – The axes to draw the plot on.

  • motion_obj (Motion) – The motion object to plot.

  • t_lim (tuple, optional) – The time limits for the plot. Defaults to (0, 4).

  • number_contr (int, optional) – The number of contractions to overlay. If None, all contractions are overlaid. Defaults to None.

  • frame (int, optional) – The frame number to plot the individual sarcomeres in phase space. Defaults to None.

static plot_popping_events(motion_obj: sarcasm.motion.Motion, save_name=None)[source]

Create binary event map of popping events of the motion object.

Parameters:
  • motion_obj (Motion) – The motion object to plot.

  • save_name (str, optional) – The name to save the plot as. If None, the plot is not saved. Defaults to None.

class sarcasm.PlotUtils[source]

Helper function and parameters for plotting

fontsize = 8
markersize = 3
labelpad = 1
dpi = 600
save_format = 'png'
width_1cols = 3.5
width_1p5cols = 5
width_2cols = 7.1
static label_all_panels(axs: dict, offset=(-0.1, 1.1), color='k')[source]

Labels all panels in a given dictionary of Axes objects.

Parameters:
  • axs (dict) – A dictionary of Axes objects.

  • offset (tuple, optional) – The x and y offset for the labels. Defaults to (-0.1, 1.1).

  • color (str, optional) – The color of the labels. Defaults to ‘k’ (black).

static label_panel(ax: matplotlib.axes.Axes, label: str, offset=(-0.1, 1.1), color='k')[source]

Labels a single panel with the specified label.

Parameters:
  • ax (matplotlib.axes.Axes) – The Axes object representing the panel to be labeled.

  • label (str) – The label to be displayed.

  • offset (tuple, optional) – The x and y offset for the label. Defaults to (-0.1, 1.1).

  • color (str, optional) – The color of the label. Defaults to ‘k’ (black).

static remove_all_spines(axs: dict)[source]

Removes the spines from all panels in a given dictionary of Axes objects.

Parameters:

axs (dict) – A dictionary of Axes objects.

static remove_spines(ax)[source]

Removes the spines from a single panel.

Parameters:

ax (matplotlib.axes.Axes) – The Axes object representing the panel.

static change_color_spines(ax, c='w', linewidth=1)[source]

Changes the color of the spines (borders) of a single panel.

Parameters:
  • ax (matplotlib.axes.Axes) – The Axes object representing the panel.

  • c (str, optional) – The color of the spines. Defaults to ‘w’ (white).

static remove_ticks(ax)[source]

Removes the ticks (markings) from both x-axis and y-axis of a single panel.

Parameters:

ax (matplotlib.axes.Axes) – The Axes object representing the panel.

static polish_xticks(ax, major, minor, pad=3, radian=False)[source]

Formats and polishes the x-ticks (markings) of a single panel.

Parameters:
  • ax (matplotlib.axes.Axes) – The Axes object representing the panel.

  • major (float) – The major tick spacing.

  • minor (float) – The minor tick spacing.

  • pad (float, optional) – The padding between the x-axis and the tick labels. Defaults to 3.

  • radian (bool, optional) – Flag to format ticks in radians. Defaults to False.

static polish_yticks(ax, major, minor, pad=3)[source]

Formats and polishes the y-ticks (markings) of a single panel.

Parameters:
  • ax (matplotlib.axes.Axes) – The Axes object representing the panel.

  • major (float) – The major tick spacing.

  • minor (float) – The minor tick spacing.

  • pad (float, optional) – The padding between the y-axis and the tick labels. Defaults to 3.

static plot_box(ax, xlim, ylim, c='w', lw=1, linestyle='-')[source]

Plots a box around a given area defined by the x-axis and y-axis limits.

Parameters:
  • ax (matplotlib.axes.Axes) – The Axes object representing the panel.

  • xlim (tuple) – The x-axis limits of the box.

  • ylim (tuple) – The y-axis limits of the box.

  • c (str, optional) – The color of the box. Defaults to ‘w’ (white).

  • lw (float, optional) – The linewidth of the box. Defaults to 1.

  • linestyle (str, optional) – The linestyle of the box. Defaults to ‘-’ (solid line).

static jitter(x, y, width=0.02)[source]

Adds a small amount of random noise to the x-coordinates of the points to prevent overlap.

Parameters:
  • x (array-like) – The x-coordinates of the points.

  • y (array-like) – The y-coordinates of the points.

  • width (float, optional) – The maximum width of the random noise. Defaults to 0.02.

Returns:

The jittered x-coordinates of the points.

Return type:

array-like

boxplot_with_points(data, labels, width=0.1, alpha=0.5, s=10, whis=(5, 95), rotation=90)[source]

Creates a boxplot with scattered points.

Parameters:
  • ax (matplotlib.axes.Axes) – The axes to draw the plot on.

  • data (array-like) – The data to plot.

  • labels (list of str) – The labels for the boxplots.

  • width (float, optional) – The width of the boxplots. Defaults to 1.25.

  • alpha (float, optional) – The alpha value for the points. Defaults to 0.005.

  • s (int, optional) – The size of the points. Defaults to 10.

  • whis (tuple of float, optional) – The whisker range for the boxplots. Defaults to (5, 95).

  • rotation (int, optional) – The rotation angle for the x-axis labels. Defaults to 90.

Return type:

None

static plot_func_to_img(sarc_obj: sarcasm.SarcAsM | sarcasm.Motion, plot_func, img_filename, figsize=(6, 6), scalebar=False, dpi=300)[source]

Generates a plot using a specified plotting function and saves it as an image file.

Parameters:
  • sarc_obj (object) – The object containing data to be plotted, which can be an instance of SarcAsM or Motion

  • plot_func (function) – The plotting function that takes an Axes object, a sarcomere object, and a boolean indicating whether to include a scalebar. It should plot the data onto the provided Axes object.

  • img_filename (str) – The filename (including path) where the image will be saved.

  • figsize (tuple of int or float, optional) – The size of the figure (width, height) in inches. Default is (6, 6).

  • scalebar (bool, optional) – Indicates whether a scalebar should be included in the plot. Default is False.

  • dpi (int, optional) – Quality of the plot. Default is 300.

class sarcasm.MultiStructureAnalysis(list_files: list, folder: str, experiment: str = None, load_data: bool = False, **conditions)[source]

Class for multi-tif-file comparison of structure.

Parameters:
  • list_files (list) – List of tif files.

  • folder (str) – Path to a folder to store data and results.

  • experiment (str, optional) – Name of the experiment (default is None).

  • load_data (bool, optional) – Whether to load the dataframe from previous analysis from the data folder (default is False).

  • **conditions (dict) – Keyword arguments with regex functions to extract information from the filename.

folder

Path to the folder with data and results.

Type:

str

experiment

Name of the experiment.

Type:

str

files

List of tif files.

Type:

list

conditions

Keyword arguments with regex functions to extract information from the filename.

Type:

dict

data

DataFrame to store the structure data.

Type:

pandas.DataFrame

folder
experiment = None
files
conditions
data = None
get_data(structure_keys=None, meta_keys=None)[source]

Iterate files and get structure data.

Parameters:
  • structure_keys (list, optional) – List of keys to extract structure data (default is None).

  • meta_keys (list, optional) – List of keys to extract metadata (default is None).

Return type:

None

save_data()[source]

Save the DataFrame to the data folder.

Return type:

None

load_data()[source]

Load the DataFrame from the data folder.

Return type:

None

Raises:

FileExistsError – If the data file does not exist in the specified folder.

export_data(filepath, format='.xlsx')[source]

Export the DataFrame to .xlsx or .csv format.

Parameters:
  • filepath (str) – Path to the output file.

  • format (str, optional) – Format of the output file (‘.xlsx’ or ‘.csv’) (default is ‘.xlsx’).

Return type:

None

class sarcasm.MultiLOIAnalysis(list_lois, folder, load_data=False, **conditions)[source]

Class for multi-LOI comparison.

Parameters:
  • list_lois (list) – List of tuples containing tif file paths and LOI names.

  • folder (str) – Path to a folder to store data and results.

  • load_data (bool, optional) – Whether to load the dataframe from previous analysis from the folder (default is False).

  • **conditions (dict) – Keyword arguments with regex functions to extract information from the filename.

folder

Path to the folder with data and results.

Type:

str

lois

List of tuples containing tif file paths and LOI names.

Type:

list

conditions

Keyword arguments with regex functions to extract information from the filename.

Type:

dict

data

DataFrame to store the motion data.

Type:

pandas.DataFrame

folder
lois
conditions
data = None
get_data(loi_keys=None, meta_keys=None)[source]

Iterate files and get motion data.

Parameters:
  • loi_keys (list, optional) – List of keys to extract motion data (default is None).

  • meta_keys (list, optional) – List of keys to extract metadata (default is None).

Return type:

None

save_data()[source]

Save the DataFrame to the data folder as a pandas DataFrame.

Return type:

None

load_data()[source]

Load the DataFrame from the data folder.

Return type:

None

Raises:

FileExistsError – If the data file does not exist in the specified folder.

export_data(filepath, format='.xlsx')[source]

Export the DataFrame to .xlsx or .csv format.

Parameters:
  • filepath (str) – Path to the output file.

  • format (str, optional) – Format of the output file (‘.xlsx’ or ‘.csv’) (default is ‘.xlsx’).

Return type:

None