sarcasm.structure

Attributes

logger

Classes

Structure

Class for analyzing sarcomere morphology.

Module Contents

sarcasm.structure.logger
class sarcasm.structure.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.SarcAsM

Class for analyzing sarcomere morphology.

Parameters:
  • file_path (str | os.PathLike) – Path to the image tif file.

  • restart (bool, optional) – If True the previous analysis folder is deleted and a fresh run is started (default: False).

  • pixelsize (float or None, optional) – Physical pixel size in µm. If None the value is taken from file metadata; otherwise the supplied number overrides all metadata.

  • frametime (float or None, optional) – Time between frames in s. If None it 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'). None lets 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

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

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