foundation package

binary_image

towbintools.foundation.binary_image.connect_endpoints(binary_image: ndarray, max_distance: int = 200) ndarray[source]

Connect endpoints of a binary image if they are within a specified maximum distance.

First identifies the endpoints in the binary image using a Hit-Or-Miss morphology operation. If there are at least two endpoints, calculates the pairwise distances between them. Endpoints that are within the specified maximum distance from each other are connected using a straight line.

Parameters:
  • binary_image (np.ndarray) – A binary image where the foreground is represented by 1s and the background is represented by 0s.

  • max_distance (int, optional) – The maximum distance between two endpoints to consider connecting them. (default: 200)

Returns:

A binary image with the same dimensions as the input, where endpoints within the maximum distance are connected by straight lines.

Return type:

np.ndarray

towbintools.foundation.binary_image.fill_bright_holes(image: ndarray, mask: ndarray, scale: float) ndarray[source]

Fill bright holes in an image based on a given mask and statistical properties of the background.

Identifies holes in a provided mask and evaluates the brightness of these holes in the original image. Bright holes with a median brightness significantly greater than the background mean are filled.

Parameters:
  • image (np.ndarray) – Grayscale input image.

  • mask (np.ndarray) – Binary mask with foreground equal to 1.

  • scale (float) – A scaling factor that defines how many standard deviations above the background mean a hole needs to be in order for it to be considered ‘bright’ and filled.

Returns:

A binary mask with the same dimensions as the input, where bright holes have been filled.

Return type:

np.ndarray

towbintools.foundation.binary_image.find_endpoints(binary_image: ndarray) ndarray[source]

Find the endpoints of a binary image using the Hit-Or-Miss morphology operation.

Parameters:
  • binary_image (np.ndarray) – A binary image where the foreground is represented by 1s

  • 0s. (and the background is represented by)

Returns:

A binary image with the same dimensions as the input, where 1s represent the locations of the endpoints.

Return type:

np.ndarray

towbintools.foundation.binary_image.get_biggest_object(mask: ndarray, connectivity: int = 4) ndarray[source]

Retrieve the largest connected object from a binary mask.

Identifies connected components in the provided binary mask and returns a mask of the largest object. If no objects are identified, returns a zero mask of the same shape as the input.

Parameters:
  • mask (np.ndarray) – Binary image mask where the objects are set to 1.

  • connectivity (int, optional) – Connectivity for connected components. (default: 4)

Returns:

Binary mask of the biggest object.

Return type:

np.ndarray

detect_molts

towbintools.foundation.detect_molts.find_end_molts(volume: ndarray, midmolts: ndarray, search_width: int = 20, fit_width: int = 5) ndarray[source]

Identify the end of molts in a given volume time series based on mid-molt locations.

Processes the volume data by performing logarithmic transformations and smoothing. Searches for the end of each molt around the provided mid-molt locations using the provided search width. The end of each molt is determined by analyzing the second derivative of the smoothed volume.

Parameters:
  • volume (np.ndarray) – A time series representing volume.

  • midmolts (np.ndarray) – An array of identified mid-molt locations.

  • search_width (int, optional) – Width around the mid-molt to search for the end molt. Default is 20.

  • fit_width (int, optional) – Width for the linear regression fit used in determining the end molt. Default is 5.

Returns:

Indices of the identified end-molts in the input volume.

Return type:

np.ndarray

towbintools.foundation.detect_molts.find_hatch_time(worm_types: ndarray) float[source]

Determine the hatch time based on the classified worm types.

The hatch time is defined as the index immediately after the last egg found before the first worm in the sequence. If no worms or eggs are found before the first worm, it returns NaN.

Parameters:

worm_types (np.ndarray) – An array of strings representing the sequence of worm-related types, e.g., [“egg”, “egg”, “worm”, …].

Returns:

The index representing the hatch time.

Returns NaN if the conditions for hatch time aren’t met.

Return type:

float

towbintools.foundation.detect_molts.find_mid_molts(volume: ndarray, molt_size_range: ndarray) ndarray[source]

Identify mid-molts in a given volume time series based on expected sizes at molt.

Processes the volume data by performing logarithmic transformations, smoothing, and calculating the derivative. Peaks in the derivative represent potential mid-molts. The best mid-molts are then selected based on closeness to expected molt sizes and linear regression slopes.

Parameters:
  • volume (np.ndarray) – A time series representing volume.

  • molt_size_range (np.ndarray) – An array of expected sizes at molt.

Returns:

Indices of the identified mid-moults in the input volume.

Return type:

np.ndarray

towbintools.foundation.detect_molts.find_molts(volume: ndarray, worm_types: ndarray, molt_size_range: list = [66000.0, 150000.0, 360000.0, 1020000.0], search_width: int = 20, fit_width: int = 5) dict[source]

Identify molt events.

