Skip to main content

Python Version License: MIT tests PyPI - Version Conda Version GitHub last commit


Example shown: region-level 3D registration across subjects (video slowed down ~5x). Cell-level registration of microscopy data is also possible.

warpfield

A GPU-accelerated Python library for non-rigid 3D registration / warping.

Links: API documentation, GitHub repository

Features

  • GPU-accelerated code for high performance (CuPy, CUDA kernels & FFT plans or MLX, Apple Silicon GPU acceleration)
  • Typical speedup compared to CPU-based methods: > 1000x (seconds vs. hours for gigavoxel volumes)
  • Forward and inverse transform of 3D volumes as well as point coordinates
  • Python API and command-line interface (CLI)
  • Support for .h5, .zarr, .nii, .nrrd, .tiff, .mat and .npy file formats

General Principle

The registration process aligns a moving 3D volume to a fixed reference volume by estimating and applying a displacement field. The process is typically performed in a multi-resolution (pyramid) fashion, starting with coarse alignment and progressively refining the displacement field at finer resolutions.

The key steps are:

  1. Preprocessing: Enhance features in the volumes (e.g., using Difference-of-Gaussian or 'DoG' filtering) to improve registration accuracy.
  2. Block Matching: Divide the volumes into smaller 3D blocks, project them to 2D (along each axis) for memory and compute efficiency, and calculate 2D cross-correlation maps. After smoothing these 2D maps across neighboring blocks, use their maxima to determine the block-level 3D displacement vector.
  3. Displacement Field Estimation: Combine block-level displacement vectors into a displacement field (and optionaly apply a median filter or fit an affine transform)
  4. Warping: Apply the displacement field to the moving volume to align it with the fixed volume.
  5. Multi-Resolution Refinement: Repeat the above steps at progressively finer resolutions to refine the alignment.

Hardware requirements

  • A computer running Linux (recommended) or Windows for the CUDA backend, or macOS 14.0+ for the Metal backend
  • A CUDA- or Metal-compatible GPU with sufficient GPU memory: ≥ 30 bytes per voxel (30 GB / gigavoxel) of your 3D volume

Installation

CUDA (NVIDIA GPUs)

This requires an NVIDIA GPU with a current driver. The CUDA libraries are installed along with warpfield, so you don't need a separate CUDA Toolkit. We recommend installing warpfield via conda/mamba:

conda install conda-forge::warpfield

Or, to install into a new conda environment (recommended):

conda create -n warpfield conda-forge::warpfield
conda activate warpfield

Installation via pip is also possible. Choose the extra that matches your driver's CUDA version (nvidia-smi shows it in the top right):

pip install "warpfield[cuda12]"   # CUDA 12.x
pip install "warpfield[cuda13]"   # CUDA 13.x

A plain pip install warpfield does not install CuPy. Use it if CuPy is already installed, as on Google Colab, so that the existing CuPy is not replaced by one built for a different CUDA version.

Apple Silicon (Metal)

This requires a Mac with Apple Silicon (M-series chip) and macOS 14.0 or later. Installation via pip should just work:

pip install warpfield

Development

For development, fork and clone the repository. Then type:

conda env create -n warpfield -f environment.yml
conda activate warpfield
pip install --no-deps -e .

Quickstart

import numpy as np
import warpfield

# 1. Load data (note: the two volumes are expected to be of the same resolution)
vol_ref, _ = warpfield.load_data("reference_volume.npy")
vol_mov, _ = warpfield.load_data("moving_volume.npy")

# 2. Choose registration recipe (here: loaded from a YAML file. See below for alternatives)
recipe = warpfield.Recipe.from_yaml('default.yml')

# 3. Register moving volume
vol_mov_reg, warp_map, _ = warpfield.register_volumes(vol_ref, vol_mov, recipe)

# 4. Optional: apply the transformation to another volume (same shape and resolution)
vol_another_reg = warp_map.apply(vol_another)

