Public entry points

Top-level functions exposed from neuroreg.

neuroreg.robreg(src, trg, *, src_affine=None, trg_affine=None, src_mask=None, trg_mask=None, return_v2v=False, init_type='centroid', init_transform=None, init_lta=None, initial_r2r=None, dof=6, nmax=5, sat=6.0, symmetric=True, isotropic=True, isotropic_size=None, adaptive_sat=False, target_outlier_pct=5.0, outliers_name=None, stop_level=0, verbose=False, device='cpu')[source]

Register two images with the public IRLS robust-registration path.

Parameters are intentionally close to the tensor-level IRLS pyramid implementation, but this wrapper also accepts filenames and nibabel images.

Parameters:
src, trgImageLike

Moving/source and fixed/target images. Each input may be a path, a nibabel-like image object, or a torch.Tensor volume.

src_affine, trg_affineTensor, optional

Explicit voxel-to-RAS affines to use when src or trg are passed as tensors.

src_mask, trg_maskImageLike, optional

Optional source and target masks. Voxels outside these masks are ignored during IRLS fitting.

return_v2vbool, default=False

If True, return the estimated transform in voxel coordinates. If False, return the corresponding RAS-to-RAS transform.

init_type{“header”, “centroid”, “image_center”}, default=”centroid”

Explicit initialization mode used when no explicit transform is supplied. "image_center" matches FreeSurfer’s cras0-style center start.

init_transformInitTransformLike, optional

Unified explicit initialization transform. This may be an LTA filename, an in-memory LTA, or a 4 x 4 RAS-to-RAS matrix stored as a NumPy array or torch tensor. When provided, it overrides init_type.

init_ltastr, optional

Backward-compatible alias for file-based initialization. Prefer init_transform.

initial_r2rTensor or ndarray, optional

Backward-compatible alias for in-memory RAS-to-RAS initialization. Prefer init_transform.

dofint, default=6

Degrees of freedom. The public IRLS path currently supports rigid registration only, so this must remain 6.

nmaxint, default=5

Maximum number of IRLS outer iterations per pyramid level.

satfloat, default=6.0

Tukey biweight saturation threshold.

symmetricbool, default=True

If True, run symmetric halfway-space registration. This is the default/public robreg behavior.

isotropicbool, default=True

If True, resample to isotropic voxels before building the pyramid.

isotropic_sizefloat, optional

Explicit isotropic voxel size in millimeters. When omitted, the public robreg path derives a shared isotropic size from the source and target voxel sizes.

adaptive_satbool, default=False

Whether to adapt the Tukey saturation threshold based on the observed outlier fraction.

target_outlier_pctfloat, default=5.0

Target outlier percentage used when adaptive_sat is enabled.

outliers_namestr, optional

Output filename for the final outlier map.

stop_levelint, default=0

Finest pyramid level to process. 0 processes all levels. Higher values skip the finest levels for faster coarse-only registration. Mirrors FreeSurfer’s stopres in computeMultiresRegistration.

verbosebool, default=False

If True, emit progress logging from the IRLS implementation.

devicestr, default=”cpu”

Torch device on which to place the image tensors before registration.

Returns:
Tensor

Estimated transform matrix. This is voxel-to-voxel when return_v2v=True and RAS-to-RAS otherwise.

Raises:
ValueError

If dof is anything other than 6, or if multiple explicit initialization transforms are provided.

Parameters:
  • src (str | Path | Any | Tensor)

  • trg (str | Path | Any | Tensor)

  • src_affine (Tensor | None)

  • trg_affine (Tensor | None)

  • src_mask (str | Path | Any | Tensor | None)

  • trg_mask (str | Path | Any | Tensor | None)

  • return_v2v (bool)

  • init_type (Literal['header', 'centroid', 'image_center'])

  • init_transform (str | Path | LTA | Tensor | ndarray | None)

  • init_lta (str | None)

  • initial_r2r (Tensor | ndarray | None)

  • dof (int)

  • nmax (int)

  • sat (float)

  • symmetric (bool)

  • isotropic (bool)

  • isotropic_size (float | None)

  • adaptive_sat (bool)

  • target_outlier_pct (float)

  • outliers_name (str | None)

  • stop_level (int)

  • verbose (bool)

  • device (str)

Return type:

Tensor

neuroreg.multireg(movables, *, masks=None, init_ltas=None, average='median', init_target_index=None, seed=None, fix_target=False, init_type=None, nmax=5, sat=6.0, symmetric=True, device='gpu', use_cras_center=False, template_iterations=None, template_eps=0.03, return_mapped=False, mapped_keep_dtype=False, verbose=False)[source]