Integrated approach that uses a combination of several utility functions to: 1. Identify hatch time of the worm. 2. Identify mid-molts based on specified size ranges. 3. Identify the end-molts based on mid-molts and given search and fit widths. 4. Compute the volume at hatch and each molt event.

Parameters:
  • volume (np.ndarray) – A time series representing volume.

  • worm_types (np.ndarray) – An array indicating the type of each entry in the volume time series. Expected values are “worm”, “egg”, “error”, etc.

  • molt_size_range (list, optional) – Expected size ranges for mid-molts. Default values are provided.

  • search_width (int, optional) – Width for searching the end-molts. Default is 20.

  • fit_width (int, optional) – Width for the linear regression fit used in computing the volume. Default is 5.

Returns:

Dictionary containing the hatch time and end-molt times.

Return type:

dict

towbintools.foundation.detect_molts.interpolate_peaks(signal: ndarray) ndarray[source]

Interpolate over prominent peaks in a given signal.

Identifies prominent peaks in the signal and replaces their values with NaN. The NaN values are then interpolated to provide a smoother representation. If there’s a ValueError, likely due to no peaks being found, the original signal is returned.

Parameters:

signal (np.ndarray) – The input signal array.

Returns:

The signal with interpolated values over detected peaks.

Return type:

np.ndarray

file_handling

towbintools.foundation.file_handling.add_dir_to_experiment_filemap(experiment_filemap: DataFrame, dir_path: str, subdir_name: str, time_regex: str = 'Time(\\d+)', point_regex: str = 'Point(\\d+)') DataFrame[source]

Add the images contained in a directory to an existing filemap as a new column.

Parameters:
  • experiment_filemap (pl.DataFrame) – Existing filemap dataframe with at least "Time" and "Point" columns.

  • dir_path (str) – The path to the directory containing the images.

  • subdir_name (str) – The name of the new column to be added to the filemap.

  • time_regex (str) – Regular expression pattern to extract time information from file names. (default: r”Time(d+)”)

  • point_regex (str) – Regular expression pattern to extract point information from file names. (default: r”Point(d+)”)

Returns:

Updated filemap dataframe with the new column added, missing

entries filled with empty strings.

Return type:

pl.DataFrame

towbintools.foundation.file_handling.extract_time_point(path: str, time_regex: str = 'Time(\\d+)', point_regex: str = 'Point(\\d+)') tuple[int, int][source]

Extract time and point information from a file name using regular expressions.

Parameters:
  • path (str) – The file path or name to extract information from.

  • time_regex (str) – Regular expression pattern to extract time information. (default: r”Time(d+)”)

  • point_regex (str) – Regular expression pattern to extract point information. (default: r”Point(d+)”)

Returns:

A tuple containing the extracted time and point as integers.

Return type:

tuple

towbintools.foundation.file_handling.fill_empty_timepoints(filemap: DataFrame) DataFrame[source]

Fill in missing time points in a filemap dataframe with empty image paths.

Parameters:

filemap (pl.DataFrame) – The filemap dataframe containing ‘Time’, ‘Point’, and ‘ImagePath’ columns.

Returns:

The filled filemap dataframe with missing time points included.

Return type:

pl.DataFrame

towbintools.foundation.file_handling.get_all_timepoints_from_dir(dir_path: str, time_regex: str = 'Time(\\d+)', point_regex: str = 'Point(\\d+)') list[dict][source]

Retrieve all time points and corresponding image paths from a directory.

Parameters:
  • dir_path (str) – The path to the directory containing the images.

  • time_regex (str) – Regular expression pattern to extract time information from file names. (default: r”Time(d+)”)

  • point_regex (str) – Regular expression pattern to extract point information from file names. (default: r”Point(d+)”)

Returns:

A list of dictionaries, each containing the time, point, and image path.

Return type:

list

towbintools.foundation.file_handling.get_dir_filemap(dir_path: str, time_regex: str = 'Time(\\d+)', point_regex: str = 'Point(\\d+)') DataFrame[source]

Get the filemap dataframe for a directory by retrieving all time points and filling in missing time points.

Parameters:
  • dir_path (str) – The path to the directory containing the images.

  • time_regex (str) – Regular expression pattern to extract time information from file names. (default: r”Time(d+)”)

  • point_regex (str) – Regular expression pattern to extract point information from file names. (default: r”Point(d+)”)

Returns:

The filemap dataframe with ‘Time’, ‘Point’, and ‘ImagePath’ columns.

Return type:

pl.DataFrame

towbintools.foundation.file_handling.get_experiment_dir_filemap(dir_path: str, raw_dir: str = 'raw', analysis_dir: str = 'analysis', time_regex: str = 'Time(\\d+)', point_regex: str = 'Point(\\d+)') DataFrame[source]

Get the filemap dataframe for an experiment directory.

Retrieves time points from the ‘raw’ directory and fills in missing ones then adds paths from the ‘analysis’ subdirectories.

