API reference

Core functions

Core routines for the MotilA pipeline.

This module implements the main processing functions for microglial fine process motility analysis from 4D and 5D time-lapse multiphoton imaging stacks. It provides utilities for loading TIFF/Zarr data, optional subvolume extraction, 2D and 3D motion correction, spectral unmixing, intensity normalization, contrast adjustments, filtering, segmentation, and computation of motility metrics such as gain, loss, stability, and turnover rate.

The module exposes three high-level entry points:

  • process_stack for single-stack analysis

  • batch_process_stacks for automated project-folder processing

  • batch_collect for aggregation of metrics across datasets

All public functions are documented in detail in the API reference.

motila.motila.batch_collect(PROJECT_Path, ID_list=[], project_tag='TP000', motility_folder='motility_analysis', RESULTS_Path='batch_results', log='')[source]

Collect motility outputs from multiple processed stacks and consolidate them into combined tables.

This function scans all project subfolders, loads the output files generated by the MotilA pipeline (motility metrics, brightness tables, and pixel area summaries), merges them across stacks or animals, and saves the resulting DataFrames into a summary directory.

Parameters:
  • PROJECT_Path (str or Path) – The base directory containing the image stacks.

  • ID_list (list of str, optional) – List of sample or subject IDs to be processed (default is an empty list).

  • project_tag (str, optional) – Tag used to identify project folders (default is “TP000”).

  • motility_folder (str, optional) – Folder name containing motility analysis results (default is “motility_analysis”).

  • RESULTS_Path (str or Path, optional) – Directory where the consolidated results will be saved (default is “batch_results”).

Returns:

Saves three DataFrames as Excel files in the RESULTS_Path directory.

Return type:

None

Notes

Expected folder structure:

ID/
    project_tag*/motility_analysis/projection_center*/

Extracted files include:

  • motility_analysis.xlsx

  • Normalized average brightness of each stack.xlsx

  • pixel area sums.xlsx

The function saves three consolidated DataFrames in RESULTS_Path.

Motility metrics are averaged across projection centers and across time points before export.

Additional excel files are saved as:

  • all_motility.xlsx

  • all_brightness.xlsx

  • all_pixel_area.xlsx

  • average_motility.xlsx.

motila.motila.batch_process_stacks(PROJECT_Path, ID_list=[], project_tag='TP000', reg_tif_file_folder='registered', reg_tif_file_tag='reg', metadata_file='metadata.xls', RESULTS_foldername='../motility_analysis/', group='blinded', MG_channel=0, N_channel=1, two_channel=True, projection_center=50, projection_layers=20, histogram_ref_stack=0, log='', blob_pixel_threshold=100, regStack2d=True, regStack3d=False, template_mode='mean', usepystackreg=False, spectral_unmixing=True, hist_equalization=False, hist_match=True, hist_equalization_kernel_size=None, hist_equalization_clip_limit=0.05, max_xy_shift_correction=50, threshold_method='li', compare_all_threshold_methods=True, gaussian_sigma_proj=1, spectral_unmixing_amplifyer=1, median_filter_slices='square', median_filter_window_slices=3, median_filter_projections='square', median_filter_window_projections=3, clear_previous_results=False, spectral_unmixing_median_filter_window=3, debug_output=False, stats_plots=False)[source]

Batch-processing wrapper that applies the MotilA pipeline to multiple 4D/5D multiphoton imaging stacks.

This function detects all project folders matching a given tag, loads the associated registered stacks, and processes each dataset using process_stack(). The function handles metadata loading, optional registration, spectral unmixing, contrast adjustments, thresholding, and motility extraction. Results for each dataset are written into structured output directories.

Parameters:
  • PROJECT_Path (str or Path) – The base directory containing the image stacks.

  • ID_list (list of str, optional) – List of sample or subject IDs to be processed (default is an empty list).

  • project_tag (str, optional) – Tag used to identify project folders (default is “TP000”).

  • reg_tif_file_folder (str, optional) – Folder name containing registered TIFF files (default is “registered”).

  • reg_tif_file_tag (str, optional) – Tag used to filter for registered TIFF files (default is “reg”).

  • metadata_file (str, optional) – Name of the metadata file to retrieve processing parameters (default is “metadata.xls”).

  • RESULTS_Path (str or Path, optional) – Directory where results will be saved (default is “motility_analysis”).

  • group (str, optional) – Sample group label (default is “blinded”).

  • MG_channel (int, optional) – Channel index for microglial signal (default is 0).

  • N_channel (int, optional) – Channel index for neuronal signal (default is 1).

  • two_channel (bool, optional) – Indicates whether the data contains two channels (default is True).

  • projection_center (int, optional) – Center plane for z-projections (default is 50).

  • projection_layers (int, optional) – Number of layers used for projection (default is 20).

  • histogram_ref_stack (int, optional) – Reference stack index for histogram matching (default is 0).

  • log (object, optional) – Logging object for process tracking (default is an empty string).

  • blob_pixel_threshold (int, optional) – Minimum size of segmented objects to retain (default is 100 pixels).

  • regStack2d (bool, optional) – Whether to perform 2D registration (default is True).

  • regStack3d (bool, optional) – Whether to perform 3D registration (default is False).

  • template_mode (str, optional) – Mode used to generate a reference template for registration (default is “mean”).

  • spectral_unmixing (bool, optional) – Whether to perform spectral unmixing to separate signals (default is True).

  • hist_equalization (bool, optional) – Whether to apply histogram equalization to enhance contrast (default is False).

  • hist_equalization_clip_limit (float) – Clip limit for histogram equalization.

  • hist_equalization_kernel_size (None or tuple of int) – Kernel size for histogram equalization.

  • hist_match (bool, optional) – Whether to match histograms across image stacks (default is True).

  • max_xy_shift_correction (int, optional) – Maximum allowed shift in pixels for image registration (default is 50).

  • threshold_method (str, optional) – Method for binarization thresholding (default is “li”).

  • compare_all_threshold_methods (bool, optional) – Whether to compare multiple thresholding methods (default is True).

  • gaussian_sigma_proj (int, optional) – Sigma value for Gaussian blur applied before binarization (default is 1).

  • spectral_unmixing_amplifyer (int, optional) – Amplification factor for spectral unmixing (default is 1).

  • median_filter_slices (str, optional) – Type of median filtering applied to individual slices (“square” or “circular”) (default is “square”).

  • median_filter_window_slices (int, optional) – Window size for median filtering on slices (default is 3).

  • median_filter_projections (str, optional) – Type of median filtering applied to projections (“square” or “circular”) (default is “square”).

  • median_filter_window_projections (int, optional) – Window size for median filtering on projections (default is 3).

  • clear_previous_results (bool, optional) – Whether to delete previous results before processing (default is False).

  • spectral_unmixing_median_filter_window (int, optional) – Window size for median filtering applied before spectral unmixing (default is 3).

  • debug_output (bool, optional) – Whether to print debug information, including RAM usage (default is False).

  • stats_plots (bool, optional) – Whether to generate additional statistics plots (default is False).