Run the FreeSurfer-style multi-timepoint registration pipeline.

Parameters:
movablessequence of ImageLike

Input time-point images or paths to them.

maskssequence of ImageLike or None, optional

Optional per-timepoint masks aligned with movables.

init_ltassequence of TransformLike or None, optional

Optional precomputed LTAs defining the initial timepoint-to-template mappings and template geometry.

average{“mean”, “median”, 0, 1}, default=”median”

Template aggregation mode. Integer aliases match the FreeSurfer CLI.

init_target_indexint or None, optional

Zero-based initial target index. If omitted, select one deterministically from image content.

seedint or None, optional

Seed override for initial target selection. None and 0 recompute the seed from image content.

fix_targetbool, default=False

If True, keep the initial target geometry instead of constructing an unbiased mean-space template grid.

init_typeInitType or None, optional

Pairwise registration initialization mode.

nmaxint, default=5

Maximum number of outer IRLS iterations per pairwise registration.

satfloat, default=6.0

Tukey biweight saturation threshold for robust pairwise registration.

symmetricbool, default=True

Whether pairwise registrations should use symmetric halfway-space updates.

devicestr, default=”gpu”

Torch device string forwarded to the pairwise kernel.

use_cras_centerbool, default=False

If True, center the template geometry on the average CRAS instead of the average mapped intensity centroid.

template_iterationsint or None, optional

Maximum number of global template-refinement passes. None uses the built-in defaults for two versus three-or-more time points.

template_epsfloat, default=0.03

Convergence threshold in millimeters for the maximum per-iteration transform change.

return_mappedbool, default=False

If True, include mapped images in the returned result.

mapped_keep_dtypebool, default=False

If True, preserve source dtypes for returned mapped images and cast the output template to the initial target time point’s dtype (clipping cubic-interpolation over/undershoot instead of rescaling).

verbosebool, default=False

Whether to enable verbose pairwise-registration logging.

Returns:
MultiRegResult

Template image, final transforms, LTAs, iteration metadata, and optional mapped images.

Raises:
ValueError

If the inputs are invalid, incompatible in geometry, or the requested iteration settings are inconsistent.

Parameters:
  • movables (Sequence[str | Path | Any])

  • masks (Sequence[str | Path | Any | None] | None)

  • init_ltas (Sequence[str | Path | LTA] | None)

  • average (str | int)

  • init_target_index (int | None)

  • seed (int | None)

  • fix_target (bool)

  • init_type (Literal['header', 'centroid', 'image_center'] | None)

  • nmax (int)

  • sat (float)

  • symmetric (bool)

  • device (str)

  • use_cras_center (bool)

  • template_iterations (int | None)

  • template_eps (float)

  • return_mapped (bool)

  • mapped_keep_dtype (bool)

  • verbose (bool)

Return type:

MultiRegResult

neuroreg.coreg(src, trg, src_mask=None, trg_mask=None, lta_name=None, mapped_name=None, keep_dtype=False, return_v2v=False, init_type='image_center', init_lta=None, method='powell', symmetric=True, dof=6, n=30, level_iters=None, loss_name='mse', loss_beta=None, loss_bins=32, optimizer='adam', lr=None, translation_weight_scale=1.0, rotation_weight_scale=4.0, scale_weight_scale=1.0, shear_weight_scale=1.0, min_voxels=16, max_voxels=None, isotropic=False, device='cpu', powell_brute_force_limit=30.0, powell_brute_force_iters=1, powell_brute_force_samples=30, powell_maxiter=4, powell_sep=4, trace_fn=None)[source]

Run public image-to-image registration.

Parameters:
src, trgstr or nibabel image

Moving and reference images.

src_mask, trg_maskoptional

Optional masks in moving/source and reference/target space. Voxels outside these masks are excluded from the similarity objective.

lta_name, mapped_namestr or None, optional

Optional output paths for the final transform and mapped moving image.

keep_dtypebool, default=False

If True, cast the final mapped moving image back to the source image dtype when mapped_name is requested. When False, mapped output is written as float32.

return_v2vbool, default=False

Return the final transform in voxel coordinates instead of RAS.

init_type{“header”, “centroid”, “image_center”}, default=”image_center”

Initialization strategy for the selected backend when init_lta is not provided.

init_ltastr, optional

Existing LTA used for initialization. When provided, it overrides the requested init_type.

method{“powell”, “gd”}, default=”powell”