Parameters:
  • dir_path (str) – Base directory path for the experiment.

  • raw_dir (str) – Subdirectory name for raw images. (default: “raw”)

  • analysis_dir (str) – Subdirectory name for analysis output. (default: “analysis”)

  • time_regex (str) – Regular expression pattern to extract time information from file names. (default: r”Time(d+)”)

  • point_regex (str) – Regular expression pattern to extract point information from file names. (default: r”Point(d+)”)

Returns:

Extended filemap dataframe including both raw and analysis image paths.

Return type:

pl.DataFrame

towbintools.foundation.file_handling.read_filemap(filemap_path: str, lazy_loading: bool = False) DataFrame[source]

Read a filemap from a CSV or Parquet file using Polars.

Detects the file format from the .parquet extension; otherwise treats the file as CSV. When lazy_loading is True a LazyFrame is returned instead of an eager DataFrame.

Parameters:
  • filemap_path (str) – Path to the filemap file (.csv or .parquet).

  • lazy_loading (bool, optional) – If True, return a Polars LazyFrame instead of a DataFrame. (default: False)

Returns:

The filemap as a Polars DataFrame (or LazyFrame when

lazy_loading is True).

Return type:

pl.DataFrame

towbintools.foundation.file_handling.write_filemap(filemap: DataFrame, filemap_path: str) None[source]

Write a filemap to a CSV or Parquet file using Polars.

Detects the output format from the .parquet extension; otherwise writes CSV.

Parameters:
  • filemap (pl.DataFrame) – The filemap dataframe to write.

  • filemap_path (str) – Destination path for the filemap file (.csv or .parquet).

Returns:

None

image_handling

towbintools.foundation.image_handling.align_images_orientation_ssim(image: ndarray, reference_image: ndarray, axes_to_flip: list[int] = [-1, -2]) ndarray[source]

Align the orientation of an image based on structural similarity index (SSIM) comparison with a reference image. All combination of flipped images along the chosen axis will be generated. The one with the highest SSIM to the reference image will be returned.

Parameters:
  • image (np.ndarray) – The input worm image as a NumPy array.

  • reference_image (np.ndarray) – The reference image for comparison as a NumPy array.

  • axes_to_flip (list) – List of axes to flip.

Returns:

The aligned worm image as a NumPy array.

Return type:

np.ndarray

towbintools.foundation.image_handling.augment_contrast(image: ndarray, clip_limit: float = 5, tile_size: int = 8) ndarray[source]

Augment the contrast of an image using the CLAHE (Contrast Limited Adaptive Histogram Equalization) method.

Parameters:
  • image (np.ndarray) – The input image as a NumPy array.

  • clip_limit (float) – The clipping limit for contrast enhancement. Values above this limit get clipped.

  • tile_size (int) – The size of the tile grid for the CLAHE method.

Returns:

The contrast-enhanced image as a NumPy array of dtype np.uint16.

Return type:

np.ndarray

towbintools.foundation.image_handling.check_if_stack(file_path: str, channels_to_keep: list[int] | None = None) tuple[bool, tuple[int, int]][source]

Determine whether the given OME-TIFF file represents a stack (either z-stack or time series). Checks the z-dimension and t-dimension sizes in the OME-TIFF metadata to determine if the image is a stack (more than one z-plane or more than one time point). If the metadata cannot be read, it will try to infer the stack status from the image shape.

Parameters:
  • file_path (str) – Path to the OME-TIFF image file.

  • channels_to_keep (list[int], optional) – Channel indices used to infer stack status when OME-TIFF metadata is unavailable. (default: None)

Returns:

(is_stack, (z_dim, t_dim)) where is_stack is True when

either z_dim > 1 or t_dim > 1, and (z_dim, t_dim) are the corresponding dimension sizes.

Return type:

tuple

towbintools.foundation.image_handling.check_if_time_series(file_path: str) bool[source]

Determine whether the given OME-TIFF file represents a time series.

Checks the t-dimension size in the OME-TIFF metadata to determine if the image is a time series (more than one time point).

Returns False if the file is not a valid OME-TIFF or the metadata cannot be read.

Parameters:

file_path (str) – Path to the OME-TIFF image file.

Returns:

True if the image is a time series (t_dim > 1), False otherwise or if the file is not a valid OME-TIFF or the metadata cannot be read.

Return type:

bool

towbintools.foundation.image_handling.check_if_zstack(file_path: str) bool[source]

Determine whether the given OME-TIFF file represents a z-stack.

Checks the z-dimension size in the OME-TIFF metadata to determine if the image is a z-stack (more than one z-plane).

Returns False if the file is not a valid OME-TIFF or the metadata cannot be read.

Parameters:

file_path (str) – Path to the OME-TIFF image file.

Returns:

True if the image is a z-stack (z_dim > 1), False otherwise or if the file is not a valid OME-TIFF or the metadata cannot be read.

Return type:

bool