Returns:

The function processes each stack and saves the results in the specified output directory.

Return type:

None

Notes

  • The function scans for project folders and extracts relevant image files.

  • Metadata files, if present, override certain function parameters.

  • Each stack is processed using process_stack().

  • Results are saved in subdirectories within RESULTS_Path, organized by projection center.

motila.motila.process_stack(fname, MG_channel, N_channel, two_channel, projection_center, projection_layers, histogram_ref_stack, log, blob_pixel_threshold=100, regStack2d=True, regStack3d=False, template_mode='mean', usepystackreg=False, spectral_unmixing=True, hist_equalization=False, hist_match=True, hist_equalization_kernel_size=None, hist_equalization_clip_limit=0.05, RESULTS_Path='motility_analysis', ID='ID00000', group='blinded', max_xy_shift_correction=50, threshold_method='li', compare_all_threshold_methods=True, gaussian_sigma_proj=1, spectral_unmixing_amplifyer=1, median_filter_slices='square', median_filter_window_slices=3, median_filter_projections='square', median_filter_window_projections=3, clear_previous_results=False, spectral_unmixing_median_filter_window=3, debug_output=False, stats_plots=False)[source]

Process a single 4D or 5D multiphoton imaging stack and extract microglial motility metrics. This is the main entry point of the MotilA pipeline.

The function loads a TIFF stack, optionally performs 2D or 3D registration, applies spectral unmixing and contrast corrections, generates z-projections, segments microglial structures, and computes motility metrics such as gain, loss and stability. Outputs are written to a structured results directory.

Parameters:
  • fname (str or Path) – Path to the input TIFF file.

  • MG_channel (int) – Index of the microglia fluorescence channel.

  • N_channel (int) – Index of the neuron fluorescence channel.

  • two_channel (bool) – Whether the dataset includes two channels.

  • projection_center (int) – Center slice for z-projection.

  • projection_layers (int) – Number of layers to include in the z-projection.

  • histogram_ref_stack (int) – Stack index to use as reference for histogram matching.

  • log (logger_object) – Logger for recording processing steps.

  • blob_pixel_threshold (int) – Minimum pixel area for segmented objects.

  • regStack2d (bool) – Whether to perform 2D registration on z-projections.

  • regStack3d (bool) – Whether to perform 3D intra-stack registration.

  • usepystackreg (bool, optional) – If True, use pystackreg (StackReg) for 2D registration instead of phase cross-correlation.

  • template_mode (str) – Template calculation method for 3D registration.

  • spectral_unmixing (bool) – Whether to perform spectral unmixing.

  • hist_equalization (bool) – Whether to apply histogram equalization.

  • hist_equalization_clip_limit (float) – Clip limit for histogram equalization.

  • hist_equalization_kernel_size (None or tuple of int) – Kernel size for histogram equalization.

  • hist_match (bool) – Whether to perform histogram matching across stacks.

  • RESULTS_Path (str or Path) – Directory for saving results.

  • ID (str) – Identifier for the dataset.

  • group (str) – Experimental group label.

  • max_xy_shift_correction (int) – Maximum allowed xy-shift in registration.

  • threshold_method (str) – Method for binarization.

  • compare_all_threshold_methods (bool) – Whether to compare multiple thresholding methods.

  • gaussian_sigma_proj (float) – Sigma value for Gaussian filtering before binarization.

  • spectral_unmixing_amplifyer (int) – Amplification factor for spectral unmixing.

  • median_filter_slices (str) – Type of median filtering applied to individual slices (“square” or “circular”).

  • median_filter_window_slices (int) – Size of the median filter applied to individual slices.

  • median_filter_projections (str) – Type of median filtering applied to z-projections (“square” or “circular”).

  • median_filter_window_projections (int) – Size of the median filter applied to z-projections.

  • clear_previous_results (bool) – Whether to clear the results directory before processing.

  • spectral_unmixing_median_filter_window (int) – Window size for median filtering in spectral unmixing.

  • debug_output (bool) – Whether to enable debug output for memory usage and processing steps.

  • stats_plots (bool) – Whether to generate additional statistics plots.

Returns:

The function writes processed images, projections, segmentation masks, motility metrics and auxiliary outputs to RESULTS_Path.

Return type:

None

Notes

  • Loads and processes microglia fluorescence images for motility analysis.

  • Supports optional 3D and 2D registration.

  • 2D registration can use either phase cross-correlation or pystackreg (StackReg) if usepystackreg is True.

  • Includes histogram-based contrast adjustments and thresholding.

  • Computes motility metrics such as gain, loss, and stability.

  • Saves processed images, projections, and statistical results in a designated output directory.

  • Deletes intermediate large datasets to optimize memory usage.

Additional functions

motila.motila.hello_world()[source]

Prints a friendly message to the user.

