API#
Functions, broken down by category.
Run Suite2p#
- lbm_suite2p_python.pipeline(input_data, save_path: str | Path = None, ops: dict = None, planes: list | int = None, roi_mode: int = None, keep_reg: bool = True, keep_raw: bool = False, force_reg: bool = False, force_detect: bool = False, num_timepoints: int = None, dff_window_size: int = None, dff_percentile: int = 20, dff_smooth_window: int = None, cell_filters: list = None, accept_all_cells: bool = False, save_json: bool = False, reader_kwargs: dict = None, writer_kwargs: dict = None, roi: int = None, num_frames: int = None, **kwargs) list[Path][source]#
Unified Suite2p processing pipeline.
Wrapper around run_volume (for 4D data) and run_plane (for 3D data). Automatically detects input type and delegates processing.
- Parameters:
- input_datastr, Path, list, or lazy array
Input data source (file, directory, list of files, or array).
- save_pathstr or Path, optional
Output directory.
- opsdict, optional
Suite2p parameters.
- planesint or list, optional
Planes to process (1-based index).
- roi_modeint, optional
ROI mode for ScanImage data (None=stitch, 0=split, N=single).
- keep_reg, keep_rawbool
Keep binary files.
- force_reg, force_detectbool
Force re-processing.
- num_timepointsint, optional
Limit frames.
- dff_window_size, dff_percentile, dff_smooth_windowoptional
dF/F parameters.
- cell_filterslist, optional
Filters to apply. Default is 4-35um diameter if None. Pass [] to disable.
- accept_all_cellsbool
Mark all detected ROIs as accepted.
- **kwargs
Additional args passed to sub-functions.
- Returns:
- list[Path]
List of paths to produced ops.npy files.
- lbm_suite2p_python.run_plane(input_data, save_path: str | Path | None = None, ops: dict | str | Path = None, chan2_file: str | Path | None = None, keep_raw: bool = False, keep_reg: bool = True, force_reg: bool = False, force_detect: bool = False, dff_window_size: int = None, dff_percentile: int = 20, dff_smooth_window: int = None, accept_all_cells: bool = False, cell_filters: list = None, save_json: bool = False, plane_name: str | None = None, reader_kwargs: dict = None, writer_kwargs: dict = None, **kwargs) Path[source]#
Processes a single imaging plane using suite2p.
Handles registration, segmentation, filtering, dF/F calculation, and plotting. Now accepts both file paths and lazy arrays.
- Parameters:
- input_datastr, Path, or lazy array
Input data. Can be a file path or an mbo_utilities lazy array.
- save_pathstr or Path, optional
Root directory to save the results. A subdirectory will be created based on the input filename or plane_name parameter.
- opsdict, str or Path, optional
Path to or dict of user‐supplied ops.npy.
- chan2_filestr, optional
Path to structural / anatomical data used for registration.
- keep_rawbool, default False
If True, do not delete the raw binary (data_raw.bin) after processing.
- keep_regbool, default True
If True, keep the registered binary (data.bin) after processing.
- force_regbool, default False
If True, force a new registration.
- force_detectbool, default False
If True, force ROI detection.
- dff_window_sizeint, optional
Frames for rolling percentile baseline. Default: auto-calculated (~10*tau*fs).
- dff_percentileint, default 20
Percentile for baseline F0.
- dff_smooth_windowint, optional
Smoothing window for dF/F. Default: auto-calculated.
- accept_all_cellsbool, default False
If True, mark all detected ROIs as accepted cells.
- cell_filterslist[dict], optional
Filters to apply to detected ROIs (e.g. diameter, area). Default: [{“name”: “max_diameter”, “min_diameter_um”: 4, “max_diameter_um”: 35}] Pass [] to disable default filtering.
- save_jsonbool, default False
Save ops as JSON.
- plane_namestr, optional
Custom name for the plane subdirectory.
- reader_kwargsdict, optional
Arguments for mbo_utilities.imread.
- writer_kwargsdict, optional
Arguments for binary writing.
- **kwargsdict
Additional arguments passed to Suite2p.
- Returns:
- Path
Path to the saved ops.npy file.
- lbm_suite2p_python.run_volume(input_data, save_path: str | Path = None, ops: dict | str | Path = None, planes: list | int = None, keep_reg: bool = True, keep_raw: bool = False, force_reg: bool = False, force_detect: bool = False, dff_window_size: int = None, dff_percentile: int = 20, dff_smooth_window: int = None, accept_all_cells: bool = False, cell_filters: list = None, save_json: bool = False, reader_kwargs: dict = None, writer_kwargs: dict = None, **kwargs)[source]#
Processes a full volumetric imaging dataset using Suite2p.
Iterates over 3D planes (z-stacks) within the volume, calling run_plane() for each. Aggregates results into volume_stats.npy and generates volumetric plots.
- Parameters:
- input_datalist, Path, or lazy array
Input data source. - List of paths: [plane1.tif, plane2.tif, …] - Lazy array: 4D array (Time, Z, Y, X)
- save_pathstr or Path, optional
Base directory to save outputs.
- opsdict, optional
Suite2p parameters.
- planeslist or int, optional
Specific planes to process (1-based index).
- keep_regbool, default True
Keep registered binaries.
- keep_rawbool, default False
Keep raw binaries.
- force_regbool, default False
Force re-registration.
- force_detectbool, default False
Force detection.
- dff_window_size, dff_percentile, dff_smooth_windowoptional
dF/F calculation parameters.
- accept_all_cellsbool, default False
Mark all ROIs as accepted.
- cell_filterslist, optional
Filters to apply (see run_plane).
- save_jsonbool, default False
Save ops as JSON.
- **kwargs
Additional args passed to run_plane.
- Returns:
- list[Path]
List of paths to ops.npy files for processed planes.
- lbm_suite2p_python.default_ops(metadata=None, ops=None)[source]#
Returns default ops for Suite2P processing on Light Beads Microscopy datasets.
Main changes to defaults:
anatomical_only=3 diameter=6 spatial_hp_cp=0.5 cellprob_threshold=-6 flow_threshold=0 spatial_scale=1 tau=1.3
- Parameters:
- metadatadict, optional
Metadata dictionary containing information about the dataset.
- opsdict, str or Path, optional
Path to or dict of suite2p ops.
- Returns:
- dict
Default ops for Suite2P processing.
Examples
>>> import lbm_suite2p_python as lsp >>> metadata = mbo.get_metadata("D://demo//raw_data//raw_file_00001.tif") # noqa >>> lsp.run_plane( >>> ops=ops, >>> input_tiff="D://demo//raw_data//raw_file_00001.tif", >>> save_path="D://demo//results", >>> save_folder="v1" >>> )
- lbm_suite2p_python.add_processing_step(ops, step_name, input_files=None, duration_seconds=None, extra=None)#
Add a processing step to ops[“processing_history”].
Each step is appended to the history list, preserving previous runs. This allows tracking of re-runs and incremental processing.
- Parameters:
- opsdict
The ops dictionary to update.
- step_namestr
Name of the processing step (e.g., “binary_write”, “registration”, “detection”).
- input_fileslist of str, optional
List of input file paths for this step.
- duration_secondsfloat, optional
How long this step took.
- extradict, optional
Additional metadata for this step.
- Returns:
- dict
The updated ops dictionary.
Load Results#
- lbm_suite2p_python.load_ops(ops_input: str | Path | list[str | Path]) dict[source]#
Load a Suite2p ops.npy file.
Uses cross-platform loader to handle ops.npy files created on different operating systems (Windows vs Linux/Mac Path objects in pickled data).
- Parameters:
- ops_inputstr, Path, or dict
Path to ops.npy file, directory containing ops.npy, or an already-loaded ops dict.
- Returns:
- dict
Suite2p operations dictionary containing pipeline parameters and results metadata.
- lbm_suite2p_python.load_planar_results(ops: dict | str | Path, z_plane: list | int = None) dict[source]#
Load stat, iscell, spks files and return as a dict. Does NOT filter by valid cells, arrays contain both accepted and rejected neurons. Filter for accepted-only via
iscell_mask = iscell[:, 0].astype(bool).- Parameters:
- opsdict, str or Path
Dict of or path to the ops.npy file. Can be a fully qualified path or a directory containing ops.npy.
- z_planeint or None, optional
the z-plane index for this file. If provided, it is stored in the output.
- Returns:
- dict
Dictionary with keys: ‘F’ (fluorescence traces, n_rois x n_frames), ‘Fneu’ (neuropil fluorescence), ‘spks’ (deconvolved spikes), ‘stat’ (ROI statistics array), ‘iscell’ (classification array where column 0 is 0/1 rejected/accepted and column 1 is probability), and ‘z_plane’ (z-plane index array).
See also
lbm_suite2p_python.load_opslbm_suite2p_python.load_traces
- lbm_suite2p_python.get_results(path, include_traces=True)[source]#
Load segmentation results from Suite2p or Cellpose format.
Returns a normalized dictionary with consistent structure regardless of input format. Useful for downstream analysis and GUI integration.
- Parameters:
- pathstr or Path
Path to results directory (containing stat.npy/ops.npy for Suite2p, or masks.npy/_seg.npy for Cellpose).
- include_tracesbool, default True
Whether to load fluorescence traces (F, Fneu, spks) if available.
- Returns:
- dict
Normalized results dictionary with keys: - format: str - “suite2p”, “cellpose”, or “unknown” - path: Path - source directory - stat: ndarray - ROI statistics (Suite2p format) - masks: ndarray - label image (Cellpose format) - iscell: ndarray - cell classification (n_rois, 2) - n_rois: int - number of ROIs - shape: tuple - (Ly, Lx) image dimensions - image: ndarray - mean/max projection image - F: ndarray - fluorescence traces (if available) - Fneu: ndarray - neuropil traces (if available) - spks: ndarray - deconvolved spikes (if available) - dff: ndarray - dF/F traces (if available) - ops: dict - Suite2p ops dictionary (if available) - seg_file: Path - path to _seg.npy file (for cellpose GUI)
Examples
>>> import lbm_suite2p_python as lsp >>> results = lsp.get_results("path/to/suite2p/plane0") >>> print(f"Found {results['n_rois']} ROIs") >>> masks = results['masks'] # always available >>> stat = results['stat'] # always available
Cellpose / HITL Workflow#
Functions for human-in-the-loop cell detection using Cellpose.
- lbm_suite2p_python.redetect(suite2p_path: str | Path, model_path: str | Path = None, masks_path: str | Path = None, diameter: float = None, flow_threshold: float = 0.4, cellprob_threshold: float = 0.0, min_size: int = 15, neucoeff: float = 0.7, run_extraction: bool = True, run_classification: bool = True, run_spikes: bool = True, overwrite: bool = True) Path[source]#
Re-run detection on existing registered data with a new model or masks.
Uses existing registration (data.bin) and re-runs ROI detection with either a trained cellpose model or pre-computed masks. Then extracts fluorescence traces, runs classification, and computes spikes.
- Parameters:
- suite2p_pathstr or Path
Path to Suite2p plane directory containing ops.npy and data.bin.
- model_pathstr or Path, optional
Path to trained cellpose model. If provided, runs cellpose detection.
- masks_pathstr or Path, optional
Path to pre-computed masks (masks.npy or _seg.npy). If provided, uses these masks directly instead of running cellpose.
- diameterfloat, optional
Cell diameter for cellpose. If None, auto-estimates.
- flow_thresholdfloat, default 0.4
Cellpose flow threshold.
- cellprob_thresholdfloat, default 0.0
Cellpose cell probability threshold.
- min_sizeint, default 15
Minimum cell size in pixels.
- neucoefffloat, default 0.7
Neuropil coefficient for trace extraction.
- run_extractionbool, default True
Extract fluorescence traces (F, Fneu).
- run_classificationbool, default True
Run ROI classifier.
- run_spikesbool, default True
Run spike deconvolution.
- overwritebool, default True
Overwrite existing stat.npy, F.npy, etc.
- Returns:
- Path
Path to updated ops.npy file.
See also
pipelineFull processing pipeline
train_cellposeTrain custom cellpose model
cellposeRun cellpose detection directly
Examples
Re-detect with a trained model:
>>> import lbm_suite2p_python as lsp >>> >>> # After training a custom model >>> model = lsp.train_cellpose("training_data/", model_name="my_model") >>> >>> # Re-detect on existing pipeline output >>> lsp.redetect("output/plane01", model_path=model)
Re-detect with pre-computed masks from lsp.cellpose():
>>> # Run cellpose separately >>> result = lsp.cellpose("data.zarr", planes=[1]) >>> >>> # Use those masks for extraction >>> lsp.redetect("output/plane01", masks_path=result["save_path"] / "masks.npy")
- lbm_suite2p_python.enhance_summary_image(suite2p_path: str | Path, method: Literal['meanImg', 'meanImgE', 'max_proj', 'log_ratio', 'correlation'] = 'meanImgE', output_path: str | Path = None, denoise: bool = True, spatial_hp: int = 0, percentile_range: tuple = (1, 99)) Path[source]#
Create or enhance a summary image for cellpose annotation.
Extracts or computes a summary image from Suite2p outputs, optionally applying enhancements to improve cellpose detection.
- Parameters:
- suite2p_pathstr or Path
Path to Suite2p plane directory containing ops.npy.
- methodstr, default “meanImgE”
Summary image type: - “meanImg”: Raw mean image - “meanImgE”: Enhanced mean (spatial high-pass) - “max_proj”: Maximum projection (binned + temporal HP) - “log_ratio”: log(max_proj / meanImg) - emphasizes active regions - “correlation”: Vcorr correlation image (if available)
- output_pathstr or Path, optional
Output file path. Defaults to suite2p_path/enhanced_{method}.tif.
- denoisebool, default True
Apply PCA denoising to reduce noise.
- spatial_hpint, default 0
Spatial high-pass filter size. 0 to disable.
- percentile_rangetuple, default (1, 99)
Percentile range for intensity normalization.
- Returns:
- Path
Path to the saved enhanced image.
See also
annotatePrepare images for annotation from raw data
export_for_guiExport existing Suite2p results for GUI
Examples
>>> import lbm_suite2p_python as lsp >>> >>> # After initial pipeline run, enhance the summary image >>> img_path = lsp.enhance_summary_image( ... "output/plane01", ... method="log_ratio", ... denoise=True, ... ) >>> >>> # Open in cellpose GUI for annotation >>> lsp.open_in_gui(img_path)
- lbm_suite2p_python.train_cellpose(train_dir: str | Path, test_dir: str | Path = None, model_name: str = 'lbm_custom', learning_rate: float = 1e-05, weight_decay: float = 0.1, n_epochs: int = 100, batch_size: int = 1, min_train_masks: int = 5, save_every: int = 100, save_each: bool = False, mask_filter: str = '_masks', image_filter: str = None, gpu: bool = True, normalize: bool = True) Path[source]#
Train/fine-tune a Cellpose model on your data.
Fine-tunes the cpsam (Cellpose-SAM) model on your labeled images. The trained model can then be used with
lsp.pipeline()orlsp.cellpose()by passing the model path aspretrained_modelormodel_type.Note
Currently only fine-tuning from cpsam is supported. Custom base models are not yet available.
- Parameters:
- train_dirstr or Path
Directory containing training images and masks. Images should be named like
image.tifwith correspondingimage_masks.tif(or usemask_filterto specify a different suffix). Can also use GUI annotations (image_seg.npy) withmask_filter="_seg.npy".- test_dirstr or Path, optional
Directory containing test images and masks for validation. If None, no validation is performed during training.
- model_namestr, default “lbm_custom”
Name for the trained model. The model will be saved to
{train_dir}/models/{model_name}.- learning_ratefloat, default 1e-5
Learning rate for training. The default is optimized for fine-tuning.
- weight_decayfloat, default 0.1
L2 regularization weight decay.
- n_epochsint, default 100
Number of training epochs.
- batch_sizeint, default 1
Batch size for training. Keep small (1-2) for fine-tuning.
- min_train_masksint, default 5
Minimum number of masks an image must have to be included in training.
- save_everyint, default 100
Save checkpoint every N epochs.
- save_eachbool, default False
If True, save a separate checkpoint file for each epoch.
- mask_filterstr, default “_masks”
Suffix for mask files. Use
"_seg.npy"for GUI annotations.- image_filterstr, optional
Suffix for image files (e.g.,
"_img"forwells_000_img.tif).- gpubool, default True
Use GPU if available.
- normalizebool, default True
Normalize images during training.
- Returns:
- Path
Path to the trained model file.
See also
prepare_training_dataOrganize pipeline outputs for training
cellposeRun segmentation with trained model
open_in_guiOpen images for manual annotation
Examples
Basic training workflow:
>>> import lbm_suite2p_python as lsp >>> >>> # 1. prepare your training data (images + masks in a folder) >>> # 2. train the model >>> model_path = lsp.train_cellpose( ... train_dir="D:/training_data", ... test_dir="D:/test_data", ... model_name="my_neurons", ... n_epochs=200, ... ) >>> >>> # 3. use the trained model >>> result = lsp.cellpose( ... "D:/new_data", ... model_type=str(model_path), ... )
Using GUI annotations for training:
>>> # after annotating images in cellpose gui, train with _seg.npy files >>> model_path = lsp.train_cellpose( ... train_dir="D:/annotated_images", ... mask_filter="_seg.npy", ... model_name="gui_trained", ... )
- lbm_suite2p_python.annotate(input_data, save_path: str | Path = None, planes: list | int = None, projection: Literal['max', 'mean', 'std'] = 'max', reader_kwargs: dict = None) Path[source]#
Prepare images for annotation in cellpose GUI.
Computes projections from input data and saves them in a format ready for manual annotation in the cellpose GUI. After annotating, the resulting
_seg.npyfiles can be used for training.- Parameters:
- input_datastr, Path, or array
Input data (same formats as
lsp.cellpose()).- save_pathstr or Path, optional
Output directory for projection images.
- planesint or list, optional
Which planes to prepare (1-indexed).
- projectionstr, default “max”
Projection method for time series.
- reader_kwargsdict, optional
Arguments passed to mbo_utilities.imread().
- Returns:
- Path
Path to directory containing images ready for annotation.
See also
open_in_guiLaunch cellpose GUI
train_cellposeTrain model on annotated data
Examples
Prepare images for annotation:
>>> import lbm_suite2p_python as lsp >>> >>> # 1. prepare projections >>> annotation_dir = lsp.annotate("D:/data.zarr", planes=[5, 10, 15]) >>> >>> # 2. open in gui and annotate (draws masks, saves _seg.npy) >>> lsp.open_in_gui(annotation_dir) >>> >>> # 3. train on annotations >>> model_path = lsp.train_cellpose(annotation_dir, mask_filter="_seg.npy")
- lbm_suite2p_python.open_in_gui(path: str | Path = None, image: ndarray = None, masks: ndarray = None, seg_path: str | Path = None)[source]#
Open cellpose GUI for viewing results or annotating images.
This function launches the cellpose GUI for: - Viewing existing segmentation results - Manually annotating images to create training data - Correcting automatic segmentations
- Parameters:
- pathstr or Path, optional
Path to open. Can be: - Directory containing .tif images (for annotation) - Directory containing _seg.npy files (to view/edit results) - Path to specific _seg.npy file - Path to specific image file
- imagendarray, optional
Image array to open directly (without file).
- masksndarray, optional
Masks to overlay on image (requires image parameter).
- seg_pathstr or Path, optional
Deprecated. Use
pathinstead.
See also
annotatePrepare images for annotation
train_cellposeTrain model on annotated data
save_gui_resultsSave results in GUI-compatible format
Notes
Requires cellpose to be installed with GUI dependencies:
pip install cellpose[gui]
Training workflow: 1. Prepare images with
lsp.annotate()or save projections as .tif 2. Open withlsp.open_in_gui(path)3. Draw cell masks: Ctrl+click to start, click to add points, Enter to finish 4. Delete masks: select + Delete key 5. Save annotations: Ctrl+S (creates _seg.npy files) 6. Train model:lsp.train_cellpose(path, mask_filter='_seg.npy')Examples
Open a directory of images for annotation:
>>> import lbm_suite2p_python as lsp >>> lsp.open_in_gui("D:/annotations")
View existing segmentation results:
>>> lsp.open_in_gui("D:/results/cellpose")
Open a specific file:
>>> lsp.open_in_gui("D:/results/projection_seg.npy")
- lbm_suite2p_python.prepare_training_data(source_dirs: list | str | Path, output_dir: str | Path, projection: Literal['max', 'mean', 'std'] = 'max', use_seg_files: bool = True, use_mask_files: bool = True, copy_images: bool = True, image_suffix: str = '.tif') Path[source]#
Prepare training data from pipeline outputs or annotated images.
Collects images and masks from multiple source directories and organizes them into the format expected by
train_cellpose(). This is useful for combining annotations from multiple experiments.- Parameters:
- source_dirslist, str, or Path
Directory or list of directories containing: -
*_seg.npyfiles (cellpose GUI annotations), and/or -*_masks.tiffiles with corresponding images -projection*.tifor other image files- output_dirstr or Path
Output directory for organized training data.
- projectionstr, default “max”
If source has time-series data, which projection to use.
- use_seg_filesbool, default True
Look for
_seg.npyfiles (GUI annotations).- use_mask_filesbool, default True
Look for
_masks.tiformasks*.npyfiles.- copy_imagesbool, default True
Copy image files to output directory. If False, creates symlinks.
- image_suffixstr, default “.tif”
Suffix for output image files.
- Returns:
- Path
Path to output directory ready for training.
See also
train_cellposeTrain model on prepared data
save_gui_resultsSave results in GUI-compatible format
Examples
Collect training data from multiple pipeline runs:
>>> import lbm_suite2p_python as lsp >>> >>> # collect from multiple annotated folders >>> train_dir = lsp.prepare_training_data( ... source_dirs=[ ... "D:/experiment1/cellpose", ... "D:/experiment2/cellpose", ... ], ... output_dir="D:/training_data", ... ) >>> >>> # train on collected data >>> model_path = lsp.train_cellpose(train_dir)
Format Conversion#
- lbm_suite2p_python.export_for_gui(suite2p_dir, output_path=None, name=None)[source]#
Export Suite2p results for Cellpose GUI editing.
Creates a _seg.npy file that can be opened directly in Cellpose GUI. The cellpose GUI expects files with names ending in ‘_seg.npy’.
- Parameters:
- suite2p_dirstr or Path
Suite2p plane directory containing stat.npy and ops.npy.
- output_pathstr or Path, optional
Output directory. Defaults to suite2p_dir.
- namestr, optional
Base name for output files. Defaults to ‘projection’. Creates {name}.tif and {name}_seg.npy.
- Returns:
- Path
Path to the created _seg.npy file.
Examples
>>> import lbm_suite2p_python as lsp >>> seg_file = lsp.conversion.export_for_gui("path/to/suite2p/plane0") >>> lsp.cellpose.open_in_gui(seg_file) # opens in cellpose GUI
- lbm_suite2p_python.import_from_gui(seg_file, original_dir, output_dir=None, update_in_place=False)[source]#
Import edited results from Cellpose GUI back to Suite2p format.
- Parameters:
- seg_filestr or Path
Path to edited _seg.npy from Cellpose GUI.
- original_dirstr or Path
Original Suite2p directory (for ops, traces).
- output_dirstr or Path, optional
Output directory. If None and update_in_place=False, creates ‘edited’ subdir.
- update_in_placebool
If True, overwrites original stat.npy and iscell.npy.
- Returns:
- dict
Import result with change summary.
- lbm_suite2p_python.ensure_cellpose_format(path, force=False)[source]#
Ensure a _seg.npy file exists for cellpose GUI compatibility.
If the path contains Suite2p results without a _seg.npy file, creates one using export_for_gui().
- Parameters:
- pathstr or Path
Path to results directory.
- forcebool, default False
If True, recreate _seg.npy even if it exists.
- Returns:
- Path
Path to the _seg.npy file.
- lbm_suite2p_python.detect_format(path)[source]#
Detect whether path contains Suite2p or Cellpose results.
- Parameters:
- pathstr or Path
Directory to check.
- Returns:
- str
“suite2p”, “suite2p_minimal”, “cellpose”, or “unknown”
- lbm_suite2p_python.masks_to_stat(masks: ndarray, image: ndarray = None) ndarray[source]#
Convert cellpose masks to suite2p stat array.
- Parameters:
- masksndarray
2D or 3D label image (0=background, 1,2,…=roi ids).
- imagendarray, optional
Original image for intensity statistics.
- Returns:
- ndarray
Array of stat dictionaries compatible with suite2p.
ROI Filtering#
- lbm_suite2p_python.postprocessing.apply_filters(plane_dir=None, iscell=None, stat=None, ops=None, filters: list = None, save: bool = False)[source]#
Apply multiple cell filters in sequence.
Chains filter functions together, passing the filtered iscell from each step to the next. All filters use a consistent interface.
- Parameters:
- plane_dirstr or Path, optional
Path to Suite2p plane directory. If provided, loads iscell, stat, ops.
- iscellnp.ndarray, optional
Cell classification array.
- statnp.ndarray or list, optional
Suite2p stat array.
- opsdict, optional
Suite2p ops dictionary.
- filterslist of dict
List of filter configurations. Each dict must have: - ‘name’: str - filter function name (e.g., ‘max_diameter’, ‘area’, ‘eccentricity’) - Additional keys are passed as kwargs to the filter function.
Available filters: - ‘diameter’: filter_by_diameter (min_mult, max_mult) - ‘max_diameter’: filter_by_max_diameter (max_diameter_um, max_diameter_px, min_diameter_um, min_diameter_px) - ‘area’: filter_by_area (min_area_px, max_area_px, min_mult, max_mult) - ‘eccentricity’: filter_by_eccentricity (max_ratio, min_ratio)
- savebool, default False
If True, save final filtered iscell.npy to plane_dir.
- Returns:
- iscell_filterednp.ndarray
Final filtered iscell array (1D boolean).
- total_removednp.ndarray
Boolean mask of all ROIs removed by any filter.
- filter_resultslist of dict
Results from each filter, including removed_mask and info.
Examples
>>> # Apply multiple filters >>> iscell, removed, results = apply_filters( ... plane_dir="path/to/plane01", ... filters=[ ... {"name": "max_diameter", "max_diameter_um": 22}, ... {"name": "area", "min_mult": 0.25, "max_mult": 4.0}, ... {"name": "eccentricity", "max_ratio": 5.0}, ... ], ... save=True ... )
>>> # Use with pre-loaded data >>> iscell, removed, results = apply_filters( ... iscell=iscell, stat=stat, ops=ops, ... filters=[{"name": "max_diameter", "max_diameter_px": 30}] ... )
- lbm_suite2p_python.postprocessing.filter_by_diameter(plane_dir=None, iscell=None, stat=None, ops=None, min_mult: float = 0.3, max_mult: float = 3.0, save: bool = False)[source]#
Filter cells by diameter relative to median diameter.
Sets iscell=False for ROIs whose radius is outside [min_mult, max_mult] times the median diameter (from ops[‘diameter’] or computed from radii).
- Parameters:
- plane_dirstr or Path, optional
Path to Suite2p plane directory. If provided, loads iscell, stat, ops.
- iscellnp.ndarray, optional
Cell classification array (n_rois,) or (n_rois, 2).
- statnp.ndarray or list, optional
Suite2p stat array with ROI statistics.
- opsdict, optional
Suite2p ops dictionary.
- min_multfloat, default 0.3
Minimum diameter as multiple of median.
- max_multfloat, default 3.0
Maximum diameter as multiple of median.
- savebool, default False
If True, save updated iscell.npy to plane_dir.
- Returns:
- iscell_filterednp.ndarray
Updated iscell array (1D boolean).
- removed_masknp.ndarray
Boolean mask of ROIs that were removed.
- infodict
Dictionary with ‘diameters_px’, ‘lower_px’, ‘upper_px’, ‘n_removed’.
- lbm_suite2p_python.postprocessing.filter_by_max_diameter(plane_dir=None, iscell=None, stat=None, ops=None, max_diameter_um: float = None, max_diameter_px: float = None, min_diameter_um: float = None, min_diameter_px: float = None, pixel_size_um: float = None, save: bool = False)[source]#
Filter cells by diameter bounds in microns or pixels.
Sets iscell=False for ROIs whose diameter is outside the specified bounds. Diameter is computed as 2 * radius from the ellipse fit.
- Parameters:
- plane_dirstr or Path, optional
Path to Suite2p plane directory. If provided, loads iscell, stat, ops.
- iscellnp.ndarray, optional
Cell classification array (n_rois,) or (n_rois, 2).
- statnp.ndarray or list, optional
Suite2p stat array with ROI statistics.
- opsdict, optional
Suite2p ops dictionary.
- max_diameter_umfloat, optional
Maximum allowed diameter in microns.
- max_diameter_pxfloat, optional
Maximum allowed diameter in pixels.
- min_diameter_umfloat, optional
Minimum allowed diameter in microns.
- min_diameter_pxfloat, optional
Minimum allowed diameter in pixels.
- pixel_size_umfloat, optional
Pixel size in microns. If None, attempts to read from ops.
- savebool, default False
If True, save updated iscell.npy to plane_dir.
- Returns:
- iscell_filterednp.ndarray
Updated iscell array (1D boolean).
- removed_masknp.ndarray
Boolean mask of ROIs that were removed.
- infodict
Dictionary with ‘diameters_px’, ‘min_px’, ‘max_px’, ‘n_removed’.
Examples
>>> # Filter by max 22 microns diameter >>> iscell_filtered, removed, info = filter_by_max_diameter( ... plane_dir="path/to/plane01", max_diameter_um=22 ... )
>>> # Filter by diameter range in pixels >>> iscell_filtered, removed, info = filter_by_max_diameter( ... plane_dir, min_diameter_px=5, max_diameter_px=30 ... )
>>> # Filter and save to iscell.npy >>> iscell_filtered, removed, info = filter_by_max_diameter( ... plane_dir, max_diameter_um=22, save=True ... )
- lbm_suite2p_python.postprocessing.filter_by_area(plane_dir=None, iscell=None, stat=None, ops=None, min_area_px: float = None, max_area_px: float = None, min_mult: float = None, max_mult: float = None, save: bool = False)[source]#
Filter cells by total area (in pixels).
Can specify absolute bounds (min_area_px, max_area_px) or relative bounds as multiples of the median area (min_mult, max_mult).
- Parameters:
- plane_dirstr or Path, optional
Path to Suite2p plane directory. If provided, loads iscell, stat, ops.
- iscellnp.ndarray, optional
Cell classification array.
- statnp.ndarray or list, optional
Suite2p stat array.
- opsdict, optional
Suite2p ops dictionary (not used, for consistent interface).
- min_area_pxfloat, optional
Minimum allowed area in pixels.
- max_area_pxfloat, optional
Maximum allowed area in pixels.
- min_multfloat, optional
Minimum area as multiple of median (e.g., 0.25 = 25% of median).
- max_multfloat, optional
Maximum area as multiple of median (e.g., 4.0 = 400% of median).
- savebool, default False
If True, save updated iscell.npy to plane_dir.
- Returns:
- iscell_filterednp.ndarray
Updated iscell array (1D boolean).
- removed_masknp.ndarray
Boolean mask of ROIs that were removed.
- infodict
Dictionary with ‘areas_px’, ‘min_px’, ‘max_px’, ‘n_removed’.
- lbm_suite2p_python.postprocessing.filter_by_eccentricity(plane_dir=None, iscell=None, stat=None, ops=None, max_ratio: float = 5.0, min_ratio: float = None, save: bool = False)[source]#
Filter ROIs by aspect ratio (elongation).
Uses bounding box dimensions to compute aspect ratio. High ratios indicate elongated shapes (likely not cell bodies).
- Parameters:
- plane_dirstr or Path, optional
Path to Suite2p plane directory. If provided, loads iscell, stat, ops.
- iscellnp.ndarray, optional
Cell classification array.
- statnp.ndarray or list, optional
Suite2p stat array.
- opsdict, optional
Suite2p ops dictionary (not used, for consistent interface).
- max_ratiofloat, default 5.0
Maximum allowed aspect ratio (width/height or height/width).
- min_ratiofloat, optional
Minimum allowed aspect ratio.
- savebool, default False
If True, save updated iscell.npy to plane_dir.
- Returns:
- iscell_filterednp.ndarray
Updated iscell array (1D boolean).
- removed_masknp.ndarray
Boolean mask of ROIs that were removed.
- infodict
Dictionary with ‘ratios’, ‘min_ratio’, ‘max_ratio’, ‘n_removed’.
Post-Processing#
ΔF/F Calculation#
- lbm_suite2p_python.dff_rolling_percentile(f_trace, window_size: int = None, percentile: int = 20, use_median_floor: bool = False, smooth_window: int = None, fs: float = None, tau: float = None)[source]#
Compute ΔF/F₀ using a rolling percentile baseline.
- Parameters:
- f_tracenp.ndarray
(N_neurons, N_frames) fluorescence traces.
- window_sizeint, optional
Size of the rolling window for baseline estimation (in frames). If None, auto-calculated as ~10 × tau × fs (default: 300 frames).
- percentileint, default 20
Percentile to use for baseline F₀ estimation.
- use_median_floorbool, default False
Set a minimum F₀ floor at 1% of the median fluorescence.
- smooth_windowint, optional
Size of temporal smoothing window (in frames) applied after dF/F. If None, auto-calculated as ~0.5 × tau × fs to emphasize transients while reducing noise. Set to 0 or 1 to disable smoothing.
- fsfloat, optional
Frame rate in Hz. Used to auto-calculate window sizes if tau is provided.
- taufloat, optional
Calcium indicator decay time constant in seconds (e.g., 1.0 for GCaMP6s). Used to auto-calculate window sizes if fs is provided.
- Returns:
- dffnp.ndarray
(N_neurons, N_frames) ΔF/F₀ traces.
Notes
Window size recommendations:
Baseline window (~10 × tau × fs): Should span multiple transients so the percentile filter can find baseline between events.
Smooth window (~0.5 × tau × fs): Should be shorter than typical transients to preserve them while averaging out noise.
For GCaMP6s (tau ~ 1.0s) at 30 Hz: window_size ~ 300 frames (10 seconds), smooth_window ~ 15 frames (0.5 seconds).
For GCaMP6f (tau ~ 0.4s) at 30 Hz: window_size ~ 120 frames (4 seconds), smooth_window ~ 6 frames (0.2 seconds).
- lbm_suite2p_python.dff_shot_noise(dff, fr)[source]#
Estimate the shot noise level of calcium imaging traces.
This metric quantifies the noise level based on frame-to-frame differences, assuming slow calcium dynamics compared to the imaging frame rate. It was introduced by Rupprecht et al. (2021) [1] as a standardized method for comparing noise levels across datasets with different acquisition parameters.
The noise level \(\nu\) is computed as:
\[\nu = \frac{\mathrm{median}_t\left( \left| \Delta F/F_{t+1} - \Delta F/F_t \right| \right)}{\sqrt{f_r}}\]- where
\(\Delta F/F_t\) is the fluorescence trace at time \(t\)
\(f_r\) is the imaging frame rate (in Hz).
- Parameters:
- dffnp.ndarray
Array of shape (n_neurons, n_frames), containing raw \(\Delta F/F\) traces (percent units, without neuropil subtraction).
- frfloat
Frame rate of the recording in Hz.
- Returns:
- np.ndarray
Noise level \(\nu\) for each neuron, expressed in %/√Hz units.
Notes
The metric relies on the slow dynamics of calcium signals compared to frame rate.
Higher values of \(\nu\) indicate higher shot noise.
Units are % divided by √Hz, and while unconventional, they enable comparison across frame rates.
References
- [1] Rupprecht et al., “Large-scale calcium imaging & noise levels”,
A Neuroscientific Blog (2021). https://gcamp6f.com/2021/10/04/large-scale-calcium-imaging-noise-levels/
Quality Scoring#
- lbm_suite2p_python.postprocessing.compute_trace_quality_score(F, Fneu=None, stat=None, fs=30.0, weights=None)[source]#
Compute a weighted quality score for sorting neurons by signal quality.
Combines SNR, skewness, and shot noise into a single score for ranking neurons from best to worst signal quality. Higher scores indicate better quality traces.
- Parameters:
- Fnp.ndarray
Fluorescence traces, shape (n_neurons, n_frames).
- Fneunp.ndarray, optional
Neuropil fluorescence traces, shape (n_neurons, n_frames). If None, no neuropil correction is applied.
- statnp.ndarray or list, optional
Suite2p stat array containing ROI statistics. If provided, uses pre-computed skewness from stat[‘skew’]. Otherwise computes from traces.
- fsfloat, default 30.0
Frame rate in Hz, used for shot noise calculation.
- weightsdict, optional
Weights for each metric. Keys: ‘snr’, ‘skewness’, ‘shot_noise’. Default: {‘snr’: 1.0, ‘skewness’: 0.8, ‘shot_noise’: 0.5} Note: shot_noise is inverted (lower noise = higher score).
- Returns:
- dict
Dictionary containing: - ‘score’: Combined quality score (n_neurons,) - ‘sort_idx’: Indices that sort neurons by score (descending) - ‘snr’: SNR values (n_neurons,) - ‘skewness’: Skewness values (n_neurons,) - ‘shot_noise’: Shot noise values (n_neurons,) - ‘weights’: Weights used for scoring
Notes
Each metric is z-scored before weighting to ensure comparable scales: - SNR: signal std / noise estimate (higher = better) - Skewness: positive skew indicates calcium transients (higher = better) - Shot noise: frame-to-frame variability (lower = better, so inverted)
Examples
>>> import numpy as np >>> from lbm_suite2p_python.postprocessing import compute_trace_quality_score >>> F = np.load("F.npy") >>> Fneu = np.load("Fneu.npy") >>> result = compute_trace_quality_score(F, Fneu, fs=30.0) >>> sorted_F = F[result['sort_idx']] # Traces sorted by quality
- lbm_suite2p_python.postprocessing.sort_traces_by_quality(F, Fneu=None, stat=None, fs=30.0, weights=None)[source]#
Sort fluorescence traces by quality score (best to worst).
Convenience function that computes quality scores and returns sorted traces.
- Parameters:
- Fnp.ndarray
Fluorescence traces, shape (n_neurons, n_frames).
- Fneunp.ndarray, optional
Neuropil fluorescence traces.
- statnp.ndarray or list, optional
Suite2p stat array for pre-computed skewness.
- fsfloat, default 30.0
Frame rate in Hz.
- weightsdict, optional
Weights for each metric. Default: {‘snr’: 1.0, ‘skewness’: 0.8, ‘shot_noise’: 0.5}
- Returns:
- F_sortednp.ndarray
Traces sorted by quality (best first).
- sort_idxnp.ndarray
Indices used to sort (can be used to sort other arrays).
- qualitydict
Full quality metrics from compute_trace_quality_score().
Examples
>>> F_sorted, sort_idx, quality = sort_traces_by_quality(F, Fneu) >>> # Also sort stat and iscell arrays >>> stat_sorted = stat[sort_idx] >>> iscell_sorted = iscell[sort_idx]
Utilities#
- lbm_suite2p_python.postprocessing.load_traces(ops)[source]#
Load fluorescence traces and related data from an ops file directory and return valid cells.
This function loads the raw fluorescence traces, neuropil traces, and spike data from the directory specified in the ops dictionary. It also loads the ‘iscell’ file and returns only the traces corresponding to valid cells (i.e. where iscell is True).
- Parameters:
- opsdict
Dictionary containing at least the key ‘save_path’, which specifies the directory where the following files are stored: ‘F.npy’, ‘Fneu.npy’, ‘spks.npy’, and ‘iscell.npy’.
- Returns:
- F_validndarray
Array of fluorescence traces for valid cells (n_valid x n_timepoints).
- Fneu_validndarray
Array of neuropil fluorescence traces for valid cells (n_valid x n_timepoints).
- spks_validndarray
Array of spike data for valid cells (n_valid x n_timepoints).
Notes
The ‘iscell.npy’ file is expected to be an array where the first column (iscell[:, 0]) contains boolean values indicating valid cells.
- lbm_suite2p_python.postprocessing.normalize_traces(F, mode='percentile')[source]#
Normalize fluorescence traces F to [0, 1] range. :param F: 2d array of fluorescence traces (n_neurons x n_timepoints). :type F: ndarray :param mode: Normalization mode, either “per_neuron” or “percentile”. :type mode: str
- Returns:
- F_normndarray
Normalized fluorescence traces in [0, 1] range.
Notes
“per_neuron”: scales each neuron’s trace based on its own min and max.
“percentile”: scales each neuron’s trace based on its 1st and 99th percentiles.
If min == max for each cell, the trace is set to all zeros to avoid division by zero.
- lbm_suite2p_python.postprocessing.ops_to_json(ops: dict | str | Path, outpath=None, indent=2)[source]#
Convert a Suite2p ops.npy file (or dict) to JSON.
- Parameters:
- opsdict or str or Path
Either a loaded ops dictionary or the path to an ops.npy file.
- outpathstr or Path, optional
Output path for ops.json. If None, saves as ‘ops.json’ in the same directory as the input ops.npy (or current directory if ops is a dict).
- indentint
Indentation for JSON formatting.
- Returns:
- Path
Path to the written ops.json file.
Grid Search#
- lbm_suite2p_python.grid_search(input_data, save_path: Path | str, grid_params: dict, ops: dict = None, planes: list | int = None, roi_mode: int = None, force_reg: bool = False, force_detect: bool = True, reader_kwargs: dict = None, writer_kwargs: dict = None, roi: int = None, **kwargs)[source]#
Run a grid search over all combinations of Suite2p parameters.
Tests all combinations of parameters in grid_params, running detection for each combination. When only searching detection parameters, the binary is written and registered once, then reused for all combinations.
- Parameters:
- input_datastr, Path, list, or lazy array
Input data source. Can be: - Path to a file (TIFF, Zarr, HDF5, .bin) - Path to a directory containing supported files - An mbo_utilities lazy array (MboRawArray, Suite2pArray, etc.)
- save_pathstr or Path
Root directory where results will be saved.
- grid_paramsdict
Dictionary mapping parameter names to lists of values to test. All combinations will be tested (Cartesian product).
- opsdict, optional
Base ops dictionary. If None, uses default_ops().
- planesint or list, optional
Which z-planes to process (1-indexed, 0 is not valid).
- roi_modeint, optional
ROI handling for multi-ROI ScanImage data.
- force_regbool, default False
If True, force registration even if already done.
- force_detectbool, default True
If True, force ROI detection for each combination.
- reader_kwargsdict, optional
Keyword arguments passed to mbo_utilities.imread().
- writer_kwargsdict, optional
Keyword arguments passed when writing binary files.
- **kwargs
Additional arguments passed to Suite2p.
- Returns:
- Path
Path to save_path directory containing all results.
Examples
>>> import lbm_suite2p_python as lsp >>> >>> # search detection params on plane 7 >>> lsp.grid_search( ... input_data="D:/data/raw.tif", ... save_path="D:/results/grid_search", ... planes=7, ... grid_params={ ... "threshold_scaling": [0.8, 1.0, 1.2], ... "diameter": [6, 8], ... }, ... ) >>> >>> # collect and analyze results >>> df = lsp.collect_grid_results("D:/results/grid_search", grid_params) >>> best = lsp.get_best_parameters(df)
- lbm_suite2p_python.collect_grid_results(save_path: Path | str, grid_params: dict = None) DataFrame[source]#
Collect quality metrics from all grid search combinations.
- Parameters:
- save_pathPath or str
Root directory containing grid search results.
- grid_paramsdict, optional
Grid parameters dict to extract parameter values from ops. If None, only combo name is included.
- Returns:
- pd.DataFrame
DataFrame with one row per combination, containing: - combo: folder name - n_accepted, n_rejected: cell counts - snr_median, snr_iqr: signal-to-noise ratio - skew_median, skew_iqr: trace skewness - noise_median, noise_iqr: shot noise - parameter columns from grid_params
- lbm_suite2p_python.save_grid_results(df: DataFrame, save_path: Path | str)[source]#
Save grid search results to CSV.
- lbm_suite2p_python.plot_grid_metrics(df: DataFrame, grid_params: dict = None, save_path: Path | str = None, figsize: tuple = (15, 10))[source]#
Plot quality metrics comparison across grid search combinations.
- Parameters:
- dfpd.DataFrame
Results DataFrame from collect_grid_results().
- grid_paramsdict, optional
Grid parameters for parameter effect plots.
- save_pathPath or str, optional
Path to save figure. If None, displays with plt.show().
- figsizetuple, default (15, 10)
Figure size.
- Returns:
- matplotlib.figure.Figure
Plotting#
Planar Visualization#
- lbm_suite2p_python.plot_traces(f, save_path: str | Path = '', cell_indices: ndarray | list[int] | None = None, fps=17.0, num_neurons=20, window=220, title='', offset=None, lw=0.5, cmap='tab10', scale_bar_unit: str = None, mask_overlap: bool = True) None[source]#
Plot stacked fluorescence traces with automatic offset and scale bars.
- Parameters:
- fndarray or str or Path
2d array of fluorescence traces (n_neurons x n_timepoints), or path to Suite2p plane directory containing dff.npy/F.npy.
- save_pathstr, optional
Path to save the output plot.
- fpsfloat
Sampling rate in frames per second.
- num_neuronsint
Number of neurons to display if cell_indices is None.
- windowfloat
Time window (in seconds) to display.
- titlestr
Title of the figure.
- offsetfloat or None
Vertical offset between traces; if None, computed automatically.
- lwfloat
Line width for data points.
- cmapstr
Matplotlib colormap string.
- scale_bar_unitstr, optional
Unit suffix for the vertical scale bar (e.g., “% ΔF/F₀”, “a.u.”). The numeric value is computed automatically based on the plot’s vertical scale. If None, inferred from data range.
- cell_indicesarray-like or None
Specific cell indices to plot. If provided, overrides num_neurons.
- mask_overlapbool, default True
If True, lower traces mask (occlude) traces above them, creating a layered effect where each trace has a black background.
- lbm_suite2p_python.animate_traces(f, save_path='./traces.mp4', cell_indices=None, fps=17.0, num_neurons=20, window=30, title='', offset=None, lw=0.5, cmap='tab10', scale_bar_unit=None, mask_overlap=True, anim_fps=30, speed=1.0, dpi=150)[source]#
Animated version of plot_traces - scrolling window through time.
Creates an mp4 video showing traces scrolling like an oscilloscope display. Visual style matches plot_traces exactly.
- Parameters:
- fndarray
2d array of fluorescence traces (n_neurons x n_timepoints).
- save_pathstr or Path, default “./traces.mp4”
Output path for the animation.
- cell_indicesarray-like or None
Specific cell indices to plot. If provided, overrides num_neurons.
- fpsfloat, default 17.0
Data frame rate in Hz.
- num_neuronsint, default 20
Number of neurons to display if cell_indices is None.
- windowfloat, default 30
Time window width in seconds.
- titlestr, default “”
Title for the animation.
- offsetfloat or None
Vertical offset between traces; if None, computed automatically.
- lwfloat, default 0.5
Line width for traces.
- cmapstr, default “tab10”
Matplotlib colormap.
- scale_bar_unitstr, optional
Unit suffix for vertical scale bar. If None, uses “a.u.”.
- mask_overlapbool, default True
If True, lower traces mask traces above them.
- anim_fpsint, default 30
Animation frame rate (frames per second in output video).
- speedfloat, default 1.0
Playback speed multiplier (1.0 = real-time, 2.0 = 2x speed).
- dpiint, default 150
Output video resolution.
- Returns:
- str
Path to saved animation.
- lbm_suite2p_python.plot_projection(ops, output_directory=None, fig_label=None, vmin=None, vmax=None, add_scalebar=False, proj='meanImg', display_masks=False, accepted_only=False)[source]#
Plot a projection image from ops with optional mask overlay.
- Parameters:
- opsdict or str or Path
Suite2p ops dictionary or path to ops.npy.
- output_directorystr or Path, optional
Directory to save figure. If None, displays interactively.
- fig_labelstr, optional
Label for y-axis.
- vmin, vmaxfloat, optional
Intensity display range. Defaults to 2nd/98th percentiles.
- add_scalebarbool, default False
Whether to add a scale bar.
- projstr, default “meanImg”
Projection type: “meanImg”, “max_proj”, or “meanImgE”.
- display_masksbool, default False
Whether to overlay detected ROI masks.
- accepted_onlybool, default False
If True, only show accepted cells when display_masks=True.
- Returns:
- matplotlib.figure.Figure
The generated figure.
- lbm_suite2p_python.plot_zplane_figures(plane_dir, dff_percentile=8, dff_window_size=None, dff_smooth_window=None, run_rastermap=False, **kwargs)[source]#
Re-generate Suite2p figures for a merged plane.
- Parameters:
- plane_dirPath
Path to the planeXX output directory (with ops.npy, stat.npy, etc.).
- dff_percentileint, optional
Percentile used for ΔF/F baseline.
- dff_window_sizeint, optional
Window size for ΔF/F rolling baseline. If None, auto-calculated as ~10 × tau × fs based on ops values.
- dff_smooth_windowint, optional
Temporal smoothing window for dF/F traces (in frames). If None, auto-calculated as ~0.5 × tau × fs to emphasize transients while reducing noise. Set to 1 to disable.
- run_rastermapbool, optional
If True, compute and plot rastermap sorting of cells.
- kwargsdict
Extra keyword args (e.g. fig_label).
- lbm_suite2p_python.plot_plane_quality_metrics(stat: ndarray, iscell: ndarray, save_path: str | Path = None, figsize: tuple = (14, 10)) Figure[source]#
Generate publication-quality ROI quality metrics across all planes.
Creates a multi-panel figure with line plots showing mean ± std: - Compactness vs plane - Skewness vs plane - ROI size (npix) vs plane - Radius vs plane
- Parameters:
- statnp.ndarray
Consolidated stat array with ‘iplane’, ‘compact’, ‘npix’ fields.
- iscellnp.ndarray
Cell classification array (n_rois, 2).
- save_pathstr or Path, optional
If provided, save figure to this path.
- figsizetuple, default (14, 10)
Figure size in inches.
- Returns:
- figmatplotlib.figure.Figure
The generated figure object.
Examples
>>> stat = np.load("merged/stat.npy", allow_pickle=True) >>> iscell = np.load("merged/iscell.npy") >>> fig = plot_plane_quality_metrics(stat, iscell, save_path="quality.png")
- lbm_suite2p_python.plot_plane_diagnostics(plane_dir: str | Path, save_path: str | Path = None, figsize: tuple = (16, 14), n_examples: int = 4) Figure[source]#
Generate a single-figure diagnostic summary for a processed plane.
Creates a publication-quality figure showing: - ROI size distribution (accepted vs rejected) - SNR distribution with quality threshold - Compactness vs SNR scatter - Summary statistics text - Zoomed ROI examples: N highest SNR and N lowest SNR cells
Robust to low/zero cell counts - will display informative messages when data is insufficient for certain visualizations.
- Parameters:
- plane_dirstr or Path
Path to the plane directory containing ops.npy, stat.npy, etc.
- save_pathstr or Path, optional
If provided, save figure to this path.
- figsizetuple, default (16, 14)
Figure size in inches.
- n_examplesint, default 4
Number of high/low SNR ROI examples to show.
- Returns:
- figmatplotlib.figure.Figure
The generated figure object.
- lbm_suite2p_python.plot_trace_analysis(F: ndarray, Fneu: ndarray, stat: ndarray, iscell: ndarray, ops: dict, save_path: str | Path = None, figsize: tuple = (16, 14)) Tuple[Figure, dict][source]#
Generate trace analysis figure showing extreme examples by quality metrics.
Creates a 6-panel figure showing example ΔF/F traces for: - Highest SNR / Lowest SNR - Lowest shot noise / Highest shot noise - Highest skewness / Lowest skewness
- Parameters:
- Fnp.ndarray
Fluorescence traces array (n_rois, n_frames).
- Fneunp.ndarray
Neuropil fluorescence array (n_rois, n_frames).
- statnp.ndarray
Stat array with ‘iplane’ and ‘skew’ fields.
- iscellnp.ndarray
Cell classification array.
- opsdict
Ops dictionary with ‘fs’ (frame rate) field.
- save_pathstr or Path, optional
If provided, save figure to this path.
- figsizetuple, default (16, 14)
Figure size in inches.
- Returns:
- figmatplotlib.figure.Figure
The generated figure object.
- metricsdict
Dictionary containing computed metrics (snr, shot_noise, skewness, dff).
Examples
>>> fig, metrics = plot_trace_analysis(F, Fneu, stat, iscell, ops) >>> print(f"Mean SNR: {np.mean(metrics['snr']):.2f}")
- lbm_suite2p_python.plot_multiplane_masks(suite2p_path: str | Path, stat: ndarray, iscell: ndarray, nrows: int = None, ncols: int = None, figsize: tuple = None, save_path: str | Path = None, cmap: str = 'gray') Figure[source]#
Plot ROI masks from all planes in a publication-quality grid layout.
Creates a multi-panel figure showing detected ROIs overlaid on reference images for each z-plane, with accepted cells in green and rejected cells in red. Background image is selected based on anatomical_only setting.
- Parameters:
- suite2p_pathstr or Path
Path to suite2p directory containing plane folders (e.g., zplane01/).
- statnp.ndarray
Consolidated stat array with ‘iplane’ field indicating plane assignment.
- iscellnp.ndarray
Cell classification array (n_rois, 2) where column 0 is binary classification.
- nrowsint, optional
Number of rows in the figure grid. Auto-calculated if None.
- ncolsint, optional
Number of columns in the figure grid. Auto-calculated if None.
- figsizetuple, optional
Figure size in inches (width, height). Auto-calculated if None.
- save_pathstr or Path, optional
If provided, save figure to this path. Otherwise display interactively.
- cmapstr, default “gray”
Colormap for background images.
- Returns:
- figmatplotlib.figure.Figure
The generated figure object.
- lbm_suite2p_python.plot_mask_comparison(img, results, zoom_levels=None, zoom_center=None, title=None, save_path=None, figsize=None)[source]#
Create a multi-panel comparison of detection results with zoom views.
Generates a grid visualization comparing different parameter combinations (e.g., diameters) with full-image views and progressively zoomed regions.
- Parameters:
- imgnumpy.ndarray
2D background image for overlay (e.g., max projection).
- resultsdict
Dictionary mapping names to result dicts. Each result dict should contain either: - ‘masks’: 2D labeled mask array, OR - ‘stat’: Suite2p stat array (will be converted to mask) And optionally: - ‘n_cells’: Number of cells (computed from mask if not provided)
- zoom_levelslist of int, optional
List of zoom region sizes in pixels. Default is [400, 200, 100].
- zoom_centertuple of (int, int), optional
Center point (cy, cx) for zoom regions. Default is image center.
- titlestr, optional
Overall figure title.
- save_pathstr or Path, optional
Path to save the figure. If None, displays with plt.show().
- figsizetuple, optional
Figure size (width, height) in inches. Default is auto-calculated.
- Returns:
- matplotlib.figure.Figure
The generated figure.
See also
mask_overlayCreates individual overlays.
stat_to_maskConverts stat arrays to masks.
Examples
>>> img = ops['max_proj'] >>> results = { ... 'd=2': {'masks': masks_d2, 'n_cells': 500}, ... 'd=4': {'masks': masks_d4, 'n_cells': 350}, ... 'd=6': {'masks': masks_d6, 'n_cells': 200}, ... } >>> fig = plot_mask_comparison(img, results, zoom_levels=[200, 100])
- lbm_suite2p_python.plot_regional_zoom(plane_dir, zoom_size: int = 150, img_key: str = 'max_proj', alpha: float = 0.5, save_path=None, figsize: tuple = (15, 10), accepted_only: bool = True)[source]#
Plot corner, edge, and center zoom views of detection results.
Creates a 2x3 grid visualization showing the full image with region boxes, plus zoomed views of each corner and the center. Useful for checking detection quality across different parts of the field of view.
- Parameters:
- plane_dirstr or Path
Path to a Suite2p plane directory containing ops.npy, stat.npy, and optionally iscell.npy.
- zoom_sizeint, optional
Size of zoom regions in pixels. Default is 150.
- img_keystr, optional
Key in ops to use as background image. Options: ‘max_proj’, ‘meanImg’, ‘meanImgE’. Default is ‘max_proj’.
- alphafloat, optional
Blending factor for mask overlay (0-1). Default is 0.5.
- save_pathstr or Path, optional
Path to save the figure. If None, displays with plt.show().
- figsizetuple, optional
Figure size (width, height) in inches. Default is (15, 10).
- accepted_onlybool, optional
If True, only show cells marked as accepted (iscell[:, 0] == 1). Default is True.
- Returns:
- matplotlib.figure.Figure
The generated figure.
Examples
>>> # From pipeline results >>> ops_paths = lsp.pipeline(input_data=path, save_path=output_dir, ...) >>> for ops_path in ops_paths: ... plot_regional_zoom(ops_path.parent, zoom_size=150)
>>> # With custom settings >>> plot_regional_zoom( ... "D:/results/plane01_vdaq0", ... zoom_size=200, ... img_key="meanImgE", ... save_path="regional_zoom.png" ... )
- lbm_suite2p_python.plot_filtered_cells(plane_dir, iscell_original, iscell_filtered, img_key: str = 'max_proj', alpha: float = 0.5, save_path=None, figsize: tuple = (18, 6), title: str = None)[source]#
Plot side-by-side comparison of cells before and after filtering.
Shows three panels: kept cells, removed cells, and both overlaid with different colors.
- Parameters:
- plane_dirstr or Path
Path to a Suite2p plane directory containing ops.npy, stat.npy.
- iscell_originalnp.ndarray
Original iscell array before filtering (n_rois,) or (n_rois, 2).
- iscell_filterednp.ndarray
Filtered iscell array (n_rois,) or (n_rois, 2).
- img_keystr, optional
Key in ops to use as background image. Default is ‘max_proj’.
- alphafloat, optional
Blending factor for mask overlay (0-1). Default is 0.5.
- save_pathstr or Path, optional
Path to save the figure. If None, displays with plt.show().
- figsizetuple, optional
Figure size (width, height) in inches. Default is (18, 6).
- titlestr, optional
Custom title for the figure.
- Returns:
- matplotlib.figure.Figure
The generated figure.
Examples
>>> from lbm_suite2p_python import filter_by_max_diameter, plot_filtered_cells >>> res = load_planar_results(plane_dir) >>> iscell_filtered = filter_by_max_diameter( ... res["iscell"], res["stat"], max_diameter_px=15 ... ) >>> plot_filtered_cells(plane_dir, res["iscell"], iscell_filtered)
- lbm_suite2p_python.plot_diameter_histogram(stat, iscell=None, max_diameter_px: float = None, pixel_size_um: float = None, bins: int = 50, save_path=None, figsize: tuple = (10, 6))[source]#
Plot histogram of cell diameters with optional threshold line.
- Parameters:
- statnp.ndarray or list
Suite2p stat array with ROI statistics.
- iscellnp.ndarray, optional
Cell classification array. If provided, only plots accepted cells.
- max_diameter_pxfloat, optional
Threshold diameter in pixels to show as vertical line.
- pixel_size_umfloat, optional
Pixel size in microns. If provided, adds micron scale to x-axis.
- binsint, optional
Number of histogram bins. Default is 50.
- save_pathstr or Path, optional
Path to save the figure.
- figsizetuple, optional
Figure size. Default is (10, 6).
- Returns:
- matplotlib.figure.Figure
The generated figure.
Volume Visualization#
- lbm_suite2p_python.plot_volume_diagnostics(ops_files: list[str | Path], save_path: str | Path = None, figsize: tuple = (16, 12)) Figure[source]#
Generate a single-figure diagnostic summary for an entire processed volume.
Creates a publication-quality figure showing across all z-planes: - Row 1: ROI counts (accepted/rejected stacked bars), Mean signal per plane - Row 2: SNR distribution per plane, Size distribution per plane - Row 3: Compactness vs SNR (all planes), Skewness vs SNR (all planes)
- Parameters:
- ops_fileslist of str or Path
List of paths to ops.npy files for each z-plane.
- save_pathstr or Path, optional
If provided, save figure to this path.
- figsizetuple, default (16, 12)
Figure size in inches.
- Returns:
- figmatplotlib.figure.Figure
The generated figure object.
- lbm_suite2p_python.plot_orthoslices(ops_files: list[str | Path], save_path: str | Path = None, figsize: tuple = (16, 6), use_mean: bool = True) Figure[source]#
Generate orthogonal maximum intensity projections (XY, XZ, YZ) of the volume.
Creates a 3-panel figure showing the volume from three orthogonal views, with proper interpolation to isotropic resolution. Axes are displayed in micrometers using voxel size metadata.
- Parameters:
- ops_fileslist of str or Path
List of paths to ops.npy files for each z-plane, ordered by z.
- save_pathstr or Path, optional
If provided, save figure to this path.
- figsizetuple, default (16, 6)
Figure size in inches.
- use_meanbool, default True
If True, use meanImg. If False, use refImg (registered reference).
- Returns:
- figmatplotlib.figure.Figure
The generated figure object.
- lbm_suite2p_python.plot_3d_roi_map(ops_files: list[str | Path], save_path: str | Path = None, figsize: tuple = (14, 10), color_by: str = 'snr', show_rejected: bool = False) Figure[source]#
Generate a 3D scatter plot of ROI centroids across the volume.
Creates a 3D visualization showing the spatial distribution of detected cells colored by SNR. Axes are displayed in micrometers when valid voxel size metadata is available, otherwise in pixels/planes.
- Parameters:
- ops_fileslist of str or Path
List of paths to ops.npy files for each z-plane.
- save_pathstr or Path, optional
If provided, save figure to this path.
- figsizetuple, default (14, 10)
Figure size in inches.
- color_bystr, default “snr”
How to color the ROIs: “snr”, “plane”, “size”, or “activity”.
- show_rejectedbool, default False
If True, also show rejected ROIs in gray.
- Returns:
- figmatplotlib.figure.Figure
The generated figure object.
- lbm_suite2p_python.plot_3d_rastermap_clusters(suite2p_path: str | Path, save_path: str | Path = None, figsize: tuple = (14, 10), n_clusters: int = 40, show_rejected: bool = False, rastermap_kwargs: dict = None) Figure[source]#
Generate a 3D scatter plot of ROI centroids colored by rastermap cluster.
Loads volumetric suite2p output, runs rastermap clustering on fluorescence data, and visualizes ROI positions in 3D colored by cluster assignment. Checks for existing rastermap model file before running.
- Parameters:
- suite2p_pathstr or Path
Path to suite2p directory containing plane folders or merged folder.
- save_pathstr or Path, optional
If provided, save figure to this path.
- figsizetuple, default (14, 10)
Figure size in inches.
- n_clustersint, default 40
Number of rastermap clusters. Ignored if loading existing model.
- show_rejectedbool, default False
If True, also show rejected ROIs in gray.
- rastermap_kwargsdict, optional
Additional kwargs passed to Rastermap(). Ignored if loading existing model.
- Returns:
- figmatplotlib.figure.Figure
The generated figure object.
Notes
Looks for existing rastermap model at: - suite2p_path/rastermap_model.npy - suite2p_path/merged/rastermap_model.npy
If not found, runs rastermap on the consolidated fluorescence data and saves the model for future use.
Examples
>>> import lbm_suite2p_python as lsp >>> fig = lsp.plot_3d_rastermap_clusters("path/to/suite2p") >>> fig = lsp.plot_3d_rastermap_clusters("path/to/suite2p", n_clusters=50)
- lbm_suite2p_python.plot_volume_signal(zstats, savepath)[source]#
Plots the mean fluorescence signal per z-plane with standard deviation error bars.
This function loads signal statistics from a .npy file and visualizes the mean fluorescence signal per z-plane, with error bars representing the standard deviation.
- Parameters:
- zstatsstr or Path
Path to the .npy file containing the volume stats. The output of get_zstats().
- savepathstr or Path
Path to save the generated figure.
Notes
The .npy file should contain structured data with plane, mean_trace, and std_trace fields.
Error bars represent the standard deviation of the fluorescence signal.
- lbm_suite2p_python.plot_volume_neuron_counts(zstats, savepath)[source]#
Plots the number of accepted and rejected neurons per z-plane.
This function loads neuron count data from a .npy file and visualizes the accepted vs. rejected neurons as a stacked bar plot with a black background.
- Parameters:
- zstatsstr, Path
Full path to the zstats.npy file.
- savepathstr or Path
Path to directory where generated figure will be saved.
Notes
The .npy file should contain structured data with plane, accepted, and rejected fields.
- lbm_suite2p_python.consolidate_volume(suite2p_path, merged_dir='merged', overwrite=False)[source]#
Consolidate all plane results into a single merged directory.
Combines ops.npy, stat.npy, iscell.npy, F.npy, Fneu.npy, and spks.npy from all plane folders into a single merged/ folder with plane-indexed arrays.
- Parameters:
- suite2p_pathstr or Path
Path to suite2p directory containing plane folders (zplaneNN or planeNN)
- merged_dirstr, optional
Name of merged directory to create (default: “merged”)
- overwritebool, optional
Whether to overwrite existing merged directory (default: False)
- Returns:
- merged_pathPath
Path to the created merged directory
Examples
>>> import lbm_suite2p_python as lsp >>> merged = lsp.consolidate_volume("path/to/suite2p") >>> # Load consolidated results >>> ops = np.load(merged / "ops.npy", allow_pickle=True).item() >>> stat = np.load(merged / "stat.npy", allow_pickle=True) >>> iscell = np.load(merged / "iscell.npy")