towbintools.foundation.image_handling.crop_images_to_same_dim(image1: ndarray, image2: ndarray) tuple[ndarray, ndarray][source]

Crop two images to the same dimensions by taking the minimum height and width.

Parameters:
  • image1 (np.ndarray) – The first input image as a NumPy array.

  • image2 (np.ndarray) – The second input image as a NumPy array.

Returns:

A tuple containing the cropped images.

Return type:

Tuple[np.ndarray, np.ndarray]

towbintools.foundation.image_handling.crop_to_dim(image: ndarray, xdim: int, ydim: int) ndarray[source]

Crop an image to target dimensions by removing pixels from the bottom and right

Parameters:
  • image (np.ndarray) – Input image array of shape (… , H, W).

  • xdim (int) – Desired height of the cropped image.

  • ydim (int) – Desired width of the cropped image.

Returns:

Cropped image of shape (… , xdim, ydim).

Return type:

np.ndarray

towbintools.foundation.image_handling.crop_to_dim_equally(image: ndarray, xdim: int, ydim: int) ndarray[source]

Crop an image equally to the specified dimensions by removing pixels from both sides.

Parameters:
  • image (np.ndarray) – Input image array of shape (… , H, W).

  • xdim (int) – Desired height of the cropped image.

  • ydim (int) – Desired width of the cropped image.

Returns:

Cropped image of shape (… , xdim, ydim).

Return type:

np.ndarray

Raises:

ValueError – If target dimensions are larger than input dimensions.

towbintools.foundation.image_handling.get_acquisition_date(file_path: str) datetime | None[source]

Extract the acquisition date from the OME-TIFF metadata of the given file.

Returns None if the metadata cannot be read or the file is not a valid OME-TIFF.

Parameters:

file_path (str) – Path to the OME-TIFF image file.

Returns:

The acquisition date of the image, or None if the metadata cannot be read or the file is not a valid OME-TIFF.

Return type:

Optional[datetime]

towbintools.foundation.image_handling.get_image_size_metadata(file_path: str) dict | None[source]

Extract and return the size metadata of an image from its OME-TIFF file.

Includes its width (x dimension), height (y dimension), depth (z dimension), timepoints (t dimension), and number of channels (c dimension).

Parameters:

file_path (str) – Path to the OME-TIFF image file.

Returns:

A dictionary containing the dimensions of the image (x_dim, y_dim, z_dim, t_dim, c_dim).

Returns None if the metadata cannot be read or the file is not a valid OME-TIFF.

Return type:

dict

towbintools.foundation.image_handling.get_shape_from_tiff(file_path: str, channels_to_keep: list[int] | None = None) tuple | None[source]

Get the shape of the image stored in the TIFF file.

Parameters:
  • file_path (str) – Path to the TIFF image file.

  • channels_to_keep (Optional[list[int]]) – List of channel indices to keep. If None, all channels are considered.

Returns:

The shape of the image as a tuple.

Returns None if the file cannot be read.

Return type:

Tuple

Raises:

ValueError – If the image file cannot be read or if the shape cannot be determined.

towbintools.foundation.image_handling.normalize_image(image: ndarray, dest_dtype: type = <class 'numpy.uint16'>) ndarray[source]

Normalize an image to a specified data type’s range.

Parameters:
  • image (np.ndarray) – The input image as a NumPy array.

  • dest_dtype (type) – The desired data type for the output normalized image. Allowed values are np.uint16, np.uint8, np.float32, np.float64.

Returns:

The normalized image with the specified data type.

Return type:

np.ndarray

Raises:

ValueError – If dest_dtype is not one of the allowed data types.

towbintools.foundation.image_handling.pad_images_to_same_dim(image1: ndarray, image2: ndarray, pad_value: float = 0) tuple[ndarray, ndarray][source]

Pad two images to the same dimensions by taking the maximum height and width.

Parameters:
  • image1 (np.ndarray) – The first input image as a NumPy array.

  • image2 (np.ndarray) – The second input image as a NumPy array.

  • pad_value (float) – The value to use for padding (default: 0).

Returns:

A tuple containing the padded images.

Return type:

Tuple[np.ndarray, np.ndarray]

towbintools.foundation.image_handling.pad_to_dim(image: ndarray, xdim: int, ydim: int, pad_value: float = 0) ndarray[source]

Pad an image to target dimensions by padding on its right and bottom.

Parameters:
  • image (np.ndarray) – Input image array of shape (…, H, W).

  • xdim (int) – Desired height of the padded image.

  • ydim (int) – Desired width of the padded image.

  • pad_value (float) – Value to use for padding (default: 0).

Returns:

Padded image of shape (…, xdim, ydim).

Return type:

np.ndarray

towbintools.foundation.image_handling.pad_to_dim_equally(image: ndarray, xdim: int, ydim: int, pad_value: float = 0) ndarray[source]

Efficiently pad an image equally on all sides to reach target dimensions.