motila.motila.calc_projection_range(projection_center, projection_layers, I_shape, log)[source]

Calculate a z-projection range for a given center plane and number of layers, ensuring that the range stays within stack boundaries.

Parameters:
  • projection_center (int) – Index of the central z-plane around which the projection is computed.

  • projection_layers (int) – Total number of layers to include in the projection (symmetric around projection_center).

  • I_shape (tuple) – Shape of the input image stack. The second entry must represent the z-dimension.

  • log (object) – Logging object with a log method for recording warnings and information.

Returns:

A tuple (projection_range, projection_layers) where:

  • projection_range : list of int Two-element list [start, end] defining the z-range after boundary correction.

  • projection_layers : int Actual number of layers used in the projection after adjusting for stack limits.

Return type:

tuple

Notes

The projection range is clipped automatically if projection_center ± layers/2 extends beyond stack boundaries. Any correction is reported via log.log().

motila.motila.plot_2D_image(image, plot_path, plot_title, fignum=1, figsize=(5, 5.15), show_ticks=False, show_borders=False, cbar_show=False, cmap=<matplotlib.colors.ListedColormap object>, cbar_label='', cbar_ticks=[], cbar_ticks_labels='', title='')[source]

Plots a 2D image and saves it as a PDF file.

Parameters:
  • image (array-like) – The 2D array representing the image to be plotted.

  • plot_path (str or Path) – The directory path where the plot will be saved.

  • plot_title (str) – The filename for the saved plot (without extension).

  • fignum (int, optional) – The figure number for the plot (default is 1).

  • cmap (matplotlib.colors.Colormap, optional) – The colormap to be used for the image (default is ‘viridis’).

  • cbar_label (str, optional) – The label for the colorbar (default is an empty string).

  • cbar_ticks (list of float, optional) – Tick positions for the colorbar (default is an empty list, meaning automatic ticks).

  • cbar_ticks_labels (list of str, optional) – Labels for the colorbar ticks (default is an empty list, meaning no custom labels).

  • title (str, optional) – The title of the plot (default is an empty string).

Returns:

This function saves the plot as a PDF file and does not return a value.

Return type:

None

Notes

  • The plot is saved in the specified directory as <plot_title>.pdf with a resolution of 500 DPI.

  • A colorbar is added if cbar_label is provided.

  • The

motila.motila.plot_2D_image_as_tif(image, plot_path, plot_title)[source]

Saves a 2D image as a compressed TIFF file.

Parameters:
  • image (array-like) – The 2D array representing the image to be saved.

  • plot_path (str or Path) – The directory where the TIFF file will be saved.

  • plot_title (str) – The filename for the saved TIFF file (without extension).

Returns:

This function saves the image as a TIFF file and does not return a value.

Return type:

None

Notes

  • The file is saved as <plot_title>.tif in the specified directory.

  • The TIFF file is compressed using zlib.

  • The function requires tifffile and os for file handling.

motila.motila.plot_histogram(image, plot_path, plot_title, fignum=1, title='histogram')[source]

Plots the histogram and cumulative distribution function (CDF) of an image and saves it as a PDF file.

Parameters:
  • image (array-like) – The 2D array representing the image for which the histogram is computed.

  • plot_path (str or Path) – The directory where the histogram plot will be saved.

  • plot_title (str) – The filename for the saved histogram plot (without extension).

  • fignum (int, optional) – The figure number for the plot (default is 1).

  • title (str, optional) – The title of the plot (default is “histogram”).

Returns:

The function saves the histogram plot as a PDF file and does not return a value.

Return type:

None

Notes

  • The function computes the histogram and cumulative distribution function (CDF) using skimage.exposure.

  • The plot is saved as <plot_title>.pdf in the specified directory.

  • The function requires matplotlib.pyplot and skimage.exposure for plotting.

motila.motila.plot_histogram_of_projections(image_stack, I_shape, plot_path, log, fignum=1)[source]

Plots histograms for each projected stack in the given image stack and saves them as PDF files.

Parameters:
  • image_stack (array-like) – The stack of 2D images for which histograms will be computed.

  • I_shape (tuple) – The shape of the image stack (assumed to be in TZYX or TCZYX format).

  • plot_path (str or Path) – The directory where the histogram plots will be saved.

  • log (logger_object) – A logging object to record processing steps and timing.

  • fignum (int, optional) – The figure number for plotting (default is 1).

Returns:

The function saves histogram plots for each projected stack as PDF files.

Return type:

None

Notes

  • Each stack slice is processed separately, and its histogram is saved as <plot_title>.pdf.

  • The function logs processing time and status using the provided logger.

  • Uses plot_histogram() internally to generate individual plots.

motila.motila.plot_projected_stack(image_stack, I_shape, plot_path, log, plottitle='MG projected')[source]

Plots and saves z-projected image stacks as grayscale images and a TIFF file.

Parameters:
  • image_stack (array-like) – The stack of 2D projected images to be plotted and saved.

  • I_shape (tuple) – The shape of the image stack, used to determine the number of stacks.

  • plot_path (str or Path) – The directory where the plots and TIFF file will be saved.

  • log (logger_object) – A logging object to record processing steps and execution time.

  • plottitle (str, optional) – The base title for the saved plots and TIFF file (default is “MG projected”).

Returns:

The function saves each projected stack as a grayscale plot and the full stack as a TIFF file.

Return type:

None

Notes

  • Individual stacks are plotted as grayscale images and saved as PDFs.

  • The full image stack is saved as a TIFF file with metadata.

  • The function logs the plotting process and execution time.

motila.motila.plot_projected_stack_as_tif(image_stack, I_shape, plot_path, log, plottitle='MG projected')[source]

Saves z-projected image stacks as TIFF files.

Parameters:
  • image_stack (array-like) – The stack of 2D projected images to be saved as TIFF files.

  • I_shape (tuple) – The shape of the image stack, used to determine the number of stacks.

  • plot_path (str or Path) – The directory where the TIFF files will be saved.

  • log (logger_object) – A logging object to record processing steps and execution time.

  • plottitle (str, optional) – The base title for the saved TIFF files (default is “MG projected”).

