Download notebook

02 · Create an alignment pair

Simulate DLPFC section 151675, rotate it by 35°, and crop it to the original window. Retained spot IDs give the ground-truth matches. Data and environment setup

[1]:
from pathlib import Path
import sys
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import anndata as ad
import FEAST

TUTORIAL = Path.cwd() if Path.cwd().name == "tutorial" else Path.cwd() / "tutorial"
sys.path.insert(0, str(TUTORIAL))
from _utils import data_root, load_counts, spatial_panel
DATA = data_root()

OUT = TUTORIAL / "outputs" / "02"
OUT.mkdir(parents=True, exist_ok=True)
print("FEAST", FEAST.__version__)
FEAST 1.0.6
[2]:
from FEAST.alignment import rotate_spatial, apply_spatial_transform
reference = load_counts(DATA / "dlpfc/151675.h5ad", "ground_truth")

Simulate and rotate

Offset the rotation center by half the window’s half-width along both axes. Cropping removes spots that rotate outside the window.

[3]:
%%capture --no-stderr
base = FEAST.simulate(
    reference, seed=2026, parameter_mode="hungarian", spatial_mode="reference_rank",
    assignment_solver="scipy", assignment_blocks=False, verbose=False,
)
[4]:
xy = np.asarray(reference.obsm["spatial"])
plate = np.array([xy.min(axis=0), xy.max(axis=0)])
center = plate.mean(axis=0) + 0.5 * (plate[1] - plate[0]) / 2
moving = rotate_spatial(base, angle_degrees=35, center=center, plate_bounds=plate)
print(f"Retained {moving.n_obs:,}/{reference.n_obs:,} spots ({moving.n_obs/reference.n_obs:.1%})")
Retained 2,918/3,565 spots (81.9%)

Recover the known matches

Apply the inverse rotation to the moving coordinates and compare them with the original positions of the retained spots.

[5]:
truth = moving.uns["feast_alignment_transform"]
restored_xy = apply_spatial_transform(moving.obsm["spatial"], truth["inverse_matrix"])
matched_xy = reference[moving.obs_names].obsm["spatial"]
np.testing.assert_allclose(restored_xy, matched_xy, atol=1e-8)
fig, axes = plt.subplots(1, 3, figsize=(13, 4), layout="constrained")
spatial_panel(axes[0], xy, reference.obs["ground_truth"], "Full reference", True)
spatial_panel(axes[1], moving.obsm["spatial"], moving.obs["ground_truth"], "35° rotation + crop", True)
spatial_panel(axes[2], restored_xy, moving.obs["ground_truth"], "Known inverse (retained spots)", True)
for ax in axes:
    ax.set_xlim(plate[0, 0], plate[1, 0])
    ax.set_ylim(plate[1, 1], plate[0, 1])
plt.show()
../_images/notebooks_02_alignment_7_0.png
[6]:
# Export expression and geometry only; keep known transforms and labels out of method inputs.
for name, data in [("reference", reference), ("moving", moving)]:
    method_input = ad.AnnData(X=data.X.copy(), obs=pd.DataFrame(index=data.obs_names),
                             var=pd.DataFrame(index=data.var_names))
    method_input.obsm["spatial"] = data.obsm["spatial"].copy()
    method_input.write_h5ad(OUT / f"{name}.h5ad")
pd.DataFrame({"moving_id": moving.obs_names, "reference_id": moving.obs_names}).to_csv(
    OUT / "correspondence.csv", index=False,
)

The right panel shows the recovered positions. The two exported H5ADs contain expression and coordinates. Use correspondence.csv to evaluate an alignment method.