Parameters:
  • image (np.ndarray) – Input image array of shape (…, H, W).

  • xdim (int) – Desired height of the padded image.

  • ydim (int) – Desired width of the padded image.

  • pad_value (float) – Value to use for padding (default: 0).

Returns:

Padded image of shape (…, xdim, ydim).

Return type:

np.ndarray

Raises:

ValueError – If target dimensions are smaller than input dimensions.

towbintools.foundation.image_handling.read_tiff_file(file_path: str, channels_to_keep: list[int] | None = None) ndarray[source]

Read a TIFF file and optionally select specific channels from the image.

Parameters:
  • file_path (str) – Path to the TIFF image file.

  • channels_to_keep (list) – List of channel indices to keep. If empty or None, all channels are kept.

Returns:

The image data as a NumPy array. The number of dimensions may vary depending on the input and selected channels.

Return type:

np.ndarray

Raises:

ValueError – If the image file cannot be read.

image_quality

towbintools.foundation.image_quality.LAPM(img: ndarray) float[source]

Compute the Modified Laplacian (LAP2) focus measure.

Applies separate 1D Laplacian kernels along the X and Y axes and returns the mean of their absolute sum. Higher values indicate a sharper image.

Parameters:

img (np.ndarray) – The input grayscale image.

Returns:

Mean Modified Laplacian; higher values indicate better focus.

Return type:

float

towbintools.foundation.image_quality.LAPV(img: ndarray) float[source]

Compute the Variance of Laplacian (LAP4) focus measure.

Measures the variance of the Laplacian of the image, which reflects the amount of edges present. Higher values indicate a sharper image.

Parameters:

img (np.ndarray) – The input grayscale image.

Returns:

Variance of the Laplacian; higher values indicate better focus.

Return type:

float

towbintools.foundation.image_quality.MLOG(img: ndarray) float[source]

Compute the MLOG focus measure.

Returns the maximum absolute value of the Laplacian of the image. Higher values indicate a sharper image.

Parameters:

img (np.ndarray) – The input grayscale image.

Returns:

Maximum absolute Laplacian; higher values indicate better focus.

Return type:

float

towbintools.foundation.image_quality.TENG(img: ndarray) float[source]

Compute the Tenengrad (TENG) focus measure.

Calculates the mean of the squared Sobel gradient magnitudes along both axes. Higher values indicate a sharper image.

Parameters:

img (np.ndarray) – The input grayscale image.

Returns:

Mean squared Sobel gradient; higher values indicate better focus.

Return type:

float

towbintools.foundation.image_quality.TENG_VARIANCE(img: ndarray) float[source]

Compute the Tenengrad Variance focus measure.

Calculates the variance of the gradient magnitude (computed via Sobel operators). Higher values indicate a sharper image.

Parameters:

img (np.ndarray) – The input grayscale image.

Returns:

Variance of the gradient magnitude; higher values indicate better focus.

Return type:

float

towbintools.foundation.image_quality.normalized_variance_measure(image: ndarray) float[source]

Compute the normalized variance measure of an image.

Parameters:

image (np.ndarray) – The input image as a numpy array.

Returns:

The computed normalized variance value.

Return type:

float

worm_features

towbintools.foundation.worm_features.compute_base_label_features(mask_of_label: ndarray, intensity_image: ndarray, features: list[str], extra_properties: list[str]) list[source]

Compute a set of features for a single label.

Parameters:
  • mask_of_label (np.ndarray) – The mask of the label.

  • intensity_image (np.ndarray) – The intensity image.

  • features (list) – The list of features to compute.

  • extra_properties (list) – The list of extra properties to compute.

Returns:

A list of features for the label.

Return type:

list

towbintools.foundation.worm_features.compute_bending_energy(midline_points: array, widths: array, E: float = 1.0, smooth: float | None = None) float[source]

Compute bending energy of a midline considering variable width.

Parameters:
  • midline_points (np.array) – array of shape (n, 2) containing centerline x,y coordinates

  • widths (np.array) – array of shape (n,) containing width at each point

  • E (float) – Young’s modulus (set to 1.0 for relative comparisons)

  • smooth (float) – smoothing factor for spline fitting. If None, the default scipy smoothing is applied. (default: None)

Returns:

bending energy

Return type:

float

towbintools.foundation.worm_features.compute_bending_energy_mask(mask: ndarray, pixelsize: float, E: float = 1.0, smooth: float | None = None, savgol_window: int = 21, savgol_order: int = 3) float[source]

Compute bending energy of a binary mask by extracting its midline and width profile.

Parameters:
  • mask (np.ndarray) – Binary mask.

  • pixelsize (float) – Physical size of a pixel, used for width calculation.

  • E (float) – Young’s modulus (set to 1.0 for relative comparisons)

  • smooth (float) – smoothing factor for spline fitting. If None, the default scipy smoothing is applied. (default: None)

  • savgol_window (int) – window size for Savitzky-Golay filter. (default: 21)

  • savgol_order (int) – order of Savitzky-Golay filter. (default: 3)