Registration backend. "powell" uses the MRI_coreg-style brute-force plus Powell path; "gd" runs the legacy PyTorch gradient-descent pyramid.

symmetric, dof, n, level_iters, loss_name, loss_beta, loss_bins, optimizer, lr

Gradient-descent backend options.

*_weight_scalefloat

Parameter-block scaling forwarded to the GD registration model.

min_voxels, max_voxels, isotropic, device

Pyramid and device settings.

powell_brute_force_limit, powell_brute_force_iters, powell_brute_force_samples

Coarse search settings for the Powell backend.

powell_maxiterint, default=4

Maximum Powell refinement iterations.

powell_sepint, default=4

Sampling spacing for the Powell evaluator.

trace_fncallable, optional

Optional callback receiving backend-specific progress events.

Returns:
Tensor

Final RAS-to-RAS transform by default, or voxel-to-voxel when return_v2v=True.

Raises:
ValueError

If method is not "powell" or "gd".

Parameters:
  • src (str | Nifti1Image)

  • trg (str | Nifti1Image)

  • src_mask (str | SpatialImage | Tensor | None)

  • trg_mask (str | SpatialImage | Tensor | None)

  • lta_name (str | None)

  • mapped_name (str | None)

  • keep_dtype (bool)

  • return_v2v (bool)

  • init_type (Literal['header', 'centroid', 'image_center'])

  • init_lta (str | None)

  • method (str)

  • symmetric (bool)

  • dof (int)

  • n (int)

  • level_iters (list[int] | tuple[int, ...] | None)

  • loss_name (str)

  • loss_beta (float | None)

  • loss_bins (int)

  • optimizer (str)

  • lr (float | None)

  • translation_weight_scale (float)

  • rotation_weight_scale (float)

  • scale_weight_scale (float)

  • shear_weight_scale (float)

  • min_voxels (int)

  • max_voxels (int | None)

  • isotropic (bool)

  • device (str)

  • powell_brute_force_limit (float)

  • powell_brute_force_iters (int)

  • powell_brute_force_samples (int)

  • powell_maxiter (int)

  • powell_sep (int)

Return type:

Tensor

neuroreg.bbreg(mov, lh_surf=None, rh_surf=None, lh_thickness=None, rh_thickness=None, ref=None, subject_dir=None, seg=None, lta_name=None, dof=6, contrast=None, init_type='header', init_lta=None, init_ras=None, cost_type='contrast', wm_proj_abs=1.4, gm_proj_frac=0.5, gm_proj_abs=None, lh_cortex_label=None, rh_cortex_label=None, slope=0.5, gradient_weight=0.0, subsample=1, n_iters=200, lr=0.01, early_stop_patience=20, device='cpu', return_model=False)

Register a moving image to cortical surface boundaries using BBR.

This is the main Python API for the boundary-based registration path. The moving image is aligned to a target anatomical space defined either by a FreeSurfer/FastSurfer subject directory, explicit white-matter surface files plus a reference image, or a segmentation from which surfaces are extracted on the fly.

Public transform direction is always moving/source -> target/reference. That convention applies to init_ras, init_lta, the returned tensor, and any written LTA. Internally the BBR model optimizes the inverse transform because that is the natural parameterization for sampling the moving volume at target-surface locations, but that internal detail is hidden at the API boundary.

Parameters:
movstr or nib.Nifti1Image

Moving/source image to align into the target/reference space.

lh_surf, rh_surfstr, optional

Explicit left/right white-matter surface files for surface-input mode.

lh_thickness, rh_thicknessstr, optional

Optional cortical thickness files paired with lh_surf and rh_surf.

refstr or nib.Nifti1Image, optional

Reference anatomical image used with explicit-surface mode.

subject_dirstr, optional

FreeSurfer/FastSurfer subject directory providing surfaces and mri/orig.mgz.

segstr, optional

Segmentation volume used to extract white-matter surfaces on the fly.

lta_namestr, optional

Output path for a written LTA in public moving -> target direction.

dofint, default=6

Transformation degrees of freedom.

contrast{“t1”, “t2”}, optional

Expected image contrast for the BBR intensity model. When None, the model auto-detects the polarity.

init_type{“header”, “lta”}, default=”header”

Initialization source when init_ras is not supplied.

init_ltastr, optional

Existing LTA used for initialization. It must encode a moving/source -> target/reference transform.

init_rasndarray, optional

Initial 4x4 RAS-to-RAS transform in public moving/source -> target/reference direction.

cost_type{“contrast”, “gradient”, “both”}, default=”contrast”

