Merfish merfish initial affine

Merfish merfish initial affine#

The same pair again, initialised by an explicit rotation and translation rather than by landmarks. Upstream calls its version using-L-T after the two arguments it passes: L is the 2x2 linear part of the starting affine and T the translation vector. squidpy has no such pair – it takes one homogeneous initial_affine, or derives the start from landmarks – so here the rotation is applied to the coordinates instead and the fit starts from the identity, which keeps the initialisation visible rather than folded into a matrix convention.

Upstream’s equivalent is merfish-merfish-alignment-using-L-T. 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: merfish-merfish-alignment-using-L-T.

Inputs#

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

def read_xy(path, x, y, *, skip_first=False):
    df = pd.read_csv(path)
    xy = np.c_[np.asarray(df[x])[1:] if skip_first else df[x],
               np.asarray(df[y])[1:] if skip_first else df[y]].astype(float)
    return ad.AnnData(X=np.zeros((len(xy), 1)), obsm={'spatial': xy})

# Upstream's starting guess, applied to the coordinates rather than passed as `initial_affine`:
# the fit then starts from the identity, and the initialisation stays visible here instead of
# folded into a matrix convention.
def rotated_onto(query, ref, degrees):
    theta = np.deg2rad(-degrees)
    rotation = np.array([[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]])
    centred = query.obsm['spatial'] - query.obsm['spatial'].mean(0)
    out = query.copy()
    out.obsm['spatial'] = centred @ rotation.T + ref.obsm['spatial'].mean(0)
    return out

ref = read_xy('merfish_data/datasets_mouse_brain_map_BrainReceptorShowcase_Slice2_Replicate2_cell_metadata_S2R2.csv.gz', 'center_x', 'center_y')
query = read_xy('merfish_data/datasets_mouse_brain_map_BrainReceptorShowcase_Slice2_Replicate3_cell_metadata_S2R3.csv.gz', 'center_x', 'center_y')
print(f'{ref.n_obs} reference cells, {query.n_obs} query cells')

# Upstream starts this pair 45 degrees apart.
query = rotated_onto(query, ref, 45)
84172 reference cells, 85958 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=15.0, blur=1.5, niter=10000, epV=50,
)
print(f'{fit.n_iter} iterations, objective '
      f'{float(fit.energies[0]):.0f} -> {float(fit.energies[-1]):.0f}')
10000 iterations, objective 1674 -> 1577

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 0 -> 101
distance to the nearest reference cell: median 11 -> 11, 90th percentile 24 -> 22
<matplotlib.legend.Legend at 0x7fb7ef9f1be0>
../../_images/eb2a05ffb8313c0df134c96a3b7c9c596e16ed88c59aeafc511474ef5e9f707f.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/0e15369e974b891857740910d2eaa0e0fc67c081ec5926a1bd0b7b9893ce19ef.png