Returns:

bending energy

Return type:

float

towbintools.foundation.worm_features.compute_haralick_features(image: ndarray) list[source]

Compute Haralick texture features for an image.

Parameters:

image (np.ndarray) – The intensity image.

Returns:

A list of Haralick texture features.

Return type:

list

towbintools.foundation.worm_features.compute_image_features(image: ndarray, features: list) dict[source]

Compute a set of image features for an image.

Parameters:
  • image (np.ndarray) – The input image as a NumPy array.

  • features (list) – The list of features to compute.

Returns:

A dictionary containing the computed features.

Return type:

dict

towbintools.foundation.worm_features.compute_mask_area(worm_mask: ndarray, pixelsize: float) float[source]

Compute the area of a worm mask.

Parameters:
  • worm_mask (np.ndarray) – The worm mask as a NumPy array.

  • pixelsize (float) – The size of a pixel, used for area calculation.

Returns:

The computed area of the worm.

Return type:

float

towbintools.foundation.worm_features.compute_mask_average_width(straightened_mask: ndarray, pixelsize: float, aggregation: str = 'mean') float[source]

Compute the average width of a straightened mask.

Parameters:
  • straightened_mask (np.ndarray) – The straightened mask as a NumPy array.

  • pixelsize (float) – The size of a pixel, used for width calculation.

  • aggregation (str) – The aggregation method to use to compute the width. Can be either ‘mean’ or ‘median’. (default: ‘mean’)

Returns:

The computed average width of the worm.

Return type:

float

Raises:

ValueError – If aggregation is not "mean" or "median".

towbintools.foundation.worm_features.compute_mask_length(straightened_mask: ndarray, pixelsize: float) float[source]

Compute the length of a straightened mask using the sum of its pixels along the 0-axis.

Parameters:
  • straightened_mask (np.ndarray) – The straightened mask as a NumPy array.

  • pixelsize (float) – The size of a pixel, used for length calculation.

Returns:

The computed length of the worm.

Return type:

float

towbintools.foundation.worm_features.compute_mask_morphological_features(straightened_mask: ndarray, pixelsize: float, features: list[str]) dict[source]

Compute a set of morphological features for a straightened mask.

Parameters:
  • straightened_mask (np.ndarray) – The straightened mask as a NumPy array.

  • pixelsize (float) – The size of a pixel, used for various calculations.

  • features (list) – The list of features to compute.

Returns:

A dictionary containing the computed features.

Return type:

dict

towbintools.foundation.worm_features.compute_mask_type_features(straightened_mask: ndarray, pixelsize: float) list[source]

Compute a series of morphological features for a straightened mask including length, volume, volume per length, width measures, entropy, and region properties.

Parameters:
  • straightened_mask (np.ndarray) – The straightened mask as a NumPy array.

  • pixelsize (float) – The size of a pixel, used for various calculations.

Returns:

A list containing the computed features in the following order:

[worm_length, worm_volume, volume_per_length, width_mean, width_std, width_cv, entropy_mask, eccentricity, solidity, permimeter]

Return type:

list

towbintools.foundation.worm_features.compute_mask_volume(straightened_mask: ndarray, pixelsize: float) float[source]

Compute the volume of a straightened mask using its radius and pixel size.

Parameters:
  • straightened_mask (np.ndarray) – The straightened mask as a NumPy array.

  • pixelsize (float) – The size of a pixel, used for volume calculation.

Returns:

The computed volume of the worm.

Return type:

float

towbintools.foundation.worm_features.compute_max_width(width_profile: ndarray, window_size: int = 10) float[source]

Compute the maximum width of a worm from its width profile by taking the maximum value and averaging the values around it.

Parameters:
  • width_profile (np.ndarray) – The width profile of the worm.

  • window_size (int) – The size of the window to average around the maximum. (default: 10)

Returns:

The maximum width of the worm.

Return type:

float

towbintools.foundation.worm_features.compute_mid_width(width_profile: ndarray, window_size: int = 10) float[source]

Compute the width of a worm at its midpoint from its width profile by averaging the values around the midpoint.

Parameters:
  • width_profile (np.ndarray) – The width profile of the worm.

  • window_size (int) – The size of the window to average around the midpoint. (default: 10)

Returns:

The width of the worm at its midpoint.

Return type:

float

towbintools.foundation.worm_features.compute_patch_features(regionmask: ndarray, intensity_image: ndarray, patch_size: int = 64) list[source]

Compute a set of features for a patch around a region.

Parameters:
  • regionmask (np.ndarray) – The mask of the region.

  • intensity_image (np.ndarray) – The intensity image.

  • patch_size (int) – The size of the patch. (default: 64)

Returns:

A list of features for the patch.

Return type:

list

