Visium visium affine only

Visium visium affine only#

Two Visium sections, spots rather than cells: about 250 points each, and their coordinates are array indices spanning roughly 6 to 29 rather than microns. Every length in the solver is in those units, which is why dx is 1 and not 30, and why a is 5 and not 500 – the defaults are tuned for micron-scale data and would put the whole section inside a single raster cell.

Upstream’s equivalent is visium-visium-alignment-affine-only. One call does the alignment: stalign_align_obs fits a diffeomorphism straight between two point clouds, rasterizing both sides itself.

STalign’s own version of this analysis: visium-visium-alignment-affine-only.

Inputs#

import anndata as ad, numpy as np, pandas as pd

# No header in these files, so a plain `read_csv` would promote the first spot to column
# names and silently drop it.
def read_headerless(path):
    xy = pd.read_csv(path, header=None).to_numpy(dtype=float)
    return ad.AnnData(X=np.zeros((len(xy), 1)), obsm={'spatial': xy})

ref = read_headerless('visium_data/slice2_coor.csv')
query = read_headerless('visium_data/slice1_coor.csv')
print(f'{ref.n_obs} reference cells, {query.n_obs} query cells')
251 reference cells, 254 query cells

The fit#

Upstream’s own solver values, and squidpy’s defaults for everything else.

from squidpy.experimental.tl import stalign_align_obs

fit = stalign_align_obs(
    ref, query, spatial_key='spatial',
    dx=1.0, blur=1.0, niter=1000, a=5.0, diffeo_start=1001,
)
print(f'{fit.n_iter} iterations, objective '
      f'{float(fit.energies[0]):.0f} -> {float(fit.energies[-1]):.0f}')
1000 iterations, objective 8 -> 1

Where the cells land#

StalignFit.transform writes the mapped coordinates straight back into the query’s obsm, so the alignment ends up on the object rather than in a local variable. It evaluates the fitted map at each point, so a cell lands where it lands rather than at the nearest raster cell.

import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from scipy.spatial import cKDTree

fit.transform(query, key_added='aligned')
moved = query.obsm['aligned']

# Whether the fit worked, in the units of the data rather than of the objective. The energy
# can halve while the sections stay as far apart as they started -- that is what an iteration
# budget that ran out looks like, and it is invisible in the energy alone.
tree = cKDTree(ref.obsm['spatial'])
before = tree.query(query.obsm['spatial'])[0]
after = tree.query(moved)[0]
print(f"centroid offset {np.linalg.norm(query.obsm['spatial'].mean(0) - ref.obsm['spatial'].mean(0)):.0f}"
      f" -> {np.linalg.norm(moved.mean(0) - ref.obsm['spatial'].mean(0)):.0f}")
print(f'distance to the nearest reference cell: median {np.median(before):.0f} -> '
      f'{np.median(after):.0f}, 90th percentile {np.percentile(before, 90):.0f} -> '
      f'{np.percentile(after, 90):.0f}')

fig, ax = plt.subplots(1, 2, figsize=(12, 5.5))
for a, (pts, title) in zip(ax, [(query.obsm['spatial'], 'before'),
                                (moved, 'after the fit')], strict=True):
    a.scatter(*ref.obsm['spatial'].T, s=0.12, alpha=0.3, label='reference')
    a.scatter(*pts.T, s=0.12, alpha=0.3, label='query')
    a.set_title(title); a.set_aspect('equal'); a.invert_yaxis()
    a.set_xticks([]); a.set_yticks([])
ax[0].legend(handles=[Line2D([], [], marker='o', ls='', ms=5, color=c, label=l)
                     for c, l in (('tab:blue', 'reference'), ('tab:orange', 'query'))],
             loc='lower left', fontsize=8)
centroid offset 4 -> 0
distance to the nearest reference cell: median 0 -> 0, 90th percentile 2 -> 1
<matplotlib.legend.Legend at 0x7f1ebb1b9be0>
../../_images/aa69d2c6746255920631f0d7736ecb23d52308bcb97887888970cb39c863fbf1.png

Convergence#

energies = np.asarray(fit.energies)[: fit.n_iter]
plt.figure(figsize=(5, 3))
plt.plot(energies, lw=0.8)
plt.xlabel('iteration'); plt.ylabel('objective'); plt.grid(alpha=0.3)
../../_images/01db274a6ae0f5aa72a1a4f12aa9fe3893faa6e5a0a13644f8673ac6ca6d968d.png