Returns:

The function saves each projected stack as an individual TIFF file.

Return type:

None

Notes

  • Each stack is saved as a separate TIFF file with a unique filename.

  • The function logs the saving process and execution time.

motila.motila.get_stack_dimensions(fname)[source]

Retrieves the dimensions of a TIFF image stack without loading the entire dataset (i.e., of all axis, TZCYX or TZYX (ImageJ default order)).

Parameters:

fname (str or Path) – The path to the TIFF file.

Returns:

  • list – A list representing the shape of the image stack, ordered as TZCYX or TZYX.

  • Raises

  • ——-

  • ValueError – If the provided file is not a TIFF file.

Notes

  • The function reads metadata from the TIFF file to determine its dimensions.

  • The file is opened and closed without loading the image into memory.

motila.motila.extract_and_register_subvolume(fname, I_shape, projection_layers, projection_range, MG_channel, log, two_channel, template_mode='mean', max_xy_shift_correction=5, debug_output=False)[source]

Extracts sub-volumes from a multi-dimensional TIFF image stack, registers them using phase cross-correlation, and saves the results in a Zarr format.

Parameters:
  • fname (str or Path) – Path to the TIFF file.

  • I_shape (tuple) – Shape of the input image stack.

  • projection_layers (int) – Number of layers to extract for projection.

  • projection_range (tuple) – The range of layers to be extracted.

  • MG_channel (int) – The channel index corresponding to microglial cells.

  • log (logger_object) – Logging object for recording the process.

  • two_channel (bool) – Whether the image stack contains two channels.

  • template_mode (str, optional) – The method to compute the template for registration. Options: ‘mean’, ‘median’, ‘max’, ‘std’, ‘var’. Default is ‘mean’.

  • max_xy_shift_correction (int, optional) – The maximum allowed shift correction in XY directions (default is 5 pixels).

Returns:

  • tuple

    If two_channel is False:
    • MG_sub_reg_cropped (Zarr dataset): Registered and cropped microglial sub-volume.

    • I_shape_reg (tuple): Shape of the registered dataset.

    • zarr_group (Zarr group): The Zarr group containing the sub-volumes.

    If two_channel is True:
    • MG_sub_reg_cropped (Zarr dataset): Registered and cropped microglial sub-volume.

    • N_sub_reg_cropped (Zarr dataset): Registered and cropped neuronal sub-volume.

    • I_shape_reg (tuple): Shape of the registered dataset.

    • zarr_group (Zarr group): The Zarr group containing the sub-volumes.

  • Raises

  • ——-

  • ValueError – If the provided file is not a TIFF file.

Notes

  • The function extracts sub-volumes using extract_subvolume and applies 3D registration.

  • Registration is performed via phase cross-correlation using a reference template.

  • The function supports multiple template modes, including mean, median, and variance.

  • The final registered volumes are cropped to remove zero-padding caused by shifts.

  • All intermediate datasets are stored in a Zarr format for efficient access.

motila.motila.extract_subvolume(fname, I_shape, projection_layers, projection_range, log, two_channel=False, channel=0)[source]

Extracts sub-volumes from a multi-dimensional TIFF image stack and stores them in a Zarr format.

Parameters:
  • fname (str or Path) – Path to the TIFF file.

  • I_shape (tuple) – Shape of the input image stack.

  • projection_layers (int) – Number of layers to extract for projection.

  • projection_range (tuple) – The range of layers to be extracted.

  • log (logger_object) – Logging object for recording the process.

  • two_channel (bool, optional) – Whether the image stack contains two channels (default is False).

  • channel (int, optional) – The primary channel index to be extracted (default is 0).

Returns:

  • tuple

    If two_channel is False:
    • MG_sub (Zarr dataset): Extracted microglial sub-volume.

    • zarr_group (Zarr group): The Zarr group containing the sub-volumes.

    If two_channel is True:
    • MG_sub (Zarr dataset): Extracted microglial sub-volume.

    • N_sub (Zarr dataset): Extracted neuronal sub-volume.

    • zarr_group (Zarr group): The Zarr group containing the sub-volumes.

  • Raises

  • ——-

  • ValueError – If the provided file is not a TIFF file.

Notes

  • The function converts the TIFF file into a Zarr store for efficient memory access.

  • The extracted sub-volumes are saved in the Zarr format to reduce memory consumption.

  • The function supports both single-channel and two-channel extractions.

motila.motila.spectral_unmix(MG_sub, N_sub, I_shape, zarr_group, projection_layers, log, median_filter_window=3, amplifyer=2)[source]

Performs spectral unmixing to reduce channel bleed-through in microglial image stacks. It requires a microglial and a neuronal channel and spectral unmixing is performed by simple subtraction of the neuronal signal from the microglial signal.

Parameters:
  • MG_sub (Zarr dataset) – The extracted microglial channel sub-volume.

  • N_sub (Zarr dataset) – The extracted neuronal channel sub-volume.

  • I_shape (tuple) – Shape of the input image stack.

  • zarr_group (Zarr group) – The Zarr group containing the sub-volumes.

  • projection_layers (int) – Number of layers used for projection.

  • log (logger_object) – Logging object for recording the process.

  • median_filter_window (int, optional) – Size of the median filter window for noise reduction (default is 3).

  • amplifyer (float, optional) – Amplification factor applied to the neuronal signal before subtraction (default is 2).

Returns:

MG_sub_processed – The spectrally unmixed microglial sub-volume.

Return type:

Zarr dataset

Notes

  • The function applies median filtering and Gaussian smoothing to the neuronal channel.

  • The neuronal signal is scaled and subtracted from the microglial channel to remove bleed-through.

  • Negative values are clipped to zero to avoid artificial signals.

  • Intermediate datasets are deleted after processing to free memory.