towbintools.foundation.worm_features.compute_width_profile(straightened_mask: ndarray, pixelsize: float, smooth: bool = True, savgol_window: int = 21, savgol_order: int = 3) ndarray[source]

Compute the width profile of a straightened mask.

Parameters:
  • straightened_mask (np.ndarray) – The straightened mask as a NumPy array.

  • pixelsize (float) – The size of a pixel, used for width calculation.

  • smooth (bool) – Whether to apply a Savitzky-Golay filter to the width profile. (default: True)

  • savgol_window (int) – The window size of the Savitzky-Golay filter. (default: 21)

  • savgol_order (int) – The order of the Savitzky-Golay filter. (default: 3)

Returns:

The computed and smoothed width profile. If smoothing fails, the unsmoothed profile is returned.

Return type:

np.ndarray

towbintools.foundation.worm_features.get_available_mask_features() list[str][source]

Get a list of available worm features.

Returns:

The list of available worm features.

Return type:

list

towbintools.foundation.worm_features.get_available_regionprops()[source]
towbintools.foundation.worm_features.get_context(current_label: int, mask_of_current_label: ndarray, mask_of_labels: ndarray, num_closest: int = 5) ndarray[source]

Returns the mask of the closest labels to the current label in a label image.

Parameters:
  • current_label (int) – The label of the current region.

  • mask_of_current_label (np.ndarray) – The mask of the current region.

  • mask_of_labels (np.ndarray) – The mask of all regions.

  • num_closest (int) – The number of closest regions to return. (default: 5)

Returns:

The mask of the closest regions.

Return type:

np.ndarray

towbintools.foundation.worm_features.get_context_features(mask_of_labels: ndarray, intensity_image: ndarray, features: list[str], extra_properties: list[str]) list[source]

Compute a set of features for the context of a label.

Parameters:
  • mask_of_labels (np.ndarray) – The mask of all regions.

  • intensity_image (np.ndarray) – The intensity image.

  • features (list) – The list of features to compute.

  • extra_properties (list) – The list of extra properties to compute.

Returns:

A list of aggregated features for the context of the label (mean and std of each desired feature).

Return type:

list

towbintools.foundation.worm_features.get_features_to_compute_at_molt() list[str][source]

Get a list of features to compute at molt.

Returns:

The list of features to compute at molt.

Return type:

list

towbintools.foundation.worm_features.intensity_kurtosis(regionmask: ndarray, intensity_image: ndarray) float[source]

Compute the kurtosis of the intensity values within a region.

Parameters:
  • regionmask (np.ndarray) – The mask of the region.

  • intensity_image (np.ndarray) – The intensity image.

Returns:

The kurtosis of the intensity values within the region.

Return type:

float

towbintools.foundation.worm_features.intensity_skew(regionmask: ndarray, intensity_image: ndarray) float[source]

Compute the skewness of the intensity values within a region.

Parameters:
  • regionmask (np.ndarray) – The mask of the region.

  • intensity_image (np.ndarray) – The intensity image.

Returns:

The skewness of the intensity values within the region.

Return type:

float

towbintools.foundation.worm_features.intensity_std(regionmask: ndarray, intensity_image: ndarray) float[source]

Compute the standard deviation of the intensity values within a region.

Parameters:
  • regionmask (np.ndarray) – The mask of the region.

  • intensity_image (np.ndarray) – The intensity image.

Returns:

The standard deviation of the intensity values within the region.

Return type:

float

zstack

towbintools.foundation.zstack.augment_contrast_zstack(zstack: ndarray, clip_limit: int = 5, tile_size: int = 8, normalize_each_plane: bool = True) ndarray[source]

Augment the contrast of a z-stack of images using the CLAHE algorithm, with an optional initial normalization step on each z-plane.

Parameters:
  • zstack (np.ndarray) – The input z-stack as a 3D NumPy array, with the third dimension representing the z-plane.

  • clip_limit (int, optional) – The clipping limit used in the CLAHE algorithm. Higher values increase contrast. (default: 5)

  • tile_size (int, optional) – The side length (in pixels) of the square tiles the image is divided into for the CLAHE algorithm. (default: 8)

  • normalize_each_plane (bool, optional) – Flag to determine if each z-plane should be normalized independently before contrast augmentation. (default: True)

Returns:

The contrast-augmented z-stack as a 3D NumPy array.

Return type:

np.ndarray

towbintools.foundation.zstack.find_best_plane(zstack: ndarray, measure: str, channel: int | None = None, dest_dtype: dtype = <class 'numpy.uint16'>, each_plane: bool = True, contrast_augmentation: bool = False, clip_limit: int = 2) tuple[int, ndarray][source]

Find the best plane (z-slice) of a z-stack based on a specified measure.

