This vignette aligns two real
single-cell spatial datasets: coronal sections of the adult mouse brain
from matched positions, measured by MERFISH. It follows the STalign
tutorial “Aligning two coronal sections of adult mouse brain from
MERFISH”, with rasterize() and lddmm() in
place of the Python calls. The recipe is the usual one for point data:
rotate the source by hand into roughly the same pose, turn both sets of
cells into density images, and let lddmm() find the
remaining affine part and the nonlinear deformation.
The alignment engine is the one of STalign (Clifton et
al., 2023, Nature Communications, doi:10.1038/s41467-023-43915-7), which RSTalign makes
available from R. If you use it, please cite that paper
(citation("RSTalign")).
The two tables are in the package’s inst/extdata folder.
Each has one row per cell, with its position (center_x,
center_y) and a few other columns that alignment does not
use. We take the positions only. They are in micrometers.
library(RSTalign)
read_cells <- function(file) {
d <- read.csv(system.file("extdata", file, package = "RSTalign"))
data.frame(x = d$center_x, y = d$center_y)
}
source_cells <- read_cells("datasets_mouse_brain_map_BrainReceptorShowcase_Slice2_Replicate3_cell_metadata_S2R3.csv.gz")
target_cells <- read_cells("datasets_mouse_brain_map_BrainReceptorShowcase_Slice2_Replicate2_cell_metadata_S2R2.csv.gz")
# replicate 3 is the source, replicate 2 the target
c(source = nrow(source_cells), target = nrow(target_cells))
#> source target
#> 85958 84172
rbind(source = colMeans(source_cells), target = colMeans(target_cells))
#> x y
#> source 5144.960 3901.513
#> target 4991.189 5282.806red <- rgb(0.85, 0.10, 0.45, 0.30)
green <- rgb(0.10, 0.65, 0.25, 0.30)
# the two clouds on one set of axes (y up, as in the data)
overlay_points <- function(a, b, main, xlim = range(a$x, b$x), ylim = range(a$y, b$y)) {
plot(NA, xlim = xlim, ylim = ylim, asp = 1, xlab = "x (µm)", ylab = "y (µm)", main = main)
points(a$x, a$y, pch = ".", col = red)
points(b$x, b$y, pch = ".", col = green)
}
both_x <- range(source_cells$x, target_cells$x)
both_y <- range(source_cells$y, target_cells$y)
par(mfrow = c(1, 3), mar = c(4, 4, 2, 1))
overlay_points(source_cells, source_cells[0, ], "Source (replicate 3)", both_x, both_y)
overlay_points(target_cells[0, ], target_cells, "Target (replicate 2)", both_x, both_y)
overlay_points(source_cells, target_cells, "Both, as measured", both_x, both_y)The two sections show the same structures (the outline of the cortex,
and the paired structure near the middle), but the target is rotated and
bent: no rigid motion will align them, which is why the nonlinear part
of lddmm() is needed.
lddmm() refines an alignment by gradient descent, so it
needs to start from roughly the right pose. RSTalign has no automatic
pre-fit, so we do this step by hand, as the STalign tutorial does:
rotate the source clockwise about its center, then move its center onto
the center of the target.
A rotation plus a shift is an affine map, and the natural way to
write one down is a 2 x 3 matrix M = [L | t],
which takes a position (x, y) to
L %*% c(x, y) + t. That is what apply_affine()
takes, and what affine_from_landmarks() and the app
described below return. Here L is the clockwise rotation,
and t is chosen so that the centroid of the source lands on
the centroid of the target:
# the 2 x 3 matrix that rotates clockwise by `degrees` about the centroid of `from` and moves that
# centroid onto the centroid of `to`: L = rotation, t = centroid(to) - L %*% centroid(from)
rotation_affine <- function(degrees, from, to) {
th <- -degrees * pi / 180
L <- matrix(c(cos(th), sin(th), -sin(th), cos(th)), 2)
unname(cbind(L, colMeans(to) - as.vector(L %*% colMeans(from))))
}
M0 <- rotation_affine(45, source_cells, target_cells)
round(M0, 3)
#> [,1] [,2] [,3]
#> [1,] 0.707 0.707 -1405.633
#> [2,] -0.707 0.707 6162.055The first two columns are the rotation (cosine 0.707 on the
diagonal), the last is the shift in micrometers. The matrix is applied
to the cells with apply_affine(), which keeps any other
columns of a data frame and returns the moved x and
y:
source_start <- apply_affine(source_cells, M0)
rbind(source = colMeans(source_start), target = colMeans(target_cells)) # same centroid now
#> x y
#> source 4991.189 5282.806
#> target 4991.189 5282.806The angle is found by eye. Three candidates are shown below, and 45 degrees, the tutorial’s choice, looks best of the three: it leaves the least tissue of the source sticking out.
par(mfrow = c(1, 3), mar = c(4, 4, 2, 1))
for (degrees in c(35, 45, 55)) {
overlay_points(apply_affine(source_cells, rotation_affine(degrees, source_cells, target_cells)),
target_cells, paste("Rotated by", degrees, "degrees"))
}This M0 is not the matrix
res$A that lddmm() returns later.
M0 is 2 x 3, acts on cells in
(x, y) order and is applied before the images are made.
res$A is 3 x 3, acts on the image coordinates
in (row, column) = (y, x) order and is what remains to be
found after M0.
Trying angles by eye, as above, only gets you so far. It is often
easier to point at a few structures that are in both sections.
landmark_affine() opens a small Shiny app for that (it
needs the shiny package, which is only suggested). It
rasterizes the two sets of cells with rasterize() (at a
coarser default pixel size than below, which dx changes)
and shows the two images side by side. You click a structure on the
source, then the same structure on the target, and repeat. From the
third pair on, the app fits the affine map through the pairs by least
squares and shows the moved source over the target in a third panel
(white where they agree), together with the matrix and the error left at
each landmark. When the overlay looks right, press
Done.
# opens the app in your browser; returns the 2 x 3 matrix when you press Done
M0 <- landmark_affine(source_cells, target_cells)
# used exactly like the hand-made matrix above
source_start <- apply_affine(source_cells, M0)The matrix is also printed to the console as code that you can paste
into a script, so the alignment can be repeated without opening the app.
Use at least 3 pairs that do not lie on a line; more pairs average out
the error of each click, which is about one screen pixel (a few tens of
micrometers at the default pixel size).
affine_from_landmarks() does the same fit from landmark
coordinates that you already have, for example from another tool:
rasterize() turns each cloud into a density image, with
30 µm pixels and a Gaussian kernel of blur = 1.5 pixels (so
a standard deviation of 3 pixels, 90 µm), the values of the STalign
tutorial. Each cloud gets its own grid, and the result is a list with
the pixel coordinates x (columns) and y (rows)
and the image M, channels first, whose first image axis is
the row axis (y). That is the layout lddmm()
takes.
src <- rasterize(source_start$x, source_start$y, dx = 30, blur = 1.5)
tgt <- rasterize(target_cells$x, target_cells$y, dx = 30, blur = 1.5)
rbind(source = dim(src$M)[2:3], target = dim(tgt$M)[2:3]) # rows (y) and columns (x) of each image
#> [,1] [,2]
#> source 323 345
#> target 342 326
range(src$M)
#> [1] 0.000000 4.004951We do not rescale the images. Each cell adds a total of 1, so the
values are cells per pixel (at most about 4 here), which is a scale the
default step sizes of lddmm() cope with.
pal <- colorRampPalette(c("white", "navy"))(64)
xlim <- range(src$x, tgt$x); ylim <- range(src$y, tgt$y)
show_image <- function(r, main) {
image(r$x, r$y, t(r$M[1, , ]), col = pal, asp = 1, xlim = xlim, ylim = ylim,
xlab = "x (µm)", ylab = "y (µm)", main = main)
}
par(mfrow = c(1, 2), mar = c(4, 4, 2, 1))
show_image(src, "Source image (rotated)")
show_image(tgt, "Target image")We only set the number of iterations. Every other argument keeps its
default, so this also shows that the defaults work on data at this scale
(micrometers, cells per pixel). The STalign tutorial runs 10000
iterations with a smaller velocity step (epV = 50); with
the larger default step the fit settles in about 3000 (the energy plot
at the end shows it).
res <- lddmm(
xI = list(src$y, src$x), I = src$M, # source: rows = y, columns = x
xJ = list(tgt$y, tgt$x), J = tgt$M, # target, on its own grid
niter = 3000,
num_threads = 2
)
names(res)
#> [1] "A" "v" "xv" "WM" "WB" "WA" "AI" "fAI" "Esave"res$AI is the deformed source on the target’s grid,
channels first.
The top row overlays the images: the source in magenta, the target in
green, white where they agree. The bottom row shows the target’s cells
(green dots) over the source image, before and after. “Before” is the
source after the rotation above and before lddmm(). It
needs a lookup onto the target’s grid for the picture (the “after” image
is already on it).
# the image `img` (on the grid `from`, a list with x and y) looked up at the pixels of `to`
on_grid <- function(img, from, to) {
i <- round((to$y - from$y[1]) / (from$y[2] - from$y[1])) + 1
j <- round((to$x - from$x[1]) / (from$x[2] - from$x[1])) + 1
out <- matrix(0, length(to$y), length(to$x))
ok_i <- i >= 1 & i <= length(from$y); ok_j <- j >= 1 & j <= length(from$x)
out[ok_i, ok_j] <- img[i[ok_i], j[ok_j]]
out
}
I0 <- on_grid(src$M[1, , ], src, tgt) # source on the target grid, before lddmm()
AI <- res$AI[1, , ] # deformed source, after
J <- tgt$M[1, , ] # target
scale01 <- function(M) pmin(M / quantile(M, 0.995), 1)
# source image in magenta (and target in green) on black, drawn on the grid `g`; optionally the
# target cells on top
plot_overlay <- function(s, t = NULL, g, main, cells = NULL) {
dx <- g$x[2] - g$x[1]; dy <- g$y[2] - g$y[1]
plot(NA, xlim = range(g$x), ylim = range(g$y), asp = 1, xlab = "x (µm)", ylab = "y (µm)",
main = main)
s <- scale01(s)
t <- if (is.null(t)) 0 * s else scale01(t)
cols <- matrix(rgb(s, t, s), nrow(s))
# rasterImage draws row 1 at the top, our row 1 is the smallest y: flip
rasterImage(as.raster(cols[nrow(cols):1, ]), min(g$x) - dx / 2, min(g$y) - dy / 2,
max(g$x) + dx / 2, max(g$y) + dy / 2, interpolate = FALSE)
if (!is.null(cells)) points(cells$x, cells$y, pch = ".", col = rgb(0.2, 1, 0.4, 0.15))
}
par(mfrow = c(2, 2), mar = c(4, 4, 2, 1))
plot_overlay(I0, J, tgt, "Before: source (magenta) + target (green)")
plot_overlay(AI, J, tgt, "After: deformed source + target")
plot_overlay(I0, NULL, tgt, "Before: target cells on the source", cells = target_cells)
plot_overlay(AI, NULL, tgt, "After: target cells on the deformed source", cells = target_cells)The outline of the section now follows the target’s, including the upper right edge where the source stuck out, and the structure in the middle lines up. Some mismatch is left, mostly where one section contains tissue or cells that the other lacks. These are two separate tissue sections, not one section measured twice, so a perfect match is not possible.
In numbers, over the pixels of the target image:
res$A maps source coordinates to target coordinates in
(row, column) = (y, x) order, and applies to the
rotated source. Because we rotated by hand first, it is nearly
the identity: a shift of a few micrometers and a change of under 1% in
the linear part. The deformation that bends one section onto the other
is in the velocity field v.
round(res$A, 3)
#> [,1] [,2] [,3]
#> [1,] 1.001 -0.005 -6.290
#> [2,] 0.002 1.002 4.215
#> [3,] 0.000 0.000 1.000
dim(res$v) # time steps, rows, columns of the velocity grid, (y, x)
#> [1] 3 78 83 2
round(max(sqrt(res$v[, , , 1]^2 + res$v[, , , 2]^2))) # largest velocity (µm per unit time)
#> [1] 842Esave holds the energy of every iteration: the total
E, the matching term EM and the regularization
term ER. The fit has settled when the curve is flat; if it
is still falling, raise niter.
energy <- res$Esave[, c("E", "EM", "ER")]
energy[energy <= 0] <- NA # ER is exactly 0 at the first iteration, where v is still 0
par(mar = c(4, 4, 1, 1))
matplot(energy, type = "l", lty = 1, lwd = 2, log = "y",
col = c("black", "firebrick", "steelblue"), xlab = "iteration", ylab = "energy")
legend("right", c("E", "EM", "ER"), col = c("black", "firebrick", "steelblue"), lwd = 2, bty = "n")The Python tutorial finishes by moving the individual cells to their
aligned positions (transform_points_source_to_target).
RSTalign has no such function: pointsIt only carries the
landmarks passed as pointsI / pointsJ, and
those also enter the energy. The figures above therefore move the source
image onto the target, not the cells. There is also no ground
truth for these data, so the quality is judged from the overlays and the
image difference above.