Package 'RSTalign'

Title: Minimal R Interface to the STalign C++ LDDMM Engine
Description: Runs the CPU C++ engine of the 'STalign' Python package (LDDMM for 2D images, and a 3D volume to 2D slice) from R through 'Rcpp'. Only the engine, the little set-up it needs (velocity grid and smoothing kernel) and the rasterization of a point cloud into an image are included. A Shiny app allows selecting landmark points for the priori affine transformation before the LDDMM run.
Authors: Artür Manukyan [aut, cre] (ORCID: <https://orcid.org/0000-0002-0441-9517>), JEFworks Lab [cph] (STalign and its C++ LDDMM engine, as stated in the copyright line of the STalign repository; see inst/COPYRIGHTS)
Maintainer: Artür Manukyan <[email protected]>
License: GPL-3
Version: 0.1.0
Built: 2026-12-06 10:04:06 UTC
Source: https://github.com/BIMSBbioinfo/RSTalign

Help Index


Affine map from landmark pairs

Description

Least-squares affine map taking landmarks of a source to the matching landmarks of a target. This is what landmark_affine() computes from the points you click.

Usage

affine_from_landmarks(from, to)

Arguments

from, to

Matrices (or data frames) with two columns, x and y, and one row per landmark: the landmarks in the source and the matching ones in the target, in the same order. Three or more are needed, and not all on one line. With exactly three the map is exact, with more it is the least-squares fit.

Details

The result is a ⁠2 x 3⁠ matrix ⁠M = [L | T]⁠ that acts on positions ⁠(x, y)⁠ (x first): ⁠(x', y') = L (x, y) + T⁠, with L = M[, 1:2] and T = M[, 3]. Apply it with apply_affine().

This is not the matrix A of lddmm(). A is ⁠3 x 3⁠ and works on ⁠(row, column) = (y, x)⁠ coordinates of the rasterized images. The usual route is to move the source cells with apply_affine() before rasterizing, as in vignette("lddmm-merfish").

Value

A ⁠2 x 3⁠ matrix.

See Also

apply_affine(), landmark_affine()

Examples

from <- cbind(x = c(0, 10, 0, 10), y = c(0, 0, 10, 10))
to <- cbind(x = c(5, 5, -5, -5), y = c(0, 10, 0, 10))  # a counter-clockwise quarter turn, then +5 in x
M <- affine_from_landmarks(from, to)
round(M, 6)
apply_affine(from, M)

Apply a 2 x 3 affine matrix to positions

Description

Moves positions ⁠(x, y)⁠ by an affine map ⁠(x', y') = L (x, y) + T⁠, given as the ⁠2 x 3⁠ matrix ⁠[L | T]⁠ (see affine_from_landmarks()).

Usage

apply_affine(points, M)

Arguments

points

A data frame with columns x and y (other columns are kept), or a matrix with two columns (x, y).

M

A ⁠2 x 3⁠ numeric matrix.

Value

points with the moved positions, in the same form (data frame or matrix).

See Also

affine_from_landmarks(), landmark_affine()

Examples

cells <- data.frame(x = c(0, 10), y = c(0, 0))
R <- rbind(c(0, -1, 5), c(1, 0, 0))  # turn by 90 degrees about the origin, then shift x by 5
apply_affine(cells, R)

Pick landmarks in a Shiny app to get an initial affine alignment

Description

Opens a small Shiny app with the source and the target cells rasterized side by side. Click a recognizable point on the source, then the same point on the target, and repeat. From three pairs on, the app fits the affine map from the source to the target (least squares, see affine_from_landmarks()) and shows the source moved by it over the target, so you can see whether it is good enough as a starting point for lddmm(), which has no affine pre-fit of its own. Add pairs where the overlay is still off. "Done" closes the app and returns the matrix.

Usage

landmark_affine(source, target, dx = NULL, blur = 1.5, ...)

Arguments

source, target

The cells of the source and of the target: data frames with columns x and y (or matrices with two columns), in the same units.

dx

Pixel size of the displayed images, in the units of the coordinates. The default makes the largest extent about 250 pixels.

blur

Width of the Gaussian kernel of the images, in pixels (see rasterize()).

...

Passed to shiny::runApp(), for example launch.browser = FALSE or port = 4321.

Details

The images are made with rasterize() from the cells you give, with the pixel size and blur set in the app, only for display: the landmarks are in the coordinates of the cells.

The app is interactive and needs the 'shiny' package. Close the browser tab, or press "Cancel", to leave without a result (NULL is returned).

Value

A ⁠2 x 3⁠ affine matrix ⁠[L | T]⁠ taking the ⁠(x, y)⁠ positions of the source to the target, NULL if you leave without one. Use it with apply_affine(). The matrix is also printed as R code, so that you can paste it into your script and not repeat the clicking.

See Also

affine_from_landmarks(), apply_affine(), rasterize(), lddmm()

Examples

if (interactive()) {
  dir <- system.file("extdata", package = "RSTalign", mustWork = TRUE)
  read_cells <- function(pattern) {
    d <- read.csv(list.files(dir, pattern = pattern, full.names = TRUE))
    data.frame(x = d$center_x, y = d$center_y)
  }
  source_cells <- read_cells("S2R3[.]csv[.]gz$")
  target_cells <- read_cells("S2R2[.]csv[.]gz$")
  M0 <- landmark_affine(source_cells, target_cells)
  source_start <- apply_affine(source_cells, M0)
}

LDDMM with the STalign C++ engine

Description

Jointly estimates an affine map A and a diffeomorphism (a velocity field v) between a source image I and a target image J, running the C++ engine of the Python package STalign (CPU, float64). Two problems are supported, chosen by the number of axes of the source: 2D to 2D (LDDMM) and a 3D volume to a 2D slice (LDDMM_3D_to_slice).

Usage

lddmm(
  xI,
  I,
  xJ,
  J,
  pointsI = NULL,
  pointsJ = NULL,
  A = NULL,
  a = 500,
  p = 2,
  expand = NULL,
  nt = 3L,
  niter = 5000L,
  diffeo_start = 0L,
  epL = NULL,
  epT = NULL,
  epV = NULL,
  sigmaM = 1,
  sigmaB = 2,
  sigmaA = 5,
  sigmaR = NULL,
  sigmaP = 20,
  muA = NULL,
  muB = NULL,
  affine_step_control = NULL,
  landmark_exact = TRUE,
  num_threads = 1L
)

Arguments

xI

List of coordinate vectors of the source pixels, one per axis (2 or 3).

I

Source image, array with channels first (a matrix or 3D array is one channel).

xJ

List of coordinate vectors of the target pixels (in 3D, 2 vectors place the slice at z = 0).

J

Target image, array with channels first (a matrix is one channel).

pointsI, pointsJ

Optional ⁠N x 2⁠ matrices of corresponding landmarks in the source and target (2D only).

A

Initial affine, a ⁠(d+1) x (d+1)⁠ matrix (default: identity). It maps source coordinates to target coordinates.

a

Smoothness scale of the velocity field.

p

Power of the Laplacian in the regularizer.

expand

Factor by which the velocity grid extends beyond the source grid (default 2 in 2D, 1.25 in 3D).

nt

Number of time steps of the velocity field.

niter

Number of iterations (at least 1).

diffeo_start

Number of initial iterations that fit the affine only.

epL, epT, epV

Gradient step sizes of the linear part, the translation and the velocity field (defaults 2e-8, 0.2, 2e3 in 2D; 1e-6, 10, 1e3 in 3D).

sigmaM, sigmaB, sigmaA

Standard deviations of the matching, background and artifact classes.

sigmaR

Regularization; smaller is smoother (default 5e5 in 2D, 2e6 in 3D).

sigmaP

Standard deviation of the landmark term.

muA, muB

Fixed means of the artifact and background classes (one value or one per target channel). NULL estimates them.

affine_step_control

Scale the step of every affine parameter by a multiplier that shrinks when its gradient changes sign (default FALSE in 2D and TRUE in 3D, as in STalign).

landmark_exact

Map the landmarks with the exact inverse of the fitted map (TRUE) or with forward Euler steps.

num_threads

Number of threads. The result does not depend on it.

Details

This is only the engine: there is no affine pre-fit and no data-driven choice of sigmaR, epL, epT, epV (the Python front-end's default). The defaults here are the fixed defaults of STalign 1.0 (Python's legacy_defaults = TRUE) and depend on the units and intensity scale of the data, so set them for your data. Coordinates are assumed to be in micrometers.

Arrays follow the Python package: channels first, I has dimensions c(C, n1, n2) (2D) or c(C, n1, n2, n3) (3D), the target J has c(C, m1, m2) (a matrix is one channel; in 3D the target is a slice, with c(C, 1, m1, m2) also accepted), and the first axis is the "row" axis. xI and xJ are lists with the pixel coordinates along each axis, and landmarks are (row, column) coordinates.

Value

A list with the affine A, the velocity field v (nt x grid x d) and its grid xv, the weights WM, WB, WA (matching, background, artifact) on the target pixels, the deformed source AI and its contrast-fitted version fAI (channels first, target pixels), the energies of every iteration Esave (columns E, EM, ER and, with landmarks, EP), and, when they exist, Xs (3D: the source location sampled for each target pixel) and pointsIt (the landmarks of pointsI mapped to the target). As in Python, A and v are those of the last iteration's forward pass.


Rasterize a point cloud into a density image

Description

Turns the positions of cells (or spots, or transcripts) into the image that lddmm() needs. This is STalign.rasterize of the Python package, without the figure it draws: the pixel grid, the kernel and the weights follow it step by step, so the images are the same up to floating point rounding.

Usage

rasterize(
  x,
  y,
  g = 1,
  dx = 30,
  blur = NULL,
  expand = 1.1,
  wavelet_magnitude = FALSE,
  use_windowing = TRUE,
  blur_um = NULL
)

Arguments

x, y

Numeric vectors with the horizontal and the vertical position of each cell. Cells with a missing coordinate are ignored, with a warning.

g

Weight of each cell (recycled to the number of cells), for example its RNA count. The default 1 gives a density image. Unless all weights are 1 they are min-max normalized to ⁠[0, 1]⁠, so the cells with the smallest weight add nothing, and equal weights give an image of zeros.

dx

Pixel size, in the units of x and y.

blur

Width of the Gaussian kernel in pixels (its standard deviation is 2 * blur pixels). A vector makes a multi-scale image with one channel per entry. The default is 1, unless blur_um is given.

expand

Factor by which the grid extends beyond the bounding box of the cells.

wavelet_magnitude

If TRUE, channel i holds the absolute value of the difference between the kernels i and i - 1 (a difference between scales). blur must then be sorted from greatest to least.

use_windowing

If TRUE, evaluate each kernel on a window of pixels (see above) and not on the whole image.

blur_um

The standard deviation of the kernel in the units of x and y (for example micrometers), instead of blur: blur = blur_um / (2 * dx). The kernel then keeps its physical width at any pixel size. Give blur or blur_um, not both.

Details

The grid covers the bounding box of the points, enlarged by expand about its center, with pixels dx apart, so every cloud gets its own grid (the two images given to lddmm() do not need to share one). Each cell then adds a Gaussian kernel centered on its exact position, with standard deviation 2 * blur pixels (2 * blur * dx in the units of x and y). The kernel is evaluated on a square window of pixels around the cell's nearest pixel, extending ceiling(4 * max(blur)) pixels to each side, clipped at the border of the image, and divided by its sum over that window. A cell therefore adds a total of its weight (1 for a density image), and the window holds about 95% of the Gaussian, so the kernel acts like one about 4% narrower. With use_windowing = FALSE the whole image is used instead, which is much slower.

The image is not rescaled. Its values are on the scale of cells per pixel, so for lddmm() you will want to divide it by its maximum (or similar), because the step sizes epL, epT and epV depend on the intensity scale.

Value

A list with

  • x: the coordinates of the pixel columns,

  • y: the coordinates of the pixel rows,

  • M: the image, an array of dimensions c(length(blur), length(y), length(x)), channels first, the first image axis being the rows (y) as in lddmm().

So lddmm(xI = list(src$y, src$x), I = src$M, ...) aligns an image made here.

See Also

lddmm(); vignette("lddmm-merfish") for an alignment of two sets of cells.

Examples

# cell positions (micrometers) of a MERFISH mouse-brain section shipped with the package
file <- system.file("extdata", package = "RSTalign", mustWork = TRUE)
cells <- read.csv(list.files(file, pattern = "S2R3[.]csv[.]gz$", full.names = TRUE))
img <- rasterize(cells$center_x, cells$center_y, dx = 30, blur = 1.5)
dim(img$M)                 # channels, rows (y), columns (x)
image(img$x, img$y, t(img$M[1, , ]), asp = 1)