motila.motila.histogram_equalization(MG_sub, I_shape, projection_layers, log, clip_limit=0.02)[source]

Applies adaptive histogram equalization to enhance contrast in microglial image stacks.

Parameters:
  • MG_sub (array-like) – The input microglial sub-volume.

  • I_shape (tuple) – Shape of the input image stack.

  • projection_layers (int) – Number of layers used for projection.

  • log (logger_object) – Logging object for recording the process.

  • clip_limit (float, optional) – Clipping limit for contrast limiting adaptive histogram equalization (default is 0.01).

Returns:

MG_sub_histeq – The histogram-equalized microglial sub-volume.

Return type:

ndarray

Notes

  • Adaptive histogram equalization improves local contrast while preventing over-amplification of noise.

  • The function processes each stack slice separately.

  • The input image stack is expected to be of type uint16 before applying equalization.

motila.motila.histogram_equalization_on_projections(MG_sub, I_shape, log, clip_limit=0.01, kernel_size=None)[source]

Applies adaptive histogram equalization to enhance contrast in projected microglial image stacks.

Parameters:
  • MG_sub (array-like) – The input microglial sub-volume projections.

  • I_shape (tuple) – Shape of the input image stack.

  • log (logger_object) – Logging object for recording the process.

  • clip_limit (float, optional) – Clipping limit for contrast limiting adaptive histogram equalization (default is 0.01).

  • kernel_size (tuple or None, optional) – Size of the contextual region for adaptive histogram equalization. If None, the kernel size is automatically determined.

Returns:

MG_sub_histeq – The histogram-equalized projected microglial sub-volume.

Return type:

ndarray

Notes

  • This function enhances contrast in 2D projections of the microglial image stacks.

  • Adaptive histogram equalization prevents over-amplification of noise while improving local contrast.

  • The input image stack is expected to be of type uint16 before applying equalization.

  • Each stack is processed independently to maintain consistency across slices.

motila.motila.histogram_matching(MG_sub, I_shape, histogram_ref_stack, projection_layers, log)[source]

Matches the histogram of each stack in the microglial sub-volume to a reference stack.

Parameters:
  • MG_sub (array-like) – The input microglial sub-volume containing image stacks.

  • I_shape (tuple) – Shape of the input image stack.

  • histogram_ref_stack (int) – Index of the reference stack to which all other stacks’ histograms will be matched.

  • projection_layers (int) – Number of projection layers in the image stack.

  • log (logger_object) – Logging object for recording the process.

Returns:

MG_sub_histeq – The histogram-matched microglial sub-volume.

Return type:

ndarray

Notes

  • Histogram matching ensures that all stacks have similar intensity distributions.

  • This is useful for normalizing intensity variations across different time points or conditions.

  • The reference stack should be representative of the desired intensity distribution.

  • Matching is performed independently for each stack while preserving spatial information.

motila.motila.histogram_matching_on_projections(MG_sub, I_shape, histogram_ref_stack, log)[source]

Matches the histogram of each projected stack to a reference stack.

Parameters:
  • MG_sub (array-like) – The input microglial projections containing image stacks.

  • I_shape (tuple) – Shape of the input image stack.

  • histogram_ref_stack (int) – Index of the reference stack to which all other stacks’ histograms will be matched.

  • log (logger_object) – Logging object for recording the process.

Returns:

MG_sub_histeq – The histogram-matched projected image stacks.

Return type:

ndarray

Notes

  • Histogram matching ensures uniform intensity distribution across all projected stacks.

  • Useful for standardizing contrast across different time points or conditions.

  • The reference stack should be selected based on its representativeness of the desired distribution.

  • Matching is performed independently for each stack while maintaining spatial integrity.

motila.motila.median_filtering_on_projections(MG_sub, I_shape, median_filter_window, log)[source]

Applies a median filter to each projected stack to reduce noise, using a square kernel.

Parameters:
  • MG_sub (array-like) – The input microglial projections containing image stacks.

  • I_shape (tuple) – Shape of the input image stack.

  • median_filter_window (int) – Size of the window for median filtering. If ≤1, filtering is skipped.

  • log (logger_object) – Logging object for recording the process.

Returns:

MG_sub_median – The median-filtered projected image stacks.

Return type:

ndarray

Notes

  • The median filter is a non-linear filter effective for noise removal, especially salt-and-pepper noise.

  • If median_filter_window is ≤1, the function skips filtering and returns the original image.

  • The function ensures spatial coherence while preserving important structural features.

motila.motila.circular_median_filtering_on_projections(MG_sub, I_shape, median_filter_window, log)[source]

Applies a median filter to each projected stack to reduce noise, using a circular kernel.

Parameters:
  • MG_sub (array-like) – The input microglial projections containing image stacks.

  • I_shape (tuple) – Shape of the input image stack.

  • median_filter_window (int) – Radius of the circular structuring element for median filtering. If <1, filtering is skipped.

  • log (logger_object) – Logging object for recording the process.

Returns:

MG_sub_median – The median-filtered projected image stacks.

Return type:

ndarray

Notes

  • Uses a circular structuring element (skimage.morphology.disk) to preserve shape integrity.

  • If median_filter_window < 1, the function skips filtering and returns the original image.

  • Effective for reducing noise while maintaining fine structures.

motila.motila.single_slice_median_filtering(MG_sub, I_shape, zarr_group, median_filter_window, projection_layers, log)[source]

Applies square median filtering to each slice within the projected stacks.

Parameters:
  • MG_sub (array-like) – The input microglial projections containing image stacks.

  • I_shape (tuple) – Shape of the input image stack.

  • zarr_group (zarr group) – The Zarr storage group where the filtered data will be saved.

  • median_filter_window (int) – Size of the square structuring element for median filtering. If <=1, filtering is skipped.

  • projection_layers (int) – Number of slices in each stack.

  • log (logger_object) – Logging object for recording the process.

Returns:

MG_sub_median – The median-filtered image stacks stored in Zarr.

Return type:

zarr dataset

Notes

  • The function checks if median_filter_window is an integer; if not, it defaults to 1 (no filtering).

  • Uses scipy.ndimage.median_filter for noise reduction while preserving structural integrity.

  • If median_filter_window <= 1, filtering is skipped, and the original image is returned.

  • The filtered images are stored in a new dataset MG_sub_median within the Zarr group.

motila.motila.single_slice_circular_median_filtering(MG_sub, I_shape, zarr_group, median_filter_window, projection_layers, log)[source]

Applies circular median filtering to each slice within the projected stacks.

Parameters:
  • MG_sub (array-like) – The input microglial projections containing image stacks.

  • I_shape (tuple) – Shape of the input image stack.

  • zarr_group (zarr group) – The Zarr storage group where the filtered data will be saved.

  • median_filter_window (int) – Radius of the circular structuring element for median filtering. If <1, filtering is skipped.

  • projection_layers (int) – Number of slices in each stack.

  • log (logger_object) – Logging object for recording the process.

Returns:

MG_sub_median – The median-filtered image stacks stored in Zarr.

Return type:

zarr dataset

Notes

  • Uses skimage.morphology.disk to create a circular filter mask.

  • If median_filter_window < 1, filtering is skipped, and the original image is returned.

  • Utilizes skimage.filters.median for noise reduction while preserving structural details.

  • The filtered images are stored in a new dataset MG_sub_median within the Zarr group.

motila.motila.gaussian_blurr_filtering_on_projections(MG_sub, I_shape, gaussian_blurr_sigma, log)[source]

Applies Gaussian blur filtering to each projected stack.

Parameters:
  • MG_sub (array-like) – The input microglial projections containing image stacks.

  • I_shape (tuple) – Shape of the input image stack.

  • gaussian_blurr_sigma (float) – Standard deviation for the Gaussian kernel.

  • log (logger_object) – Logging object for recording the process.

Returns:

MG_sub_gaussian – The Gaussian-blurred image stacks.

Return type:

ndarray

Notes

  • Uses skimage.filters.gaussian to apply Gaussian blurring.

  • Helps in reducing noise while preserving edges to a certain extent.

  • The filter is applied independently to each stack.

motila.motila.single_slice_gaussian_blurr_filtering(MG_sub, I_shape, gaussian_blurr_sigma, projection_layers, log)[source]

Applies Gaussian blur filtering to each individual slice in the image stack.

Parameters:
  • MG_sub (array-like) – The input microglial image stack.

  • I_shape (tuple) – Shape of the input image stack.

  • gaussian_blurr_sigma (float) – Standard deviation for the Gaussian kernel.

  • projection_layers (int) – Number of layers in the projection stack.

  • log (logger_object) – Logging object for recording the process.

Returns:

MG_sub_gaussian – The Gaussian-blurred image stack.

Return type:

ndarray

Notes

  • Uses skimage.filters.gaussian to apply Gaussian blurring.

  • The filter is applied independently to each slice within each stack.

  • Helps in noise reduction while preserving relevant image structures.

motila.motila.z_max_project(MG_sub, I_shape, log)[source]

Computes the maximum intensity Z-projection of an image stack.

Parameters:
  • MG_sub (array-like) – The input microglial image stack.

  • I_shape (tuple) – Shape of the input image stack.

  • log (logger_object) – Logging object for recording the process.

Returns:

MG_pro – The Z-projected image stack using maximum intensity projection.

Return type:

ndarray

Notes

  • This function collapses the Z-dimension by selecting the maximum intensity value for each pixel across all Z-slices.

  • Useful for visualizing microglial structures in a single 2D image.

  • Logs execution time for performance monitoring.

motila.motila.compare_histograms(MG_sub_pre, MG_sub_post, log, plot_path, I_shape, xlim=(0, 6000))[source]

Compares histograms of projected stacks before and after histogram adjustments.

Parameters:
  • MG_sub_pre (array-like) – The image stack before histogram adjustments.

  • MG_sub_post (array-like) – The image stack after histogram adjustments.

  • log (logger_object) – Logging object for recording the process.

  • plot_path (str or Path) – The directory path where the histogram plots will be saved.

  • I_shape (tuple) – Shape of the input image stack.

  • xlim (tuple, optional) – Limits for the x-axis of the histogram (default is (0, 6000)).

Returns:

The function saves the histogram plots as PDF files.

Return type:

None

Notes

  • Each stack’s histogram is plotted and saved separately.

  • The function normalizes intensity values before plotting.

  • Uses a logarithmic scale for better visualization of histogram distributions.

  • Logs execution time for performance monitoring.

motila.motila.plot_intensities(MG_pro, log, plot_path, I_shape)[source]

Plots and saves the normalized average brightness per projected stack.

Parameters:
  • MG_pro (array-like) – The projected image stack.

  • log (logger_object) – Logging object for recording the process.

  • plot_path (str or Path) – The directory path where the plot and data file will be saved.

  • I_shape (tuple) – Shape of the input image stack.

Returns:

intensity_means – Array containing the mean intensity values for each stack.

Return type:

ndarray

Notes

  • The function calculates the average intensity for each projected stack.

  • Normalizes intensity values relative to the first stack.

  • Saves a bar plot of the normalized brightness and an Excel file with values.

  • Includes grid lines for easier comparison.

  • Logs execution time for performance monitoring.

motila.motila.reg_2D_images(MG_pro, I_shape, log, histogram_ref_stack, max_xy_shift_correction=50, median_filter_projections=None, median_filter_window_projections=3, usepystackreg=False)[source]

Registers 2D z-projection images using phase cross-correlation or pystackreg.