# 5. Optional: apply inverse transformation to the reference volume
vol_ref_reg = warp_map.invert().apply(vol_ref)

# 6. Optional: apply the warp transformation to a set of coordinates (3-by-n array, in units of volume voxels)
points = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
points_pushed = warp_map.push_coordinates(points)
points_pulled = warp_map.invert().push_coordinates(points) # inverse transformation

Backends

warpfield runs on the first available GPU backend: CuPy (NVIDIA GPUs) or MLX (Apple Silicon). To use a different one, call warpfield.set_backend("mlx") (or "cupy", "numpy") before you start. On the command line, use --backend. The numpy backend runs on the CPU; it is slow and mainly meant for testing. warpfield.get_available_backends() lists the backends that work on your machine.

Functions return the same array type you pass in: NumPy in, NumPy out. When calling several warpfield functions in a row, pass GPU arrays (e.g. cupy.asarray(vol)) to avoid copying between CPU and GPU at every call.

Command-Line Interface (CLI)

The warpfield library provides a command-line interface, allowing you to perform registration directly from the terminal. We recommend starting with the Python interface to develop and optimize your recipes interactively. Once you are satisfied with the results, you can use the CLI for batch processing.

Usage

python -m warpfield --fixed <fixed_image_path> --moving <moving_image_path> --recipe <recipe_path> [options]
# You can use the `--help` flag to see instructions for the CLI:
python -m warpfield --help
Further details

Required Arguments

  • --fixed: Path to the fixed 3D volume: .h5/.hdf5, .zarr, .mat, .nii/.nii.gz, .nrrd/.nhdr, .tif/.tiff or .npy. For HDF5, MATLAB and Zarr files, add the dataset, variable or array after the file name, separated by : or / (e.g. data.h5:fixed, data.mat/fixed, store.zarr/fixed). A Zarr store that is itself an array needs no name.
  • --moving: Path to the moving 3D volume, in any of the same formats. Its shape may differ from the fixed volume's, but its voxel size must be the same.
  • --recipe: Path to a recipe YAML file, or the name of a bundled recipe (default.yml, default_opm.yml).

Optional Arguments

  • --output: Path to save the registered volume (.h5). Defaults to <moving>_registered.h5 next to the moving file if not provided. Must not be one of the input files.
  • --compression: Compression method for saving the registered volume. Default is gzip.
  • --invert: Additionally, invert the warp map and warp the fixed image into the space of the moving image (saved as /fixed_reg_inv).
  • --backend: cupy, mlx or numpy (see Backends). Default is auto.

Output Structure

The output file is an HDF5 file containing the following datasets:

  • /moving_reg: The registered moving image.
  • /recipe_json: The recipe used, as JSON.
  • /warp_map: A group containing the warp field and its metadata (load it with warpfield.WarpMap.from_h5(path, group="warp_map")):
    • /warp_field: The displacement field.
    • /block_size: The block size (in voxels).
    • /block_stride: The block stride (in voxels).
    • /ref_shape, /mov_shape: The shapes of the fixed and moving volumes.
  • /fixed_reg_inv (optional): The fixed image warped into the space of the moving image (if --invert is used).

Recipes

The registration pipeline is defined by a recipe. The recipe consists of a pre-filter that is applied to all volumes (typically a DoG filter to sharpen features) and list of levels, each of which contains a set of parameters for the registration process. Typically, each level corresponds to a different resolution of the displacement field (the block size), with the first level being the coarsest and the last level being the finest.

Recipe parameters

