Align Module API Reference
Follow the Broad–Allen mouse-brain preprocessing and alignment notebook for cluster-centroid registration, neighborhood-overlap refinement, and CellCloud export. Its visualization companion opens the prepared data in linked views.
Alignment and registration of spatial single-cell data.
Covers three related registration problems: (1) stitching serial 3D tissue slices into a shared coordinate frame, (2) registering data onto a reference (e.g. a common coordinate framework/atlas such as the Allen Institute mouse brain, or a particular dataset within a cohort), and (3) registering across modalities (e.g. Xenium to H&E). All three align in physical (spatial) coordinates — image/tissue pixel or micron space. Batch correction / integration in expression or embedding space (e.g. Harmony, scVI, Seurat anchors) is a different problem and out of scope here, though a shared framework for evaluating alignment quality could plausibly extend to that space later.
Status: initial sketch. Implemented: a three-step serial-slice pipeline,
each step an independently reusable artifact. (1) calc_landmarks
computes landmarks from shared cluster labels (accepting a list of
AnnData or one combined AnnData, no manual per-slice loop needed),
or a manually-placed landmark table in the same shape (a plain
DataFrame, not a GeoDataFrame of shapely geometry, so it stays
trivially disk-portable; e.g. from Landmark, a
point-drawing widget pairing with Landscape) can be used instead, or
concatenated alongside it for a semi-manual mix. (2)
calc_alignment_transform fits a rigid Procrustes
(fit_transform_procrustes, always without scaling — see
celldega.align.serial_slices) or non-rigid thin-plate-spline
(fit_transform_tps) transform per slice from those landmarks —
chain-walking outward from a reference slice against a window of
already-aligned neighbors (alignment_window, never a single distant
reference), optionally weighting landmarks by cell count
(weight_by_adjacent_counts) and recording per-landmark leave-one-out
residuals (leave_one_out_residuals) — and returns a
SerialAlignmentTransform: a
first-class, reusable object (not a byproduct that only lives inside one
alignment call) that can be applied to other point data tied to the same
slices (segmentation-polygon vertices, transcript coordinates, eventually
raster sampling grids) via .apply_to_points(), and persisted with
.save()/.load() (a plain directory of .npz/.parquet/.json
files, no pickle required, though it's picklable too), and visually
sanity-checked with plot_alignment (also available as
transform.plot()): a 2D before/after scatter of the fitted landmarks,
so a bad fit (or a mislabeled landmark) is visible at a glance rather than
only showing up downstream. (3)
align_serial_slices applies a given transform to a specific set of
AnnData, aligning obsm["spatial"] and assigning a Z coordinate;
landmarks_initial/landmarks_aligned/fit parameters are also recorded in
the output's uns["align_serial_slices"] for at-a-glance provenance.
The aligned AnnData is a plain 3D point cloud: write it to DegaFiles for a
Celldega CellCloud with celldega.pre.write_point_cloud_dataset.
Planned: a reference/atlas-registration method sharing the same
landmark-based core (star topology onto one fixed reference, vs.
align_serial_slices's neighbor-chain) and image-based
modality-to-modality registration (deferred — unlike the two centroid-based
methods, this operates on raw image data, not single-cell coordinates).
SerialAlignmentTransform
dataclass
A fitted, reusable serial-slice alignment.
Returned by calc_alignment_transform; consumed by
align_serial_slices. Holds one Transform
per slice (the reference slice's is an identity transform) and provenance
from the fit — no Z information, since Z assignment doesn't affect the
spatial fit at all and is decided when applying the transform (see
align_serial_slices's z_space/z_coord), not when fitting
it. Persist it with save/load — everything here is plain
data or a picklable-but-not-pickled RBFInterpolator, so it also
survives a plain pickle round-trip if that's more convenient.
apply_to_points(slice_id, points)
Apply the fitted transform for slice_id to an (n, 2) array of points.
The general reuse primitive: works identically for cell coordinates, segmentation-polygon vertices, transcript coordinates, or any other point data tied to that slice.
load(path)
classmethod
Load a transform previously saved with save.
plot(**kwargs)
2D before/after scatter of this alignment — a quick visual check
of fit quality. Pass adatas= (the slices this was fit from) to
overlay the actual cell centroids, which is what really shows whether
the tissue aligns; see plot_alignment
for all accepted options.
save(path)
Save this transform to a directory of plain files — no pickle.
Layout: metadata.json (fit parameters, slice ids),
transform_log.json (per-slice diagnostics), landmarks_initial
.parquet/landmarks_aligned.parquet, and one transforms/<slice
id>.npz per slice (see save_transform).
align_serial_slices(adatas, transform, z_space=1.0, z_coord=None, key_added='Z', cell_name_prefix=False)
Apply a fitted SerialAlignmentTransform to a set of AnnData.
Z assignment lives here, not in calc_alignment_transform — it
doesn't affect the spatial fit at all, so the same fitted transform can
be applied with different Z choices without refitting anything.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
adatas
|
AnnData | list[AnnData]
|
Either a list of per-slice |
required |
transform
|
SerialAlignmentTransform
|
A |
required |
z_space
|
float
|
Uniform distance between consecutive slices, applied
outward from |
1.0
|
z_coord
|
list[float] | None
|
Explicit absolute Z value for each slice (length
|
None
|
key_added
|
str
|
Name of the new per-cell |
'Z'
|
cell_name_prefix
|
bool
|
If |
False
|
Returns:
| Type | Description |
|---|---|
AnnData
|
A new |
AnnData
|
x/y columns replaced by the aligned coordinates, a new |
AnnData
|
|
AnnData
|
landmark provenance recorded in |
AnnData
|
(plain, h5ad-safe data — the live |
AnnData
|
not stored there; keep or persist it separately, see |
AnnData
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
calc_alignment_transform(landmarks, slice_attr=None, reference=0, min_shared_landmarks=3, alignment_window=1, method='procrustes', allow_reflection=False, smoothing=0.0, degree=1, area_regularization=0.0, shape_regularization=0.0, weight_by_adjacent_counts=True, manual_landmark_weight='equal', compute_residuals=True)
Fit a serial-slice alignment transform from corresponding landmarks.
Each slice is registered onto a window of its already-aligned neighbors
by fitting a transform between corresponding landmarks. Alignment
proceeds as a chain outward from reference in both directions along
the slice order, so deformation is modeled between nearby physical
neighbors rather than against a single distant reference. This function
only touches landmarks — no cell data — so the returned transform
can be fit once and reused (see align_serial_slices and
SerialAlignmentTransform.apply_to_points). Z assignment isn't
part of this fit — it doesn't affect the spatial transform at all — see
align_serial_slices's z_space/z_coord instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
landmarks
|
DataFrame
|
A plain |
required |
slice_attr
|
str | None
|
The column in |
None
|
reference
|
int
|
Index (into the slice order) of the slice whose transform is the identity; other slices are aligned outward from it. |
0
|
min_shared_landmarks
|
int
|
Minimum number of landmark labels a slice and its neighbor window must share to fit a transform between them. |
3
|
alignment_window
|
int
|
Number of already-aligned neighboring slices (in
the same chain direction) to register each new slice against,
instead of only the single immediately-previous one. A landmark
label's target position is averaged across whichever of those
neighbors have it. Stays a local, neighbor-window operation —
never reaches back to a single distant reference — while
reducing sensitivity to any one neighbor's noise. |
1
|
method
|
str
|
|
'procrustes'
|
allow_reflection
|
bool
|
|
False
|
smoothing
|
float
|
|
0.0
|
degree
|
int
|
|
1
|
area_regularization
|
float
|
|
0.0
|
weight_by_adjacent_counts
|
bool
|
If |
True
|
manual_landmark_weight
|
str
|
How a landmark with no cell count (e.g. one
placed by hand) is weighted when
|
'equal'
|
compute_residuals
|
bool
|
If |
True
|
Returns:
| Type | Description |
|---|---|
SerialAlignmentTransform
|
The fitted |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
calc_landmarks(adatas, cluster_key, slice_attr=None, label_prefix='C-')
Compute one landmark per cluster label, at that cluster's centroid.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
adatas
|
AnnData | list[AnnData]
|
A single |
required |
cluster_key
|
str
|
|
required |
slice_attr
|
str | None
|
For a single combined |
None
|
label_prefix
|
str
|
Prepended to each cluster label to form the landmark
|
'C-'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
A |
DataFrame
|
label, as |
DataFrame
|
slice's own |
DataFrame
|
of cells in that cluster), and |
DataFrame
|
here) — plus a |
DataFrame
|
slices. This is the shape |
DataFrame
|
|
DataFrame
|
|
DataFrame
|
columns, |
DataFrame
|
see |
DataFrame
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
fit_transform_procrustes(source, target, weights=None, allow_scaling=True, allow_reflection=False)
Fit the rotation/scale/translation that best maps source onto target.
Solves the classic Procrustes/Umeyama least-squares problem: minimize
sum(weights_i * ||target_i - (scale * rotation @ source_i + translation)||^2)
over a rotation, a single uniform scale, and a translation, given n
point-to-point correspondences (source[i] corresponds to target[i]).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
ndarray
|
|
required |
target
|
ndarray
|
|
required |
weights
|
ndarray | None
|
Optional |
None
|
allow_scaling
|
bool
|
If |
True
|
allow_reflection
|
bool
|
If |
False
|
Returns:
| Type | Description |
|---|---|
SimilarityTransform
|
The fitted |
Raises:
| Type | Description |
|---|---|
ValueError
|
If fewer than 2 point pairs are given, shapes mismatch, or
|
fit_transform_tps(source, target, weights=None, smoothing=0.0, degree=1, normalize=True, area_regularization=0.0, shape_regularization=0.0)
Fit a thin-plate-spline warp that maps source landmarks onto target landmarks.
Unlike fit_transform_procrustes, this fits a smooth non-rigid
deformation: it matches the landmarks locally rather than one global
rotation/scale/translation, so it can recover warps a rigid fit cannot
(e.g. non-uniform section stretching). Points far from every landmark
fall back toward the affine (degree-1 polynomial) component rather than
an arbitrary extrapolation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
ndarray
|
|
required |
target
|
ndarray
|
|
required |
weights
|
ndarray | None
|
Optional |
None
|
smoothing
|
float
|
Bending-energy penalty trading exact landmark matching
( |
0.0
|
degree
|
int
|
Degree of the polynomial term added to the spline ( |
1
|
normalize
|
bool
|
If |
True
|
area_regularization
|
float
|
Penalty in |
0.0
|
shape_regularization
|
float
|
Penalty in Both are applied as a single post-fit correction: the warp's
global affine |
0.0
|
Returns:
| Type | Description |
|---|---|
ThinPlateSplineTransform
|
The fitted |
Raises:
| Type | Description |
|---|---|
ValueError
|
If fewer than 3 point pairs are given, shapes mismatch,
|
leave_one_out_residuals(source, target, fit_transform, weights=None)
Per-landmark leave-one-out residual: how well does the fit implied by the other landmarks predict this one?
In-sample residual is a poor diagnostic for an interpolating fit (e.g.
fit_transform_tps at smoothing=0 matches every landmark
exactly by construction, regardless of whether the landmarks are actually
consistent). Leave-one-out residual instead measures, for each landmark,
whether it agrees with a fit built from everything except it — a large
value flags a landmark that may be mislabeled, noisy, or otherwise
inconsistent with the rest.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
ndarray
|
|
required |
target
|
ndarray
|
|
required |
fit_transform
|
Callable[..., Transform]
|
A |
required |
weights
|
ndarray | None
|
Optional |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
An |
ndarray
|
whose leave-one-out refit failed (e.g. too few or degenerate points |
ndarray
|
remained). |
load_transform(path)
Load a transform previously saved with save_transform.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the |
required |
Returns:
| Type | Description |
|---|---|
Transform
|
The reconstructed |
Transform
|
|
Transform
|
|
Transform
|
numerically equivalent to the one originally fitted. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the file's |
neighborhood_alignment(shapes, initial_transform, slice_attr='slice_id', cluster_attr='cluster_id', alignment_window=None, n_sweeps=2, rotation_range=10.0, translation_range=0.1, n_rotation_grid=7, distance_weight='inverse', distance_decay=1.0, simplify_tolerance=None, min_shared_clusters=1, compute_diagnostics=True, progress_every=0)
Refine a serial-slice alignment by maximizing neighborhood polygon overlap.
Starts from initial_transform (a cluster-centroid Procrustes fit from
calc_alignment_transform) and adds,
per slice, a small residual rigid transform (rotation + translation, never
scale) chosen to maximize the summed intersection area of corresponding
neighborhood regions across a window of neighboring slices. This recovers
alignment that region centroids miss — footprint orientation and bilateral
structure a centroid averages away — while staying rigid and reusing the
Procrustes fit as a starting point close enough for the (nonsmooth) overlap
objective to optimize locally. The regions are typically cluster alpha
shapes, but any per-(slice, region) polygons with labels shared across
slices work (manually drawn regions, other domain-ID algorithms).
Optimization is block coordinate descent: the reference slice is held
fixed, and every other slice is optimized in turn against its neighbors'
current estimates, in alternating forward and backward passes over
n_sweeps sweeps. Each per-slice step coarse-searches residual rotation
on a grid, then refines all three parameters with a bounded Powell search
(see _refine_one_slice).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shapes
|
GeoDataFrame
|
A per-(slice, region) polygon |
required |
initial_transform
|
SerialAlignmentTransform
|
The Procrustes
|
required |
slice_attr
|
str
|
Column in |
'slice_id'
|
cluster_attr
|
str
|
Column in |
'cluster_id'
|
alignment_window
|
int | None
|
Number of neighboring slices on each side to score a
slice's overlap against. |
None
|
n_sweeps
|
int
|
Number of forward+backward coordinate-descent sweeps over the non-reference slices. |
2
|
rotation_range
|
float
|
Bound (in degrees) on each slice's residual rotation,
|
10.0
|
translation_range
|
float
|
Bound on each slice's residual translation, as a
fraction of the overall tissue width (largest x/y extent across all
shapes), applied |
0.1
|
n_rotation_grid
|
int
|
Number of grid points in the coarse residual-rotation
search over |
7
|
distance_weight
|
str
|
How a neighbor's overlap contribution falls off with
slice separation |
'inverse'
|
distance_decay
|
float
|
Falloff scale for the |
1.0
|
simplify_tolerance
|
float | None
|
If given, Douglas-Peucker tolerance applied to each
alpha shape before optimization, to speed up intersection at the
cost of boundary detail. |
None
|
min_shared_clusters
|
int
|
A slice is only refined if it shares at least this many cluster labels with its neighbor window; otherwise its residual stays identity (it keeps its Procrustes transform) and it is marked skipped in the transform log. |
1
|
compute_diagnostics
|
bool
|
If |
True
|
progress_every
|
int
|
If |
0
|
Returns:
| Type | Description |
|---|---|
SerialAlignmentTransform
|
A refined |
SerialAlignmentTransform
|
with |
SerialAlignmentTransform
|
residual delta composed with its initial Procrustes transform, ready to |
SerialAlignmentTransform
|
pass to |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
plot_alignment(transform, adatas=None, slice_attr=None, color_by='slice', max_cells_per_slice=20000, cell_size=1.0, figsize=(12, 6), random_state=0)
Side-by-side 2D scatter of an alignment, before vs. after fitting.
"Before" is each slice in its own native coordinates; "after" is every slice warped into the reference slice's frame by its fitted transform.
Pass adatas (strongly recommended) to overlay each slice's actual
cell centroids underneath the landmarks — that's what actually shows
whether the tissue aligns. Landmarks alone are a poor check: an
interpolating fit lands every landmark exactly on top of its match by
construction, so the landmark-only "after" panel looks perfect
regardless of how well the surrounding tissue really lines up.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
transform
|
SerialAlignmentTransform
|
A fitted |
required |
adatas
|
AnnData | list[AnnData] | None
|
The same slices used to fit |
None
|
slice_attr
|
str | None
|
For a single combined |
None
|
color_by
|
str
|
|
'slice'
|
max_cells_per_slice
|
int
|
Randomly subsample each slice's centroids to at
most this many before plotting ( |
20000
|
cell_size
|
float
|
Marker size for cell centroids (landmarks are drawn larger, on top). |
1.0
|
figsize
|
tuple[float, float]
|
Passed to |
(12, 6)
|
random_state
|
int
|
Seed for the subsampling RNG, so the figure is reproducible. |
0
|
Returns:
| Type | Description |
|---|---|
Figure
|
|
tuple[Axes, Axes]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
save_transform(transform, path)
Save a fitted SimilarityTransform or ThinPlateSplineTransform
to a plain .npz file — no pickle involved, so the result is portable,
inspectable with any numpy install, and doesn't depend on matching library
versions the way a pickled object graph would. A ThinPlateSplineTransform
is saved as the plain-array inputs (landmark positions, per-point smoothing,
kernel, epsilon, degree, plus the source normalization center/scale) that
reconstruct an equivalent RBFInterpolator, not the fitted object itself.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
transform
|
Transform
|
The transform to save. |
required |
path
|
str | Path
|
Destination |
required |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
transform_shapes(shapes, transform, slice_attr='slice_id')
Apply a serial-slice transform to an alpha-shape GeoDataFrame.
Moves each shape's geometry by its slice's fitted transform, in place of
recomputing alpha shapes from transformed cell coordinates. Handy for
inspecting or plotting the refined neighborhood shapes (the polygon
companion to
apply_to_points).
Any Z coordinate is passed through unchanged, so note it does not restamp
the aligned per-slice Z — for a 3D NeighborhoodCloud, recompute the shapes
from the aligned cells with celldega.nbhd.alpha_shape_cell_clusters_by_slice
(which stamps Z consistently) rather than feeding transformed shapes
directly. The area column, if present, is recomputed from the
transformed (rigid, so area-preserving) geometry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shapes
|
GeoDataFrame
|
Alpha shapes with a |
required |
transform
|
SerialAlignmentTransform
|
A fitted
|
required |
slice_attr
|
str
|
Column in |
'slice_id'
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
A copy of |
GeoDataFrame
|
Rows whose slice id is not in |