Parameters:
  • zstack (np.ndarray) – The input z-stack, potentially multi-channel.

  • measure (str) – The measure used to identify the “best” plane. Can be ‘shannon_entropy’, ‘mean’, ‘normalized_variance’, ‘lapv’, ‘lapm’, ‘teng’ or ‘mlog’.

  • channel (int, optional) – If the z-stack has more than 3 dimensions, specifies which channel to use. (default: None)

  • dest_dtype (np.dtype, optional) – Desired data type after normalization. (default: np.uint16)

  • each_plane (bool, optional) – Flag to determine if each z-plane should be normalized independently. (default: True)

  • contrast_augmentation (bool, optional) – Whether to augment contrast of the z-stack or not. (default: False)

  • clip_limit (int, optional) – The clipping limit used for contrast augmentation if activated. (default: 2)

Returns:

A tuple containing:
  • int: The index of the best z-plane.

  • np.ndarray: The best z-plane image slice.

Return type:

tuple

Raises:

ValueError – If the z-stack has more than 3 dimensions and the channel is not specified.

Notes

The ‘measure’ determines which z-plane is considered “best”. For example, if ‘measure’ is ‘mean’, then the z-plane with the highest mean pixel intensity is considered the best.

towbintools.foundation.zstack.normalize_zstack(zstack: ndarray, each_plane: bool = True, dest_dtype: dtype = <class 'numpy.uint16'>) ndarray[source]

Normalize a z-stack of images, either plane by plane or the whole stack, to the desired data type range.

Parameters:
  • zstack (np.ndarray) – The input z-stack as a 3D NumPy array, with the third dimension representing the z-plane.

  • each_plane (bool, optional) – Flag to determine if each z-plane should be normalized independently. (default: True)

  • dest_dtype (np.dtype, optional) – The desired data type for the output normalized z-stack. Can be one of the following: np.uint16, np.uint8, np.float32, np.float64. (default: np.uint16)

Raises:

ValueError – If dest_dtype is not one of the specified types.

Returns:

The normalized z-stack as a 3D NumPy array.

Return type:

np.ndarray

utils

exception towbintools.foundation.utils.NotImplementedError[source]

Bases: Exception

towbintools.foundation.utils.find_best_string_match(reference: str, candidates: list[str]) str[source]

Find the best matching candidate string to a reference using component and string similarity.

Scores each candidate by a weighted combination of component overlap (60 %) and sequence similarity (40 %), returning the candidate with the highest score. Useful for matching QC column names to data column names.

Parameters:
  • reference (str) – The reference string to match against.

  • candidates (list[str]) – List of candidate strings to evaluate.

Returns:

The best matching candidate string.

Return type:

str

towbintools.foundation.utils.inf_helper(y: ndarray) tuple[ndarray, Callable][source]

Return logical indices of infinities and a conversion function for use with np.interp.

Parameters:

y (np.ndarray) – 1D array with possible infinity values.

Returns:

(infs, index) where infs is a boolean array marking infinity

positions and index is a callable that converts a boolean index array to integer indices (e.g. index(infs) returns positions of infinities).

Return type:

tuple

Example

>>> infs, x = inf_helper(y)
>>> y[infs] = np.interp(x(infs), x(~infs), y[~infs])
towbintools.foundation.utils.interpolate_infs(signal: ndarray) ndarray[source]

Interpolate infinity values in a given signal.

Uses linear interpolation to estimate and replace infinity values in the provided signal based on the values of non-infinity neighbors.

Parameters:

signal (np.ndarray) – The input signal array, which might contain infinity values.

Returns:

The signal array with infinity values interpolated.

Return type:

np.ndarray

towbintools.foundation.utils.interpolate_nans(signal: ndarray) ndarray[source]

Interpolate NaN values in a given signal.

Uses linear interpolation to estimate and replace NaN values in the provided signal based on the values of non-NaN neighbors.

Parameters:

signal (np.ndarray) – The input signal array, which might contain NaN values.

Returns:

The signal array with NaN values interpolated.

Return type:

np.ndarray

towbintools.foundation.utils.interpolate_nans_infs(signal: ndarray) ndarray[source]

Interpolate NaN and infinity values in a given signal.

Uses linear interpolation to estimate and replace NaN and infinity values in the provided signal based on the values of non-NaN and non-infinity neighbors.

Parameters:

signal (np.ndarray) – The input signal array, which might contain NaN and infinity values.

Returns:

The signal array with NaN and infinity values interpolated.

Return type:

np.ndarray

towbintools.foundation.utils.nan_helper(y: ndarray) tuple[ndarray, Callable][source]

Return logical indices of NaNs and a conversion function for use with np.interp.

Parameters:

y (np.ndarray) – 1D array with possible NaN values.

Returns:

(nans, index) where nans is a boolean array marking NaN

positions and index is a callable that converts a boolean index array to integer indices (e.g. index(nans) returns positions of NaNs).

Return type:

tuple

Example

>>> nans, x = nan_helper(y)
>>> y[nans] = np.interp(x(nans), x(~nans), y[~nans])

“””