Pre-filter parameter Description
clip_thresh Pixel value threshold for clipping each volume. Default is 0. This setting helps remove DC background, which can otherwise cause edges (the shifted volume is 0 outside the FOV).
dog If True, apply a 3D Difference-of-Gaussians (DoG) pre-filter to each volume. Default is True. If False (and σlow > 0), apply a simple Gaussian filter with σlow and ignore σhigh.
low The σlow value for the 3D DoG pre-filter. Default is 0.5
high The σhigh value for the 3D DoG pre-filter. Default is 10.0. Note: σlow and σhigh should be smaller and bigger than the feature of interest, respectively. A σ of 1 correponds to a FWHM of ~ 2.4.)
soft_edge Fade the borders of the volumes to 0 (black). Reduces edge effects for volumes in which the sample extends to the volume border or beyond. Float or list of 3 floats (for each axis): size of the fade in voxels from each border. If required, the fade should be larger than σhigh (above). Defaults to 0.0 (disabled).
Level parameter Description
block_size Shape of blocks, into which the volume is divided. Positive numbers indicate block shape in voxels (e.g. [32, 16, 32]), while negative numbers are interpreted as "divide volume shape by this number" (e.g. [-5, -5, -5] results in 5 blocks along each axis, when block stride is 1.0)
block_stride Determines whether blocks overlap. Either list of 3 integer values (block center distances, or strides, in voxels) or scalar float (fraction of block_size). Default is 1.0 (no block overlap). Set this to a smaller value (e.g. 0.5) for overlaping blocks and higher precision, but larger (e.g. 8x) memory footprint
project.max If True, apply 3D -> 2D max projections to each volume block. If false, apply mean projections. Default is True
project.dog If True, apply a DoG filter to each 2D projection. Default is True
project.low The σlow value for the 2D DoG filter. Default is 0.5 voxels (pixels).
project.high The σhigh value for the 2D DoG filter. Default is 10.0 voxels (pixels).
project.normalize Whether to normalize the projections before calculating the cross-covariance (which would make it a cross-correlation). Defaults to False or 0.0. Values can range from 0.0 (False) to 1.0 (True). Values in between imply normalisation by l2_norm**project.normalize
project.periodic_smooth If True, apply periodic smoothing. Default is False. This can help reduce block-edge effects (affecting FFT-based correlation).
tukey_ref if not None, apply a Tukey window to the reference projections (alpha = tukey_ref). Default is 0.5. The Tukey window can reduce block-edge effects.
smooth.sigmas Sigmas for smoothing cross-correlations across blocks. Default is [1.0, 1.0, 1.0] blocks.
smooth.shear Shear parameter (specific to oblique plane wobble – ignore otherwise). Default is None.
smooth.long_range_ratio Long range ratio for double gaussian kernel. Default is 0.05. To deal with empty or low contrast regions, a second smooth with a larger (5x) sigma is applied to the cross-correlation maps and added. Typical values are between 0 (or None) and 0.1
median_filter If True, apply median filter to the displacement field. Default is True
affine If True, fit an affine transformation to the displacement field (least squares over all block centers). Default is False. Needs at least 2 blocks along at least two axes; use at least 2 blocks along each axis to determine the full 3D transformation. The default affine level (block_size: [-2, -2, -2], block_stride: 0.5) uses 3 blocks per axis.
update_rate Update rate for the displacement field. Default is 1.0. This value can be lowered to dampen oscillations, if needed (rarely).
repeats Number of iterations for this level. More repeats allow each block to deviate further from neighbors, despite smoothing. Typical values range from 1-10. Disable a level by setting repeats to 0.

Defining recipes

Recipes can be loaded from YAML files (either those shipped with this package, such as default.yml, or your own):

recipe = warpfield.Recipe.from_yaml("default.yml")
# or your own recipe:
# recipe = warpfield.Recipe.from_yaml("path/to/your/recipe.yaml")

# You can then modify recipe parameters programmatically, e.g.;
recipe.pre_filter.clip_thresh=10
# ... etc.

Alternatively, you can define a recipe from scratch using the Recipe class. For example:

# create a basic recipe:
recipe = warpfield.Recipe() # initialized with a translation level, followed by an affine registration level
recipe.pre_filter.clip_thresh = 0 # clip DC background, if present

# affine level properties
recipe.levels[-1].repeats = 5

