sarcasm
Submodules
Attributes
Classes
Base class for sarcomere structural and functional analysis. |
|
Class for analyzing sarcomere morphology. |
|
Class for tracking and analysis of sarcomere motion at line of interest LOI |
|
Miscellaneous utility functions |
|
Utility functions for storing and loading IO data. |
|
Class with plotting functions for Structure and Motion objects |
|
Helper function and parameters for plotting |
|
Class for multi-tif-file comparison of structure. |
|
Class for multi-LOI comparison. |
Package Contents
- sarcasm.__version__
- class sarcasm.SarcAsM(file_path: str | os.PathLike, restart: bool = False, pixelsize: float | None = None, frametime: float | None = None, channel: int | None = None, axes: str | None = None, auto_save: bool = True, use_gui: bool = False, device: torch.device | Literal['auto', 'mps', 'cuda', 'cpu'] = 'auto', log_level: str | int = 'INFO', **info: Dict[str, Any])[source]
Base class for sarcomere structural and functional analysis.
- Parameters:
file_path (str | os.PathLike) – Path to the TIFF file for analysis.
restart (bool, optional) – If True, deletes existing analysis and starts fresh (default: False).
pixelsize (float or None, optional) – Physical pixel size in micrometres (µm). If None, the class tries to extract it from file metadata; otherwise it must be provided manually.
frametime (float or None, optional) – Time between frames in seconds. If None, the class tries to extract it from file metadata; otherwise it must be provided manually.
channel (int or None, optional) – Channel index that contains the sarcomere signal in multicolour stacks (default: None).
axes (str or None, optional) – Explicit order of image dimensions (e.g.
'TXYC'or'YX'). If None, the order is auto-detected from OME-XML, ImageJ tags or shape heuristics; this is the recommended mode when the GUI offers a drop-down override.auto_save (bool, optional) – Automatically save analysis results when True (default: True).
use_gui (bool, optional) – Enable GUI-mode behaviour (default: False).
device (Union[torch.device, Literal['auto']], optional) – PyTorch computation device.
'auto'selects CUDA/MPS if available (default: ‘auto’).log_level (str or int, optional) – Logging level for the sarcasm package. Can be a string (‘DEBUG’, ‘INFO’, ‘WARNING’, ‘ERROR’, ‘CRITICAL’) or an integer (logging.DEBUG, logging.INFO, etc.). Default is ‘INFO’. Use ‘DEBUG’ for verbose output or ‘WARNING’ to suppress info messages.
**info (Any) – Additional user-supplied metadata key-value pairs (e.g.
cell_line='wt').
- file_path
Absolute path to the input TIFF file.
- Type:
str
- base_dir
Base directory for all analysis artefacts of this TIFF.
- Type:
str
- data_dir
Sub-directory for intermediate data.
- Type:
str
- analysis_dir
Sub-directory for final analysis results.
- Type:
str
- metadata
Image metadata
- Type:
- device
PyTorch device on which computations are performed.
- Type:
torch.device
- Dynamic Attributes (loaded on demand)
- -------------------------------------
- zbands
Binary Z-band mask.
- Type:
ndarray
- zbands_fast_movie
Binary Z-band mask for the high-temporal-resolution movie.
- Type:
ndarray
- mbands
Binary 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
- file_path = b'.'
- auto_save = True
- 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
- metadata
- meta_file
- model_dir
- _setup_logging(log_level: str | int) None[source]
Configure logging for the sarcasm package and all its submodules.
This method sets up a console handler for the ‘sarcasm’ logger. If the GUI has already attached a handler (e.g., QTextEditHandler), it will be preserved.
- Parameters:
log_level (str or int) – Logging level. Can be a string (‘DEBUG’, ‘INFO’, ‘WARNING’, ‘ERROR’, ‘CRITICAL’) or an integer (logging.DEBUG=10, logging.INFO=20, etc.).
Examples
>>> sarc = Structure(file_path, log_level='DEBUG') # Verbose output >>> sarc = Structure(file_path, log_level=logging.WARNING) # Only warnings and errors
- _extract_metadata_only(axes: str | None = None) None[source]
Extract metadata from the TIFF file without loading the full image data.
This method is optimized for large files (e.g., 15+ GB) on slow storage (HDD), as it only reads the file headers and metadata, not the pixel data.
- Parameters:
axes (str, optional) – Dimension order override (e.g., ‘TXYC’). Auto-detected if None.
- read_imgs(frames=None, axes=None)[source]
Load and process TIFF data with metadata extraction.
- Parameters:
frames (int, list, slice, or None, optional) – Frame selection for stacks. None loads all frames (default).
axes (str, optional) – Dimension order override (e.g., ‘TXYC’). Auto-detected if None.
- Returns:
Image data in internal format: (Y, X) or (Stack, Y, X).
- Return type:
np.ndarray
- static _determine_axes(series, tif: tifffile.TiffFile) str[source]
Return an upper-case axis string such as ‘TCZYX’, ‘YXC’, ‘YX’, …
- Raises:
ValueError – if no reasonable guess is possible and the caller must supply the order manually.
- _select_channel(data: numpy.ndarray, axes: str) tuple[numpy.ndarray, str][source]
Isolate the channel requested by
self.channeland remove the channel axis from the array.- Parameters:
data – Numpy array as it was read from disk (still in source order).
axes – Corresponding axis string (upper-case, e.g.
'TYXC').
- Returns:
data_sel (np.ndarray) – Array with the channel axis removed.
axes_sel (str) – Axis string without the
'C'character.
- Raises:
ValueError –
if the requested channel index is out of range
if
self.metadata.channelis given but the image has noCaxis
- _harvest_metadata(series, tif, axes) sarcasm.meta_data_handler.ImageMetadata[source]
Collect metadata from tif and update the instance metadata object.
- static _validate_axes(axes: str) None[source]
Raise if axes is not a unique subset of {X, Y, T, C, Z}.
- class sarcasm.Structure(file_path: str | os.PathLike, restart: bool = False, pixelsize: float | None = None, frametime: float | None = None, channel: int | None = None, axes: str | None = None, auto_save: bool = True, use_gui: bool = False, device: torch.device | Literal['auto'] = 'auto', **info: Any)[source]
Bases:
sarcasm.core.SarcAsMClass for analyzing sarcomere morphology.
- Parameters:
file_path (str | os.PathLike) – Path to the image tif file.
restart (bool, optional) – If
Truethe previous analysis folder is deleted and a fresh run is started (default:False).pixelsize (float or None, optional) – Physical pixel size in µm. If
Nonethe value is taken from file metadata; otherwise the supplied number overrides all metadata.frametime (float or None, optional) – Time between frames in s. If
Noneit is taken from metadata; an explicit number overrides it.channel (int | None, optional) – Index of the fluorescence channel that shows the sarcomeres. If the image has only one channel this argument is ignored.
axes (str | None, optional) – Explicit dimension order (e.g.
'TXYC').Nonelets the base class auto-detect the order.auto_save (bool, optional) – Write analysis results to disk automatically (default
True).use_gui (bool, optional) – Activate GUI mode (default
False).device (torch.device | Literal['auto'], optional) – Device on which PyTorch kernels are executed.
'auto'selects CUDA or MPS when available (default'auto').**info (Any) – Additional key-value pairs that are stored in the metadata file.
- data
Dictionary that contains numeric results of the morphology analysis (populated after running the respective detection routines).
- 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
- 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.
- 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), rescale_factor: float = 1.0, 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).
rescale_factor (float, optional) – Factor by which to rescale the input images in the XY dimensions before prediction. For example, 0.5 reduces the XY resolution by half. The images and all subsequent outputs will be rescaled back to their original resolution after prediction. Default is 1.0 (no rescaling).
progress_notifier (ProgressNotifier, optional) – Progress notifier for inclusion in GUI. Default is ProgressNotifier.progress_notifier_tqdm().
- Return type:
None
- _remap_mask_key(list_frames: List[int], detected_frames: Any) int | List[int][source]
Translate movie-frame indices to page indices inside a sparsely-saved mask TIFF.
Masks are stored only for frames passed to detect_sarcomeres, in detection order. When detected_frames covers every frame this is an identity mapping, so we just return the original indices; otherwise we look up each requested frame’s position.
- load_mask_full_stack(file_path: str) numpy.ndarray | None[source]
Load a mask TIFF and expand it to full stack length in memory for display.
Masks are saved sparsely (only for detected frames) to save disk space. For napari display alongside the raw movie, this returns an (n_stack, …) array with computed frames placed at their original frame indices and zeros elsewhere. Returns None if the file does not exist.
- 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.4.
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 3.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.0.
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.25, 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, interpolation_method: str = 'akima', 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.
interpolation_method (str, optional) – Interpolation method for profile analysis: ‘linear’ (fast) or ‘akima’ (smooth). Defaults to ‘akima’.
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, store_mask: bool = False, 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.
store_mask (bool, optional) – If True, store the domain mask (integer-labeled image with domain IDs) in self.data. Can be memory-intensive for large time-series. Defaults to False.
progress_notifier (ProgressNotifier) – Wraps progress notification, default is progress notification done with tqdm
- analyze_domain_motion(reference_frame: int = 0, model: str | None = None, threshold: float = 0.3, contr_time_min: float = 0.2, merge_time_max: float = 0.05, buffer_frames: int = 3, min_valid_frames: float = 0.5, filter_params: Tuple[int, int] = (13, 5), progress_notifier: bio_image_unet.progress.ProgressNotifier = ProgressNotifier.progress_notifier_tqdm()) None[source]
Analyze sarcomere contraction dynamics within sarcomere domains over time.
Uses domain masks from a reference frame to track mean sarcomere length within each domain across all frames. Then detects contraction cycles using ContractionNet and computes per-domain contraction parameters.
Prerequisites: Run analyze_sarcomere_vectors and analyze_sarcomere_domains first.
- Parameters:
reference_frame (int, optional) – Frame index to use as reference for domain masks. Must be a frame where domains were analyzed. Defaults to 0.
model (str, optional) – Path to ContractionNet model weights (.pt file). If None, uses default model.
threshold (float, optional) – Binary threshold for contraction state prediction. Default 0.3.
contr_time_min (float, optional) – Minimal time of contraction in seconds. Shorter contractions are removed. Default 0.2.
merge_time_max (float, optional) – Maximal time between two contractions. Closer contractions are merged. Default 0.05.
buffer_frames (int, optional) – Remove contraction cycles within this many frames of start/end of time-series. Default 3.
min_valid_frames (float, optional) – Minimum fraction of valid (non-NaN) frames required for a domain to be analyzed. Default 0.5.
filter_params (Tuple[int, int], optional) – Savitzky-Golay filter parameters (window_length, polyorder) for velocity calculation. Default (13, 5).
progress_notifier (ProgressNotifier, optional) – Progress notification wrapper. Default uses tqdm.
- Raises:
ValueError – If prerequisites are not met or if reference_frame is invalid.
- _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.
- 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
- class sarcasm.Motion(file_path: str, loi_name: str, restart: bool = False, auto_save: bool = True)[source]
Bases:
sarcasm.core.SarcAsMClass for tracking and analysis of sarcomere motion at line of interest LOI
- loi_data
- loi_file
- loi_name
- loi_folder
- auto_save = True
- __load_analysed_data_or_create(restart: bool)
- __create_loi_data()
- __get_loi_data_file_name(is_temp_file=False) str
- detekt_peaks(thres: float = 0.2, min_dist: float = 1.4, width: int = 0.5)[source]
Detect peaks of z-band intensity profiles
- Parameters:
thres (float) – Threshold for peak finder
min_dist (float) – Minimal distance of z-band peaks in µm
width (float) – Width of interval around peak for precise determination of peak center, in µm.
- track_z_bands(search_range: float = 1, memory_tracking: int = 10, memory_interpol: int = 3, t_range: Tuple[int, int] | None = None, z_range: Tuple[int, int] | None = None, min_length: float = 1, filter_params: Tuple[int, int] = (13, 7), equilibrium_weight: float = 0.3, use_lap_tracker: bool = True)[source]
Track peaks of intensity profile over time using LAP-based 1D tracking optimized for periodic motion
- Parameters:
search_range (float) – Maximum allowed distance for peak matching between frames (in µm)
memory_tracking (int) – Number of frames to keep track of missing peaks before starting a new trajectory
memory_interpol (int) – Maximum gap size (in frames) to interpolate missing detections in trajectories
t_range (Tuple[int, int] or None) – If not None, select time-interval of data, in frames
z_range (Tuple[int, int] or None) – If not None, select range of z-bands by index
min_length (float) – Minimal length of z-band trajectory in seconds. Shorter trajectories are removed.
filter_params (Tuple[int, int]) – Window length and polynomial order for Savitzky-Golay filter to smooth z positions
equilibrium_weight (float) – Weight factor (0-1) for equilibrium position prediction. Higher values make tracking more stable by pulling peaks toward their expected equilibrium positions.
use_lap_tracker (bool) – If True, use LAP-based tracker optimized for periodic 1D motion. If False, use basic nearest-neighbor.
- _track_z_bands_lap(peaks: List[numpy.ndarray], search_range: float, memory: int, equilibrium_weight: float = 0.3) numpy.ndarray[source]
Track z-bands using simple frame-to-frame nearest neighbor matching with equilibrium anchoring.
SIMPLE APPROACH: No new tracks after initialization. Z-bands are fixed structures that don’t appear/disappear during imaging - only the initial frame matters for track count.
- Parameters:
peaks (List[np.ndarray]) – List of peak positions for each frame
search_range (float) – Maximum allowed distance for matching (in µm)
memory (int) – Number of frames to remember missing peaks
equilibrium_weight (float) – Weight for equilibrium position in cost calculation (0 = pure spatial, 1 = pure equilibrium)
- Returns:
z_pos – 2D array of z-band trajectories (n_bands x n_frames)
- Return type:
np.ndarray
- static _greedy_assignment(cost_matrix: numpy.ndarray) Tuple[List[int], List[int]][source]
Greedy assignment fallback when Hungarian algorithm fails. Assigns tracks to detections by iteratively choosing the minimum cost pairing.
- Parameters:
cost_matrix (np.ndarray) – Cost matrix (n_tracks x n_detections)
- Returns:
row_ind, col_ind – Lists of matched track and detection indices
- Return type:
Tuple[List[int], List[int]]
- _track_z_bands_simple(peaks: List[numpy.ndarray], search_range: float, memory: int) numpy.ndarray[source]
Simple nearest-neighbor tracking as fallback.
- Parameters:
peaks (List[np.ndarray]) – List of peak positions for each frame
search_range (float) – Maximum allowed distance for matching
memory (int) – Number of frames to remember missing peaks
- Returns:
z_pos – 2D array of z-band trajectories
- Return type:
np.ndarray
- detect_analyze_contractions(model: str | None = None, threshold: float = 0.3, slen_lims: Tuple[float, float] = (1.2, 3), n_sarcomeres_min: int = 4, buffer_frames: int = 3, contr_time_min: float = 0.2, merge_time_max: float = 0.05)[source]
Detect contractions from contraction time-series using convolutional neural network and analyze beating
Predict contractions / contraction state (0 = quiescent, 1 = contracting) from sarcomere lengths (average or percentile)
- Optimize state by morphological closing and opening (minimal time of contraction cycle=contr_time_min,
merge contractions closer than merge_time_max). Remove cycles at very beginning or end (buffer_frames).
- Characterize state: obtain start times of contr. cycles (start_contractions_frame in frames, start_contr in s),
number of cycles (n_contr), label contraction cycles (1 to n_contr), duration of contr. cycles (time_contractions)
- Parameters:
model (str) – Neural network parameters (.pt file)
threshold (float) – Binary threshold for contraction state (0, 1) after prediction
slen_lims (tuple(float, float)) – Minimal and maximal sarcomere lengths, sarcomere outside interval are set to NaN
n_sarcomeres_min (int) – Minimal number of sarcomeres, if lower, contraction state is set to 0.
buffer_frames (int) – Remove contraction cycles / contractions within “buffer_frames” frames to start and end of time-series
contr_time_min (float) – Minimal time of contraction in seconds. If smaller, contraction is removed.
merge_time_max (float) – Maximal time between two contractions. If smaller, two contractions are merged to one.
- get_trajectories(slen_lims: Tuple[float, float] = (1.2, 3.0), filter_params_vel: Tuple[int, int] = (13, 5), dilate_contr: float = 0, equ_lims: Tuple[float, float] = (1.5, 2.3))[source]
Calculate sarcomere lengths (single and avg) and filter too large and too small values (slen_lims).
- Calculate sarcomere velocities (single and avg), prior smoothing of s’lengths with Savitzky-Golay filter
(filter_params_vel)
Calculate sarcomere equilibrium lengths (equ) and delta_slen
- Parameters:
slen_lims (tuple(float, float)) – Lower and upper limits of sarcomere lengths, values outside are set to nan
filter_params_vel (tuple(int, int)) – Window length and poly order for Savitky-Golay filter for smoothing of delta_slen prior to differentiation to obtain sarcomere velocities
dilate_contr (float) – Dilation time (in seconds) of contraction time-series to shorten time-interval during diastole at which the sarcomere equilibrium lengths are determined
equ_lims (tuple(float, float)) – Lower and upper limits of sarcomere equilibrium lengths, values outside are set to nan
- analyze_trajectories(custom_perc: List[Tuple[float, float]] | None = None)[source]
Analyze sarcomere single and average trajectories (extrema of sarcomeres contraction and velocity) and sarcomere popping
- Parameters:
custom_perc (List[Tuple[float, float]] or None, optional) – A list of tuples where each tuple contains two percentages (p0, p1) representing custom percentage points to analyze contraction, e.g., the time from p0% to p1% contraction of individual and average sarcomere length change. If p0<p1, the shortening is analyzed, if p1<p0, the elongation is analyzed. If not provided, defaults to None.
- calculate_surplus_motion_index()[source]
Calculate surplus motion index (SMI) for sarcomere motion: average distance traveled by individual sarcomeres contractions divided by distance traveled by sarcomere average
- analyze_popping(thres_popping: float = 0.25)[source]
Analyze sarcomere popping - popping if elongation of individual sarcomere is larger than thres_popping
- Parameters:
thres_popping (float) – Threshold above which sarcomere is identified as popping, in µm beyond equilibrium length
- analyze_correlations()[source]
Computes the Pearson correlation coefficients for sarcomere motion patterns (∆SL and V) across different contraction cycles and between sarcomeres within the same cycle to analyze static and stochastic heterogeneity in sarcomere dynamics.
It calculates the average serial (r_s) and mutual (r_m) correlation coefficients, and introduces the ratio R of serial to mutual correlations to distinguish between static and stochastic heterogeneity. The function updates the instance’s loi_data with correlation data, including the calculated R values, and stores the data if auto_save is enabled.
- Returns:
- Updates self.loi_data with the following keys:
’corr_delta_slen’ (ndarray or None): Correlation matrix for sarcomere length changes.
’corr_vel’ (ndarray or None): Correlation matrix for sarcomere velocities.
’corr_delta_slen_serial’ (float or NaN): Average serial correlation for sarcomere length changes.
’corr_delta_slen_mutual’ (float or NaN): Average mutual correlation for sarcomere length changes.
’corr_vel_serial’ (float or NaN): Average serial correlation for sarcomere velocities.
’corr_vel_mutual’ (float or NaN): Average mutual correlation for sarcomere velocities.
’ratio_delta_slen_mutual_serial’ (float or NaN): Ratio of mutual to serial correlation for sarcomere length changes.
’ratio_vel_mutual_serial’ (float or NaN): Ratio of mutual to serial correlation for sarcomere velocities.
- Return type:
None
- analyze_oscillations(min_scale: float = 6, max_scale: float = 180, num_scales: int = 60, wavelet: str = 'morl', freq_thres: float = 2, plot: bool = False)[source]
Analyze the oscillation frequencies of average and individual sarcomere length changes.
- Parameters:
min_scale (float, optional) – Minimum scale to use for the wavelet transform (default is 6).
max_scale (float, optional) – Maximum scale to use for the wavelet transform (default is 150).
num_scales (int, optional) – Number of scales to use for the wavelet transform (default is 100).
wavelet (str, optional) – Type of wavelet to use for the wavelet transform (default is ‘morl’ = Morlet wavelet).
freq_thres (float, optional) – Frequency threshold in Hz for distinguishing low-freq. oscillations at beating rate, and high-freq. oscillations.
plot (bool, optional) – If True, a plot illustrating the analysis is shown.
- Return type:
None
- static predict_contractions(z_pos: numpy.ndarray, slen: numpy.ndarray, weights: str, threshold: float = 0.33)[source]
Predict contractions from motion of z-bands and sarcomere lengths, then calculate mean state and threshold to get more accurate estimation of contractions
- Parameters:
z_pos (ndarray) – Time-series of Z-band positions
slen (ndarray) – Time-series of sarcomere lengths
weights (str) – Neural network parameters (.pt file)
threshold (float) – Binary threshold for contraction state (0, 1)
- static wavelet_analysis_oscillations(data: numpy.ndarray, frametime: float, min_scale: float = 6, max_scale: float = 150, num_scales: int = 100, wavelet: str = 'morl')[source]
Perform a wavelet transform of the data.
- Parameters:
data (array_like) – 1-D input signal.
frametime (float) – Sampling period of the signal.
min_scale (float, optional) – Minimum scale to use for the wavelet transform (default is 6).
max_scale (float, optional) – Maximum scale to use for the wavelet transform (default is 150).
num_scales (int, optional) – Number of scales to use for the wavelet transform (default is 200).
wavelet (str, optional) – Type of wavelet to use for the wavelet transform (default is ‘morl’).
- Returns:
cfs (ndarray) – Continuous wavelet transform coefficients.
frequencies (ndarray) – Corresponding frequencies for each scale.
- class sarcasm.Utils[source]
Miscellaneous utility functions
- static get_device()[source]
Determines the most suitable device (CUDA, MPS, or CPU) for PyTorch operations.
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(file_path: str) List[Tuple[str, str]][source]
Get the lines of interests (LOIs) of a tif-file.
- Parameters:
file_path (str) – Path to the tif file.
- 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 check_and_round_max_patch_size(max_patch_size)[source]
Checks whether each element of tuple is divisible by 16, and if not, rounds them up
- 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 skeleton_length_igraph(regionmask: numpy.ndarray, intensity_image=None) float[source]
Return the arc-length of a non-branching skeleton in physical units.
- Parameters:
regionmask (2-D boolean array) – One-pixel-wide skeleton (True = foreground).
- Returns:
Path length.
- Return type:
float
- static scale_back(paths: List[str], original_xy_shape: Tuple[int, int], output_dir: str, mask_data: bool = False) None[source]
Restore rescaled TIFFs to their original XY resolution. Assumes all TIFFs in ‘paths’ should be restored to the same ‘original_xy_shape’.
- Parameters:
paths (List[str]) – List of paths to the rescaled TIFF files.
original_xy_shape (Tuple[int, int]) – The target original (height, width) for the XY dimensions. This shape is applied to all images in ‘paths’.
output_dir (str) – Directory where the restored TIFFs will be saved.
mask_data (bool, optional) – If True, indicates the data represents segmentation masks, and nearest-neighbor interpolation will be used for upscaling to preserve discrete label values. Defaults to False (uses cubic).
- 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, interpolation_method: str = 'linear') 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 linear or 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.
interpolation_method (str, optional) – Interpolation method: ‘linear’ (fast) or ‘akima’ (smooth), by default ‘linear’.
- 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 linear interpolation by default for speed, or Akima for smoother results.
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 process_profiles_batch(profiles: List[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, interpolation_method: str = 'linear') Tuple[numpy.ndarray, numpy.ndarray][source]
Batch process multiple profiles for better performance.
This function processes multiple profiles at once, reducing function call overhead compared to processing them individually.
- Parameters:
profiles (List[np.ndarray]) – List of 1D intensity profiles.
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.
interpolation_method (str, optional) – Interpolation method: ‘linear’ (fast) or ‘akima’ (smooth), by default ‘linear’.
- Returns:
sarcomere_lengths (np.ndarray) – Array of sarcomere lengths for each profile.
center_offsets (np.ndarray) – Array of center offsets for each profile.
- 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 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 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 __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), file_path=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)
file_path (str, optional) – The file path to save the plot. Defaults to None.
- static plot_loi_detection(sarc_obj: sarcasm.structure.Structure, frame: int = 0, file_path: 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.
file_path (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 = 'gray', 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).
- static plot_z_bands_midlines(ax: matplotlib.pyplot.Axes, 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.
- 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_domain_timeseries(ax: matplotlib.axes.Axes, sarc_obj: sarcasm.structure.Structure, t_lim: Tuple[float, float] = (0, 12), y_lim: Tuple[float, float] = (1.6, 2.2), n_rows: int | None = None, show_contr: bool = True, use_median: bool = False)[source]
Plots domain sarcomere length time-series in a stacked multi-subplot layout.
Each domain’s sarcomere length time-series is shown in a separate row, with optional contraction period shading. Similar layout to plot_delta_slen for Motion objects.
- Parameters:
ax (matplotlib.axes.Axes) – The axes to draw the plot on.
sarc_obj (Structure) – The Structure object with domain motion analysis results.
t_lim (tuple of float, optional) – The time limits for the plot in seconds. Defaults to (0, 12).
y_lim (tuple of float, optional) – The y-axis limits for sarcomere length in µm. Defaults to (1.6, 2.2).
n_rows (int or None, optional) – Number of domains to display. If None, shows all domains. Defaults to None.
show_contr (bool, optional) – Whether to shade contraction periods. Defaults to True.
use_median (bool, optional) – If True, use median sarcomere length instead of mean. Defaults to False.
- Raises:
ValueError – If domain motion analysis has not been run.
- static plot_overlay_domain_timeseries(ax: matplotlib.axes.Axes, sarc_obj: sarcasm.structure.Structure, t_lim: Tuple[float, float] = (0, 12), y_lim: Tuple[float, float] = (1.4, 2.2), show_contr: bool = True, show_average: bool = True, use_median: bool = False, domain_indices: list | None = None)[source]
Plots domain sarcomere length time-series as overlaid trajectories.
All domain time-series are plotted on the same axes with different colors, optionally with an average line and contraction period shading.
- Parameters:
ax (matplotlib.axes.Axes) – The axes to draw the plot on.
sarc_obj (Structure) – The Structure object with domain motion analysis results.
t_lim (tuple of float, optional) – The time limits for the plot in seconds. Defaults to (0, 12).
y_lim (tuple of float, optional) – The y-axis limits for sarcomere length in µm. Defaults to (1.6, 2.2).
show_contr (bool, optional) – Whether to shade contraction periods (uses union of all domain contractions). Defaults to True.
show_average (bool, optional) – Whether to show the average across all domains. Defaults to True.
use_median (bool, optional) – If True, use median sarcomere length instead of mean. Defaults to False.
domain_indices (list or None, optional) – List of domain indices (0-based) to plot. If None, plots all domains. Defaults to None.
- Raises:
ValueError – If domain motion analysis has not been run.
- 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_file_path, 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_file_path (str) – The file 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
- get_data(structure_keys=None)[source]
Iterate files and get structure data.
- Parameters:
structure_keys (list, optional) – List of keys to extract structure data (default is None).
- 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
- get_data(loi_keys=None)[source]
Iterate files and get motion data.
- Parameters:
loi_keys (list, optional) – List of keys to extract motion data (default is None).
- Return type:
None
- load_data(path: str | None = None) pandas.DataFrame[source]
Load the DataFrame from the data folder.
- Parameters:
path (str, optional) – Path of pickle file with motion data. If None, fallback to data_motion.pd in self.folder.
- Return type:
None
- Raises:
FileExistsError – If the data file does not exist in the specified folder.