When to use this
Reach for somalign_fit_two_pass() when the batch effect
has a large global component: reagent lot changes, instrument
calibration drift, or environmental factors that shift every population
in roughly the same direction, layered on top of smaller
population-specific displacements. A single OT pass struggles with this
shape. At a small epsilon it captures fine structure but destabilises
when the global offset dwarfs the typical inter-node distance; at a
large epsilon it smooths away that instability but loses
population-level resolution.
somalign_fit_two_pass() splits the problem in two. A
first pass at a larger epsilon_global estimates the
mass-weighted mean node displacement, the global shift, and
subtracts it from the query codebook. A second pass at a finer
epsilon_local then captures the residual
population-specific offsets. The final per-node correction is the sum of
both passes, so the total displacement per sample matches a direct
single-pass alignment at epsilon_local. Subtracting the
global component first is what makes that second-pass problem better
conditioned.
The two-pass procedure refines the correction (the per-node
shift field), which somalign treats as a diagnostic rather
than a product. The corrected coordinates can over-merge distinct
populations (see somalign_topology_audit()) and are not a
batch-corrected expression matrix. The primary deliverable remains label
transfer.
Setup
library(kohonen)
library(somalign)
set.seed(42)
p <- 4L
old_data <- rbind(
matrix(rnorm(60 * p, mean = -2, sd = 0.5), ncol = p),
matrix(rnorm(60 * p, mean = 2, sd = 0.5), ncol = p)
)
colnames(old_data) <- paste0("CD", seq_len(p))
old_labels <- rep(c("pop_A", "pop_B"), each = 60L)
reference <- somalign_train_reference(
old_data,
labels = old_labels,
grid = kohonen::somgrid(3, 3, "hexagonal"),
rlen = 30
)
reference
#> <somalign_reference>
#> features: 4
#> reference nodes: 9
#> labelled nodes: 7The new batch carries a dominant global offset shared by both populations, plus a smaller population-specific residual that only the second pass can capture. The two residuals are equal and opposite across the balanced populations, so their cell mean is zero. That keeps the residual from biasing the estimated global shift, which stays aligned with the shared offset even though it is a mass-weighted mean over SOM nodes rather than a plain cell average.
global_shift <- c(0.5, 0.4, 0.45, 0.35) # shared technical offset
pop_delta <- c(0.15, -0.12, 0.10, -0.08) # population-specific residual
pop_shift <- rbind(
matrix( pop_delta, 60L, p, byrow = TRUE), # pop_A: +delta
matrix(-pop_delta, 60L, p, byrow = TRUE) # pop_B: -delta
)
set.seed(43)
local_noise <- matrix(rnorm(nrow(old_data) * p, 0, 0.08), ncol = p)
new_data <- old_data +
matrix(global_shift, nrow(old_data), p, byrow = TRUE) +
pop_shift + local_noise
query <- somalign_query(
new_data, reference,
grid = kohonen::somgrid(3, 3, "hexagonal"),
rlen = 30
)
query
#> <somalign_query>
#> samples: 120
#> features: 4
#> query nodes: 9Two-pass alignment
fit2 <- somalign_fit_two_pass(
query, reference,
epsilon_global = 0.3,
epsilon_local = 0.1
)
#> somalign_fit: 6 query node(s) have match_mass_ratio > 1 (max 1.61); this is expected in unbalanced OT. See diagnostics$ot$match_mass_ratio for details.
#> somalign_fit: 6 query node(s) have match_mass_ratio > 1 (max 1.16); this is expected in unbalanced OT. See diagnostics$ot$match_mass_ratio for details.
fit2
#> <somalign_fit>
#> label transfer: 100.0% of cells accepted across 2 class(es); median confidence 1.00, median margin 1.00
#> solver: internal | query nodes: 9 | reference nodes: 9 | transport mass: 1.114The $two_pass slot records the estimated global shift
and both epsilon values:
cat("Estimated global shift (correction direction, query -> reference):\n")
#> Estimated global shift (correction direction, query -> reference):
print(round(fit2$two_pass$global_shift, 3))
#> CD1 CD2 CD3 CD4
#> -0.238 -0.184 -0.198 -0.145
cat("\nTrue batch offset (positive = new batch above old):\n")
#>
#> True batch offset (positive = new batch above old):
print(round(global_shift, 3))
#> [1] 0.50 0.40 0.45 0.35
cat("\nGlobal shift magnitude:", round(fit2$two_pass$global_shift_norm, 3), "\n")
#>
#> Global shift magnitude: 0.388global_shift points in the correction
direction, from the query codebook toward the reference, so its sign is
opposite to the true batch offset. The node shifts are the mass-weighted
mean of first-pass OT transport vectors, so the magnitude is in
reference-scaled units, not raw units, and does not equal the raw
feature offset directly. What matters in practice is the direction: each
feature’s sign should oppose the known batch offset, and features with
larger displacements should show larger absolute values. The norm
global_shift_norm gives one scalar measure of the global
displacement, comparable across batches or experiments.
Batch subspace diagnostic
The $two_pass$batch_subspace element summarises the
principal directions of the first-pass correction field:
bs <- fit2$two_pass$batch_subspace
cat("Batch subspace rank (pass 1): ", bs$rank, "\n")
#> Batch subspace rank (pass 1): 3
cat("Variance explained by leading directions:", round(bs$variance_explained, 3), "\n")
#> Variance explained by leading directions: 0.957This is a read-only diagnostic. Rank 1 means the pass-1 node shifts are nearly collinear, expected when a single global offset dominates. Higher rank means the first-pass correction has more heterogeneous directions across the codebook, which points toward a spatially varied batch effect like the per-population residual here.
The subspace is not used for correction: the total
shift is the residual pass-2 shift plus the global shift g.
Because the first-pass OT sees the original unmodified codebook rather
than controlled anchors, the diagnostic can conflate batch effects with
biology. Read it descriptively, not as a geometric estimate of the true
batch direction. For an anchor-based analogue that does serve as a
geometric estimate, see
vignette("anchor-samples", package = "somalign").
The variance_threshold argument controls rank selection
for this diagnostic only:
fit2b <- somalign_fit_two_pass(query, reference, variance_threshold = 1.0)
#> somalign_fit: 6 query node(s) have match_mass_ratio > 1 (max 1.61); this is expected in unbalanced OT. See diagnostics$ot$match_mass_ratio for details.
#> somalign_fit: 6 query node(s) have match_mass_ratio > 1 (max 1.16); this is expected in unbalanced OT. See diagnostics$ot$match_mass_ratio for details.
cat("Rank at variance_threshold = 1.0:", fit2b$two_pass$batch_subspace$rank, "\n")
#> Rank at variance_threshold = 1.0: 4
# Correction is unchanged regardless of variance_threshold
cat("Node shifts identical:", isTRUE(all.equal(fit2$node_shifts, fit2b$node_shifts)), "\n")
#> Node shifts identical: TRUEComparison with single-pass
For reference, a plain somalign_fit() at
epsilon_local sees the full uncorrected offset in one
pass:
fit1 <- somalign_fit(query, reference, epsilon = 0.1)
#> somalign_fit: 6 query node(s) have match_mass_ratio > 1 (max 1.18); this is expected in unbalanced OT. See diagnostics$ot$match_mass_ratio for details.
cat("Mean node shift two-pass: ",
round(mean(sqrt(rowSums(fit2$node_shifts^2))), 4), "\n")
#> Mean node shift two-pass: 0.3087
cat("Mean node shift one-pass: ",
round(mean(sqrt(rowSums(fit1$node_shifts^2))), 4), "\n")
#> Mean node shift one-pass: 0.3111Both return somalign_fit objects with an identical
downstream interface:
res2 <- somalign_results(fit2)
res1 <- somalign_results(fit1)
cat("Column names match:", identical(names(res2), names(res1)), "\n")
#> Column names match: TRUE
cat("Rows:", nrow(res2), "\n")
#> Rows: 120
diag2 <- somalign_diagnostics(fit2)
cat("Solver converged:", diag2$solver$converged, "\n")
#> Solver converged: TRUE
cat("Transport mass: ", round(diag2$ot$transport_mass, 4), "\n")
#> Transport mass: 1.1138Label-guided alignment
Both somalign_fit() and
somalign_fit_two_pass() accept
label_guided = TRUE, which applies a large cost penalty to
node pairs whose dominant labels disagree. When reference labels are
known and the batch does not scramble population boundaries, the penalty
concentrates transport onto same-label pairs and reduces spurious
cross-cluster mass.
label_guided = TRUE requires
query$label_prob to be non-NULL. The standard
somalign_query() workflow with kohonen::som()
leaves that field NULL; it is populated only when a
kohonen::supersom() or kohonen::xyf() SOM with
a label code layer is passed as som_query. Build the query
SOM with a one-hot label layer, supply it via som_query,
then set label_guided = TRUE:
# One-hot label matrix for new_data (requires knowing new-batch labels)
Y <- model.matrix(~ old_labels - 1)
colnames(Y) <- levels(factor(old_labels))
# Train a supersom with the label layer
new_scaled <- scale(new_data, center = reference$center, scale = reference$scale)
query_ss <- kohonen::supersom(
list(new_scaled, Y),
grid = kohonen::somgrid(3, 3, "hexagonal"),
rlen = 30,
keep.data = TRUE
)
query_labeled <- somalign_query(
new_data, reference,
som_query = query_ss,
codebook_space = "reference_scaled"
)
fit_lg <- somalign_fit_two_pass(
query_labeled, reference,
label_guided = TRUE
)Label-guided alignment works the same way for
somalign_fit(). If labels are noisy, or the batch shifts
populations across label boundaries, the penalty can destabilise the OT
plan. Check somalign_diagnostics() and compare against
somalign_sensitivity_grid() before using label-transferred
assignments downstream.
Choosing between two-pass and the alternatives
Two-pass alignment helps most when the global batch offset is large
relative to epsilon_local: large enough that a single
low-epsilon pass struggles to route mass across the full displacement,
while a single high-epsilon pass loses population-level resolution. The
explicit global subtraction removes that tension. When the batch shift
is small or the OT problem is already well-conditioned at a single
epsilon, somalign_fit() is simpler and equally
effective.
If remeasured control samples are available,
somalign_fit_anchored() with
correction = "subspace" offers a geometrically grounded,
signal-preserving correction as an alternative to the two-pass
decomposition. See
vignette("anchor-samples", package = "somalign").
Session info
#> R version 4.6.1 (2026-06-24)
#> Platform: x86_64-pc-linux-gnu
#> Running under: Ubuntu 24.04.4 LTS
#>
#> Matrix products: default
#> BLAS: /usr/lib/x86_64-linux-gnu/openblas-pthread/libblas.so.3
#> LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.26.so; LAPACK version 3.12.0
#>
#> locale:
#> [1] LC_CTYPE=C.UTF-8 LC_NUMERIC=C LC_TIME=C.UTF-8
#> [4] LC_COLLATE=C.UTF-8 LC_MONETARY=C.UTF-8 LC_MESSAGES=C.UTF-8
#> [7] LC_PAPER=C.UTF-8 LC_NAME=C LC_ADDRESS=C
#> [10] LC_TELEPHONE=C LC_MEASUREMENT=C.UTF-8 LC_IDENTIFICATION=C
#>
#> time zone: UTC
#> tzcode source: system (glibc)
#>
#> attached base packages:
#> [1] stats graphics grDevices utils datasets methods base
#>
#> other attached packages:
#> [1] somalign_0.99.5 kohonen_3.0.13 BiocStyle_2.40.0
#>
#> loaded via a namespace (and not attached):
#> [1] digest_0.6.39 desc_1.4.3 R6_2.6.1
#> [4] bookdown_0.47 fastmap_1.2.0 xfun_0.60
#> [7] cachem_1.1.0 knitr_1.51 htmltools_0.5.9
#> [10] rmarkdown_2.31 lifecycle_1.0.5 cli_3.6.6
#> [13] sass_0.4.10 pkgdown_2.2.1 jquerylib_0.1.4
#> [16] compiler_4.6.1 tools_4.6.1 bslib_0.11.0
#> [19] evaluate_1.0.5 Rcpp_1.1.2 yaml_2.3.12
#> [22] BiocManager_1.30.27 otel_0.2.0 jsonlite_2.0.0
#> [25] rlang_1.3.0 fs_2.1.0 htmlwidgets_1.6.4