Parameters:
  • MG_pro (array-like) – The projected image stack.

  • I_shape (tuple) – Shape of the input image stack.

  • log (logger_object) – Logging object for recording the process.

  • histogram_ref_stack (int) – Index of the reference stack for registration.

  • max_xy_shift_correction (int, optional) – Maximum allowed XY shift during registration (default is 50 pixels).

  • median_filter_projections (str or None, optional) – Type of median filtering applied to projections before registration. Options: “circular”, “square”, or None (default).

  • median_filter_window_projections (int, optional) – Window size for median filtering (default is 3).

  • usepystackreg (bool, optional) – If True, uses pystackreg (StackReg) for registration instead of phase cross-correlation.

Returns:

  • MG_pro_bin_reg_clipped (ndarray) – The registered and cropped image stack.

  • I_shape_create (tuple) – New shape of the registered stack after cropping.

Notes

  • Uses phase cross-correlation or pystackreg for image alignment.

  • Applies median filtering if not previously performed to enhance registration accuracy.

  • Limits shifts to a defined maximum correction range.

  • Clips image borders to remove misaligned zero-padding regions.

  • Logs execution time for performance tracking.

motila.motila.binarize_2D_images(MG_pro, I_shape, log, plot_path, threshold_method='otsu', compare_all_threshold_methods=True, gaussian_sigma_proj=1)[source]

Binarizes 2D z-projection images using various thresholding methods.

Parameters:
  • MG_pro (array-like) – The projected image stack.

  • I_shape (tuple) – Shape of the input image stack.

  • log (logger_object) – Logging object for recording the process.

  • plot_path (str or Path) – Path to save threshold comparison plots.

  • threshold_method (str, optional) – The thresholding method to use. Options include: “isodata”, “otsu”, “li”, “mean”, “minimum”, “triangle”, “yen”, or “auto” (default is “otsu”).

  • compare_all_threshold_methods (bool, optional) – If True, generates plots comparing all thresholding methods (default is True).

  • gaussian_sigma_proj (float, optional) – Standard deviation for Gaussian blurring applied before thresholding (default is 1).

Returns:

MG_pro_bin – The binarized image stack.

Return type:

ndarray

Notes

  • Applies Gaussian blur before thresholding if gaussian_sigma_proj > 0.

  • Supports multiple thresholding methods and can auto-select the best based on Pearson correlation.

  • Saves comparison plots if compare_all_threshold_methods is enabled.

  • Logs execution time and selected thresholding method for each stack.

motila.motila.remove_small_blobs(MG_pro, I_shape, log, plot_path, pixel_threshold=100, stats_plots=False)[source]

Removes small microglial regions based on pixel connectivity and area threshold in segmented 2D images.

Parameters:
  • MG_pro (array-like) – The binarized projected image stack.

  • I_shape (tuple) – Shape of the input image stack.

  • log (logger_object) – Logging object for recording the process.

  • plot_path (str or Path) – Path to save the plots and segmentation statistics.

  • pixel_threshold (int, optional) – Minimum pixel area required to retain a connected region (default is 100).

  • stats_plots (bool, optional) – Whether to generate and save additional statistics plots (default is False).

Returns:

  • MG_pro_bin_area_thresholded (ndarray) – The binarized image stack after removing small regions.

  • MG_pro_bin_area_sum (ndarray) – The total number of pixels retained after thresholding.

Notes

  • Labels and counts connected regions using skimage.measure.label.

  • Segments regions that meet the pixel area threshold.

  • Generates and saves plots of connected component areas, histograms, and final segmentations.

  • Saves statistics on segmented pixel areas as an Excel file.

  • Logs the process and reports the number of retained segments.

motila.motila.plot_pixel_areas(MG_areas, log, plot_path, I_shape)[source]

Plots and saves the detected pixel areas per projected stack.

Parameters:
  • MG_areas (array-like) – The total segmented pixel area per stack.

  • log (logger_object) – Logging object for recording the process.

  • plot_path (str or Path) – Path where the plot and Excel file will be saved.

  • I_shape (tuple) – Shape of the input image stack.

Returns:

The function saves a bar plot and an Excel file with pixel area statistics.

Return type:

None

Notes

  • Normalizes pixel areas relative to stack 0.

  • Saves a bar plot representing relative pixel areas per stack.

  • Outputs an Excel file with absolute and relative pixel areas, including total field-of-view (FOV) area.

  • Logs the process and computation time.

motila.motila.motility(MG_pro, I_shape, log, plot_path, ID='ID00000', group='blinded')[source]

Computes and visualizes microglial motility by analyzing changes in segmented pixel regions over time.

Microglial fine processes are tracked by comparing segmented pixels between consecutive time points. The analysis includes stable, gain, and loss percentages of pixels between stacks.

Microglial fine processes turn-over is calculated as the ratio of gained and lost pixels to the total number of stable, gained, and lost pixels as it is common in the literature (e.g., Nebeling et al., 2023).

Parameters:
  • MG_pro (array-like) – The binarized projected image stacks.

  • I_shape (tuple) – Shape of the input image stack.

  • log (logger_object) – Logging object for recording the process.

  • plot_path (str or Path) – Path where the plots and output data will be saved.

  • ID (str, optional) – Identifier for the dataset (default is “ID00000”).

  • group (str, optional) – Experimental group (default is “blinded”).

Returns:

  • MG_pro_delta_t (array-like) – The computed difference images representing changes between consecutive stacks.

  • summary_df (pandas.DataFrame) – Dataframe summarizing motility metrics, including stable, gain, and loss percentages.

Notes

  • Computes changes in segmented pixels between consecutive time points.

  • Visualizes differences in motility with colormap images and histograms.

  • Saves computed motility differences as a multi-frame TIFF file.

  • Outputs an Excel file summarizing motility metrics.

  • Logs the process and computation time.

Utility functions

MotilA Utilities Module

This module contains utility functions and helper classes used throughout the MotilA pipeline for analyzing microglial fine process motility in 4D/5D image stacks.

Contents:

  • Folder operations (creation, filtering by name)

  • Process timing and logging utilities

  • RAM usage monitoring

  • TIFF file axis verification and correction

  • General system introspection tools