# add non-rigid registration levels:
recipe.add_level(block_size=[128,128,128])
recipe.levels[-1].smooth.sigmas = [1.0,1.0,1.0]
recipe.levels[-1].repeats = 5

recipe.add_level(block_size=[64,64,64])
recipe.levels[-1].block_stride = 0.5
recipe.levels[-1].smooth.sigmas = [1.0,1.0,1.0]
recipe.levels[-1].repeats = 5

recipe.add_level(block_size=[32,32,32])
recipe.levels[-1].block_stride = 0.5
recipe.levels[-1].project.low = 1
recipe.levels[-1].project.high = 2
recipe.levels[-1].smooth.sigmas = [4.0,4.0,4.0]
recipe.levels[-1].smooth.long_range_ratio = 0.1
recipe.levels[-1].repeats = 5

Feedback and contributions

We value your feedback and contributions to improve warpfield! Here's how you can help:

  • Bug reports: If you encounter any issues or unexpected behavior, please open a bug report.
  • Feature requests: Have an idea for a new feature or improvement? Let us know by submitting a feature request.
  • General discussion: Start a conversation in our Discussions. Whether you have questions, ideas, or just want to share how warpfield has helped your work, we'd like to hear from you!
  • Questions: If you have questions about using warpfield, post them in Q&A.

Contributing code or documentation

Whether it's fixing a bug, adding a feature, or improving documentation, your help is appreciated. To contribute, fork the repository, make your changes in a feature branch, and submit a pull request (PR) for review. Please follow these minimum standards:

  • Code Quality: Write clean, readable, and well-documented code.
  • Testing: Include tests for new features or bug fixes.
  • If your change doesn't concern an existing issue or discussion, please create one first to explain the motivation behind your change.

Thank you for your support!

Citing our work

If you use warpfield in your research, please cite the paper that first described our registration approach:

Hoffmann, M., Henninger, J. et al. Blazed oblique plane microscopy reveals scale-invariant inference of brain-wide population activity. Nature Communications 14, 8019 (2023). https://doi.org/10.1038/s41467-023-43741-x

@article{Hoffmann2023,
  title={Blazed oblique plane microscopy reveals scale-invariant inference of brain-wide population activity},
  author={Hoffmann, Maximilian and Henninger, Jorg and Veith, Johannes and Richter, Lars and Judkewitz, Benjamin},
  journal={Nature Communications},
  volume={14},
  number={1},
  pages={8019},
  year={2023},
  publisher={Nature Publishing Group},
  doi={10.1038/s41467-023-43741-x}
}

See also

Metadata

Release files for warpfield 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for warpfield 0.3.0
File Size Uploaded Provenance Actions
warpfield-0.3.0.tar.gz 76.7 kB Without provenance Details for warpfield-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for warpfield 0.3.0
File Interpreter ABI Platform Actions
warpfield-0.3.0-py3-none-any.whl Python 3 none any Details for warpfield-0.3.0-py3-none-any.whl

Total release size: 136.4 kB

Release files / warpfield-0.3.0.tar.gz

Download URL warpfield-0.3.0.tar.gz
Size 76.7 kB
Tags Source
SHA-256 checksum
How to use checksums
2de75203f345f8ab9d962d3a16ad8daa19a52d36feefbdf4e5911d5b0203e315
BLAKE2b-256 checksum
How to use checksums
05140d50d7e08d6c30396d4deb727647118e145c8518b01cc21f47353d38907e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.9.25

Release files / warpfield-0.3.0-py3-none-any.whl

Download URL warpfield-0.3.0-py3-none-any.whl
Size 59.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d867610c9b53757cb9afea5c89b75ecf091a293019416650b8d0b5d087c906bd
BLAKE2b-256 checksum
How to use checksums
8efa450248ff0de5bc1b9437318ceb3b76630323cec999511a81cca8c923fb74
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.9.25

Security for warpfield 0.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page