API referenceο
Core functionsο
Public compatibility layer for the MotilA pipeline.
The implementation is split across focused modules, while this module preserves
MotilAβs historical public import path. Existing scripts can continue importing
functions from motila.motila.
author: Fabrizio Musacchio date: September 2023 ported to modular MotilA: August 2026
- motila.motila.batch_collect(project_root=None, *, subject_ids=None, subject_prefix='ID', tag_folder_levels=None, image_patterns=None, exclude_name_contains=('Preview',), results_folder_name='motility_analysis', organize_by_image=True, RESULTS_Path='batch_results', table_export_formats=('excel',), log=None, verbose=True, PROJECT_Path=None)[source]ο
Collect MotilA outputs using the same BIDS-like discovery as batch processing.
The v1.2.0 collector mirrors
batch_process_stacks(): it discovers the same input files, derives the expected MotilA result folders and aggregatesmotility_analysis.xlsx,Normalized average brightness of each stack.xlsxandpixel area sums.xlsxwhen present.batch_collect_oldkeeps the pre-v1.2.0 collection implementation for migration workflows.- Return type:
BatchCollectionResult
- motila.motila.batch_process_stacks(project_root=None, *, subject_ids=None, subject_prefix='ID', tag_folder_levels=None, image_patterns=None, exclude_name_contains=('Preview',), skip_processed=True, skip_registered=None, results_folder_name='motility_analysis', organize_by_image=True, expected_output_names=('motility_analysis.xlsx',), metadata_file='metadata.xls', load_options=None, processing_options=None, save_options=None, process_function=None, raw_template_metadata=None, write_error_reports=True, write_run_report=True, run_report_name='motila_batch_run_report', continue_on_error=True, log=None, verbose=True, PROJECT_Path=None)[source]ο
Process a flexible BIDS-like MotilA project tree.
This is the v1.2.0 batch processor. It discovers supported microscopy image files below subject folders, applies MotilAβs existing
process_stack()workflow to each discovered image/projection-center pair, skips already processed outputs when requested, and writes persistent run/error reports inproject_root.batch_process_stacks_oldkeeps the pre-v1.2.0 batch implementation for migration workflows.- Return type:
BatchProcessingResult
- 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, table_export_formats=('excel',))[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 an OMIO-supported image 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 image file. Supported formats are TIFF/OME-TIFF, CZI, Thorlabs RAW and LSM.
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.
table_export_formats (str or iterable of str, optional) β Table export formats. Defaults to
("excel",)for backward compatibility. Add"csv"and/or"yaml"to write sidecar plain-text exports next to the default Excel files.
- 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
usepystackregis 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.read_image_stack(fname)[source]ο
Read an image stack with OMIO and return an OME-style
TZCYXimage.Supported input formats are TIFF/OME-TIFF, CZI, Thorlabs RAW and LSM. OMIO normalizes all supported inputs to
TZCYXbefore MotilA receives the array, so downstream processing can use one consistent axis order.
- motila.motila.write_image_stack(fname, image, metadata=None)[source]ο
Write an image with OMIO while preserving MotilAβs historical file names.
OMIO writes OME-TIFF stacks with an
.ome.tifsuffix. If callers request a plain.tifname, the OME-TIFF file is moved back to that requested path so existing scripts and notebooks keep working.
- 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
logmethod 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/2extends beyond stack boundaries. Any correction is reported vialog.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 an OME-TIFF file.
- Parameters:
image (array-like) β The 2D array representing the image to be saved.
plot_path (str or Path) β The directory where the image file will be saved.
plot_title (str) β The filename for the saved image file (without extension).
- Returns:
This function saves the image as an image file and does not return a value.
- Return type:
None
Notes
The file is saved as <plot_title>.tif in the specified directory.
The image is written through OMIO while preserving the historical .tif filename.
- 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 an OME-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 image 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 image file (default is βMG projectedβ).
- Returns:
The function saves each projected stack as a grayscale plot and the full stack as an image file.
- Return type:
None
Notes
Individual stacks are plotted as grayscale images and saved as PDFs.
The full image stack is saved as an image 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 OME-TIFF files.
- Parameters:
image_stack (array-like) β The stack of 2D projected images to be saved as image 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 image 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 image files (default is βMG projectedβ).
- Returns:
The function saves each projected stack as an individual image file.
- Return type:
None
Notes
Each stack is saved as a separate image 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 an image stack after OMIO normalization.
- Parameters:
fname (str or Path) β The path to the image file.
- Returns:
list β A list representing the shape of the image stack, ordered as TZCYX.
Raises
ββ-
ValueError β If the provided file format is not supported.
Notes
OMIO normalizes TIFF, CZI, RAW and LSM inputs to TZCYX.
Some formats require reading the image data to determine the normalized shape.
- 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, image_stack=None, image_metadata=None)[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 image 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 supported image 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, image_stack=None, image_metadata=None)[source]ο
Extracts sub-volumes from a multi-dimensional image stack and stores them in a Zarr format.
- Parameters:
fname (str or Path) β Path to the image file.
I_shape (tuple) β Shape of the input image stack in OMIO-normalized TZCYX order.
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 image file format is not supported.
Notes
The function converts the OMIO-normalized image stack 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, table_export_formats=('excel',))[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 and table file(s) with the normalized brightness 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, table_export_formats=('excel',))[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, table_export_formats=('excel',))[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 table file(s) 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', table_export_formats=('excel',))[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 image file.
Outputs table file(s) 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.
- class motila.utils.logger_object(logger_path='')[source]ο
Bases:
objectClass, 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
- 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.