Cost terms included in the BBR objective.

wm_proj_absfloat, default=1.4

White-matter sampling depth in millimetres.

gm_proj_fracfloat, default=0.5

Gray-matter sampling depth as a fraction of cortical thickness.

gm_proj_absfloat, optional

Absolute gray-matter projection depth overriding gm_proj_frac.

lh_cortex_label, rh_cortex_labelstr, optional

Optional cortex label files restricting sampled vertices.

slopefloat, default=0.5

Slope of the sigmoid used in the contrast cost.

gradient_weightfloat, default=0.0

Relative weight of the gradient term when cost_type='both'.

subsampleint, default=1

Use every subsample-th surface vertex during optimization.

n_itersint, default=200

Maximum number of RMSprop iterations.

lrfloat, default=0.01

RMSprop learning rate.

early_stop_patienceint, default=20

Stop after this many non-improving iterations. Set 0 to disable early stopping.

devicestr, default=”cpu”

Torch device on which to run the optimization.

return_modelbool, default=False

If True, also return the fitted BBRModel for debugging or inspection.

Returns:
torch.Tensor or tuple[torch.Tensor, BBRModel]

By default, returns the best-found RAS-to-RAS transform in public moving/source -> target/reference direction. When return_model=True, also returns the fitted BBRModel.

Raises:
ValueError

If the requested input mode is incomplete or unsupported.

RuntimeError

If optimization fails to produce any valid iterate.

Parameters:
  • mov (str | Nifti1Image)

  • lh_surf (str | None)

  • rh_surf (str | None)

  • lh_thickness (str | None)

  • rh_thickness (str | None)

  • ref (str | Nifti1Image | None)

  • subject_dir (str | None)

  • seg (str | None)

  • lta_name (str | None)

  • dof (int)

  • contrast (Literal['t1', 't2'] | None)

  • init_type (Literal['header', 'lta'])

  • init_lta (str | None)

  • init_ras (ndarray | None)

  • cost_type (Literal['contrast', 'gradient', 'both'])

  • wm_proj_abs (float)

  • gm_proj_frac (float)

  • gm_proj_abs (float | None)

  • lh_cortex_label (str | None)

  • rh_cortex_label (str | None)

  • slope (float)

  • gradient_weight (float)

  • subsample (int)

  • n_iters (int)

  • lr (float)

  • early_stop_patience (int)

  • device (str)

  • return_model (bool)

Return type:

Tensor | tuple[Tensor, BBRModel]

neuroreg.segreg(seg, target_seg=None, *, centroids=None, dof=6, labels=None, label_set=None, min_common_labels=None, flipped=False, midslice=None)[source]

Register a moving segmentation to another target via label centroids.

Parameters:
segImageLike

Moving segmentation image. This may be a path or a nibabel-like image.

target_segImageLike or None, optional

Target segmentation image for segmentation-to-segmentation registration.

centroidsstr or Path or None, optional

Path to a centroid target JSON file or the name of a bundled centroid target such as "fsaverage".

dof{3, 6, 7, 9, 12}, default=6

Degrees of freedom for the closed-form fit. 3 selects translation-only, 6 rigid, 7 rigid plus global scale, 9 rigid plus anisotropic scaling without shear, and 12 affine registration.

labelslist[int] or None, optional

Explicit label subset override.

label_set{‘all_shared’, ‘target_centroids’, ‘cortex_lr_pairs’} or None, optional

Named label preset. Mode-specific defaults are used when omitted.

min_common_labelsint or None, optional

Minimum number of matched labels required to proceed. When omitted, the default is 1 for translation-only, 3 for rigid/similarity, and 4 for anisotropic-scale or affine registration.

flippedbool, default=False

If True, ignore external targets and register the moving segmentation to a left-right flipped self target for upright or midspace use cases.

midslicefloat or None, optional

Explicit sagittal mid-slice used only with flipped=True. When omitted, the geometric center of the moving image is used.

Returns:
RegistrationResult

Result object containing the recovered RAS transform, participating labels, and target geometry metadata.

Raises:
ValueError

If the arguments define no valid target, define multiple targets, or do not provide enough matched labels for the requested fit.

Parameters:
  • seg (str | Path | Any)

  • target_seg (str | Path | Any | None)

  • centroids (str | Path | None)

  • dof (int)

  • labels (list[int] | None)

  • label_set (Literal['all_shared', 'target_centroids', 'cortex_lr_pairs'] | None)

  • min_common_labels (int | None)

  • flipped (bool)

  • midslice (float | None)

Return type:

RegistrationResult