Functions:

  • check_folder_exist_create(path, verbose)

  • getfile()

  • filterfolder_by_string(path_to_folder, search_string)

  • filterfiles_by_string(path_to_folder, search_string)

  • calc_process_time_logger(t0, …)

  • print_ram_usage()

  • print_ram_usage_in_loop()

  • tiff_axes_check_and_correct(fname)

Classes:

  • logger_object: flexible file-based logger with timestamped entries

Note:

This module is designed to be imported into the main MotilA scripts and can also be reused independently for other image processing tasks.

Author: Fabrizio Musacchio Date: September 2023 License: GPL-3.0

motila.utils.calc_process_time_logger(t0, verbose=False, leadspaces='', unit='min', process='')[source]

Calculates the processing time/time difference for a given input time and the current time

Usage:

Process_t0 = time.time() #your process calc_process_time(Process_t0, verbose=True, leadspaces=” “)

Return type:

motila.utils.check_folder_exist_create(path, verbose=True)[source]

Check whether a folder exists at the specified path, and create it if it does not.

Parameters:
  • path (str or Path) – The directory path to check or create.

  • verbose (bool, optional (default=True)) – If True, prints a message indicating whether the folder was created or already exists.

Return type:

None

Notes

  • Ensures the specified folder is available before performing file operations.

  • Useful for logging, output saving, or checkpointing during pipeline execution.

motila.utils.filterfiles_by_string(path_to_folder, search_string)[source]

Scans for files in a specified directory and returns those that match a given search string.

Parameters:
  • path_to_folder (str or Path) – The directory path where files should be searched.

  • search_string (str) – The substring to look for in file names.

Returns:

  • MatchingFiles_Indices (list of int) – Indices of matching files in the sorted directory listing.

  • filelist_matching (list of str) – List of file names that match the search string.

  • filelist (list of str) – Full list of file names in the directory.

Notes

  • Only files (not directories) are considered.

  • The function sorts the file list before filtering.

  • Matching is case-sensitive.

motila.utils.filterfolder_by_string(path_to_folder, search_string)[source]

Scans for folders in a specified directory and returns those that match a given search string.

Parameters:
  • path_to_folder (str or Path) – The directory path where folders should be searched.

  • search_string (str) – The substring to look for in folder names.

Returns:

  • MatchingFolders_Indices (list of int) – Indices of matching folders in the sorted directory listing.

  • folderlist_matching (list of str) – List of folder names that match the search string.

  • folderlist (list of str) – Full list of folder names in the directory.

Notes

  • Only directories (not files) are considered.

  • The function sorts the folder list before filtering.

  • Matching is case-sensitive.

motila.utils.getfile()[source]

Retrieve the name of the currently executing script or fallback to “console” if run interactively.

This function returns the filename of the main Python script. If executed in an interactive environment (e.g., IPython or Jupyter Notebook), it returns the string “console”.

Returns:

The filename of the main executing script or “console” if run interactively.

Return type:

str

Notes

  • Useful for dynamically naming log files or output paths based on the script being executed.

  • Handles edge cases where the script is executed from a shell, notebook, or other environments.

motila.utils.hello_world_utils()[source]

Prints a friendly message to the user.

class motila.utils.logger_object(logger_path='')[source]

Bases: object

Class, that creates a logger object with some base functions:

__init__ initializes the logger object type tells user type of this class object log(input, space) logs input with optional preceding spaces logc(input) logs input with chapter-separator stop stops the logger object and the logging __del__ stops the logger object and the logging before deleting the object

log(input, spaces=0, printconsole=True)[source]
logc(input, printconsole=True)[source]
logt(t0, verbose=True, spaces=0, unit='sec', process='')[source]
stop(printconsole=True)[source]
type()[source]
motila.utils.print_ram_usage(indent=0)[source]

Print the current RAM usage of the process.

This function prints the resident memory usage (RAM) of the current Python process, formatted in megabytes (MB). It is useful for tracking memory consumption at specific checkpoints in a script.

Parameters:

indent (int, optional (default=0)) – Number of spaces to prepend to the output line for indentation.

Returns:

The function prints the RAM usage to the console and does not return any value.

Return type:

None

Notes

  • RAM usage is measured using the psutil library.

  • Output is displayed in MB with two decimal places.

motila.utils.print_ram_usage_in_loop(indent=0)[source]

Print the current RAM usage continuously in a loop-friendly format.

This function is designed to be called repeatedly within a loop to monitor real-time memory usage. It updates the same console line without adding newlines, making it suitable for progress monitoring in iterative processes.

Parameters:

indent (int, optional (default=0)) – Number of spaces to prepend to the output for indentation.

Returns:

The function outputs the current RAM usage to the console and does not return any value.

Return type:

None

Notes

  • RAM usage is measured for the current process.

  • Output is formatted in megabytes (MB) with two decimal places.

motila.utils.tiff_axes_check_and_correct(fname)[source]

Check and correct the axis order of a TIFF file to match TZCYX or TZYX.

This function loads a TIFF file, checks its axis labels (as recorded in ImageJ metadata), and reorders the array to conform to standard axis conventions (TZCYX for 5D, TZYX for 4D). If the axes are already correct, the original file path is returned. If correction is needed, a new TIFF file is saved with the corrected axis order and updated metadata.

Parameters:

fname (str or Path) – Path to the input TIFF file.

Returns:

  • Path – Path to the corrected TIFF file (or the original if no correction was necessary).

  • Raises

  • ——-

  • ValueError – If the TIFF file does not contain the required axes (T, Z, Y, X).

Notes

  • Expected axis order is either TZYX (for single-channel) or TZCYX (for multi-channel).

  • The corrected TIFF is saved in the same folder as the original, prefixed with axes_corrected_.

  • ImageJ metadata and spatial resolution information are preserved in the output file.

  • This is especially useful when handling TIFFs generated by software that may reorder axes.