4  Modern Single-Cell Techniques

Under Construction

This chapter is still under construction. Expect revisions as we continue adjusting the narrative and figures.

4.1 Problem: Seeing Structure in 37 Million Measurements

In Chapters 1–3, our path was clear. We began with a mechanistic model (the Telegraph process, the toggle switch) that told us what structure to expect. Our task was to estimate a few, interpretable parameters from data. The approach was model-driven: we had a map and needed to find our location.

Here, we face the opposite problem. We have no map. We have only a vast matrix of measurements from single-cell RNA sequencing (scRNA-seq), and our task is to discover structure from scratch. We’ve shifted from fitting a model to finding one. The problem for this chapter is precise: how can we extract interpretable structure from a matrix with more entries than a novel has characters?

This is not a mere data-cleaning exercise. We need to turn Waddington’s metaphor into something we can measure. Recall Waddington’s epigenetic landscape from Chapter 1: a ball rolling down valleys, representing how genetically identical cells choose distinct fates. For Waddington, it was intuition. For us, the question is concrete: how do we actually construct this from data?

This chapter builds the map. We will define coordinates (principal components), reveal the topology (nonlinear embeddings), and identify the valleys (clusters). Later, we will add the flow and the regulatory forces that shape the landscape itself. By the end, Waddington’s metaphor will be quantitative.

To see the challenge, let’s inspect a canonical dataset. The PBMC3k dataset from 10x Genomics profiles peripheral blood mononuclear cells, which are the white blood cells circulating in your bloodstream right now. After standard quality control we retain 2,700 cells and 13,714 genes.

Code
import numpy as np
import scipy.sparse as sp
import scanpy as sc
import matplotlib.pyplot as plt
import warnings

# Silence library-level warnings so the narrative stays focused on interpretation.
warnings.filterwarnings("ignore")

# Load the canonical PBMC dataset
adata = sc.datasets.pbmc3k()

# Basic preprocessing: filter cells and genes
sc.pp.filter_cells(adata, min_genes=200)
sc.pp.filter_genes(adata, min_cells=3)

print(f"Data matrix shape: {adata.shape}")
print(f"Total measurements: {adata.n_obs * adata.n_vars:,}")
print(f"Matrix sparsity: {(adata.X == 0).sum() / (adata.n_obs * adata.n_vars):.1%} zeros")
Data matrix shape: (2700, 13714)
Total measurements: 37,027,800
Matrix sparsity: 93.8% zeros

Even this modest experiment contains 2,700 × 13,714 = 37,027,800 measurements. Contemporary atlases scale to millions of cells, so the dimensionality only grows. The question is not whether we can store this matrix; it is whether we can reason about it.

4.1.1 Inspecting the Snapshot

Code
# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

# Select a random subset for visualization
np.random.seed(42)
n_cells_viz = 100
n_genes_viz = 100

cell_idx = np.random.choice(adata.n_obs, n_cells_viz, replace=False)
gene_idx = np.random.choice(adata.n_vars, n_genes_viz, replace=False)

# Extract submatrix (convert to dense if sparse)
if sp.issparse(adata.X):
    submatrix = adata.X[cell_idx, :][:, gene_idx].toarray()
else:
    submatrix = adata.X[cell_idx, :][:, gene_idx]

# Create heatmap
fig, ax = plt.subplots()
im = ax.imshow(submatrix.T, aspect='auto', cmap='plasma', interpolation='nearest')
ax.set_xlabel('Cells')
ax.set_ylabel('Genes')
ax.set_title('Raw scRNA-seq Count Matrix (100 cells × 100 genes)')

# Add colorbar
cbar = plt.colorbar(im, ax=ax, label='UMI counts')
ax.grid(alpha=0.3)

plt.tight_layout()
plt.show()

print(f"Sparsity: {(submatrix == 0).sum() / submatrix.size:.1%} zeros")
Figure 4.1: The scRNA-seq data matrix is sparse and high-dimensional. Shown are expression counts for 100 randomly selected genes across 100 cells from the PBMC dataset. Black (zero) dominates—most gene-cell combinations show no detected transcripts, a phenomenon called ‘dropout’ that arises from limited sampling of mRNA molecules.
Sparsity: 93.2% zeros

Chapter 3 taught us to fit a Negative Binomial to a single gene across cells, recovering biologically meaningful parameters such as burst frequency and size. Scaling that exercise to our current matrix would still mean fitting 13,714 gene-specific models, for about 27,000 free parameters—already more knobs than we can interpret, yet nowhere near the 37 million measurements we began with. The obstacle is not computation; it is comprehension. We need structure, not an even larger catalogue of numbers.

The biological lifeline is that genes rarely behave independently. Cells activate modules, which are coherent sets of genes that rise and fall together in response to stimuli, developmental cues, or lineage commitments. If we can discover these shared programs, we can represent each cell with a handful of coordinates instead of 13,714 raw counts. The matrix is wide, but its intrinsic dimensionality is far smaller.

Code
# Demonstrate gene correlation structure
# Select a subset of highly variable genes for visualization
# Use a copy to avoid modifying the original dataset
adata_corr = adata.copy()
sc.pp.normalize_total(adata_corr, target_sum=1e4)
sc.pp.log1p(adata_corr)
sc.pp.highly_variable_genes(adata_corr, n_top_genes=100)
hvg_data = adata_corr[:, adata_corr.var.highly_variable].X.toarray() if sp.issparse(adata_corr.X) else adata_corr[:, adata_corr.var.highly_variable].X

# Compute gene-gene correlation matrix
gene_corr = np.corrcoef(hvg_data.T)
Code
from scipy.cluster.hierarchy import linkage, leaves_list, fcluster

# Use hierarchical clustering to reorder genes and reveal block structure
link = linkage(gene_corr, method='average', metric='correlation')
new_order = leaves_list(link)
gene_corr_clustered = gene_corr[new_order, :][:, new_order]

# Identify coarse modules directly from the dendrogram so we can bracket them in the plot
n_modules = 5
module_labels = fcluster(link, t=n_modules, criterion='maxclust')
module_ordered = module_labels[new_order]
module_edges = np.where(np.diff(module_ordered) != 0)[0] + 1
module_bounds = np.concatenate(([0], module_edges, [module_ordered.size]))
module_centers = (module_bounds[:-1] + module_bounds[1:] - 1) / 2
module_names = [f"Module {idx + 1}" for idx in range(len(module_centers))]

# Mask the diagonal to prevent self-correlation from dominating the colormap
gene_corr_viz = gene_corr_clustered.copy()
np.fill_diagonal(gene_corr_viz, 0)

# Calculate percentile-based color limits to enhance contrast
off_diagonal_mask = ~np.eye(gene_corr_viz.shape[0], dtype=bool)
off_diagonal_values = gene_corr_viz[off_diagonal_mask]
vmin_percentile = np.percentile(off_diagonal_values, 1)
vmax_percentile = np.percentile(off_diagonal_values, 99)

# Create heatmap with diverging colormap (coolwarm is better for correlation)
fig, ax = plt.subplots()
im = ax.imshow(gene_corr_viz, aspect='auto', cmap='coolwarm', vmin=vmin_percentile, vmax=vmax_percentile)

for boundary in module_edges - 0.5:
    ax.axhline(boundary, color='black', linewidth=0.8, alpha=0.8)
    ax.axvline(boundary, color='black', linewidth=0.8, alpha=0.8)

ax.set_xlabel('Gene modules (clustered order)')
ax.set_ylabel('Gene modules (clustered order)')
ax.set_xticks(module_centers)
ax.set_xticklabels(module_names, rotation=90)
ax.set_yticks(module_centers)
ax.set_yticklabels(module_names)
ax.set_title('Gene-Gene Correlation Matrix (100 HVGs, clustered)')

# Add colorbar
cbar = plt.colorbar(im, ax=ax, label='Pearson correlation')
ax.grid(False)

plt.tight_layout()
plt.show()
Figure 4.2: Genes organize into correlated modules. Hierarchical clustering reorders 100 highly variable genes, and the black guide lines bracket five correlation modules while the axis ticks name each program. The diagonal (self-correlation = 1) is masked, and the color scale uses the 1th to 99th percentiles of off-diagonal correlations to enhance contrast and reveal modular structure. These modules reflect biological programs: genes in the same pathway, responding to the same signals, or defining the same cell type tend to be expressed together. This redundancy means the effective dimensionality is far lower than 13,714.

Before searching for reduced coordinates, we must decide which version of the data matrix X \in \mathbb{R}^{n \times p} to analyze. Candidates include:

  1. Raw counts: direct UMI observations x_{ig} for gene g in cell i.

  2. Normalized counts: compensate for sequencing depth, the total number of UMIs captured per cell, \text{size}_i = \sum_g x_{ig}. This is a technical artifact: two identical cells can have different total counts simply because we sampled more mRNA from one. The standard normalization is counts-per-million (CPM): divide each gene’s count by the cell’s total, then scale by 10^6 to keep numbers interpretable.

  3. Log-transformed counts: \log(x+s) where s is a pseudocount (commonly s=1, the log1p transform). This compresses the dynamic range and avoids \log(0). The pseudocount regularizes variance for low-count genes without distorting structure at typical expression levels, where s \ll x.

  4. Variance-stabilized values: transformations that equalize variance across expression levels, accounting for the mean-variance relationship we derived in Chapter 3.

The most common choice is log-normalization: compute CPM, then apply \log(x+1). It’s simple and fast, which explains its popularity. But this convenience comes at an intellectual cost. It throws away everything we learned in Chapters 2 and 3: that transcription is a bursty stochastic process well-described by the Negative Binomial with a specific mean-variance relationship. The log transform imposes an arbitrary pseudocount and treats all genes as if they have the same noise characteristics.

We can do better by hybridizing our mechanistic understanding with explicit modeling of technical noise. The key insight: use the Negative Binomial distribution to model biological variability (as in Chapters 2-3) while simultaneously accounting for technical artifacts like sequencing depth.

4.2 Mathematical Idea: Variance Stabilization via the Negative Binomial GLM

The approach is to fit a Negative Binomial generalized linear model (NB-GLM) for each gene that separates biological signal from technical noise. This is a direct, large-scale application of our work in Chapters 2 and 3. There, we used the NB distribution to model single genes; here, we use it as a preprocessing tool for the entire transcriptome, explicitly modeling how sequencing depth inflates counts.

The SCTransform approach (Hafemeister and Satija 2019) implements this idea. For each gene g, we fit a Negative Binomial generalized linear model (NB-GLM) that explicitly models the influence of sequencing depth. The size factor—each cell’s total UMI count—is not a biological signal but a technical nuisance variable. Two biologically identical cells can have different total counts simply because we captured 10% of the mRNA from one and 20% from the other. The NB-GLM lets us “regress out” this technical effect.

For gene g in cell i, we model: \log(\mu_{ig}) = \alpha_g + \beta_g \log(\text{size}_i) where \text{size}_i=\sum_{g}x_{ig} is the total UMI count for cell i (a technical variable reflecting sequencing depth) , and the counts follow: x_{ig} \sim \text{NegBin}(\mu_{ig}, \theta_g)

Here’s what each parameter captures:

  • \alpha_g: The baseline expression level of gene g (biological)
  • \beta_g: How sensitive gene g is to sequencing depth (technical)
  • \theta_g: The overdispersion parameter for gene g (biological variability)

After fitting this model for each gene, we can compute Pearson residuals: r_{ig} = \frac{x_{ig} - \hat{\mu}_{ig}}{\sqrt{\hat{\mu}_{ig} + \hat{\mu}_{ig}^2/\hat{\theta}_g}}

A Note on Batch Effects

scRNA-seq data is often generated in multiple batches (different days, technicians, or reagent lots), introducing systematic technical variation unrelated to biology. If uncorrected, cells cluster by batch rather than by cell type.

The GLM framework naturally extends to handle this. We add a batch term: \log(\mu_{igb}) = \alpha_g + \beta_g \log(\text{size}_i) + \gamma_{gb} where \gamma_{gb} represents the batch-specific deviation for gene g in batch b. Fitting this extended model regresses out batch effects alongside sequencing depth.

For complex batch structures, specialized methods exist, but the key principle remains: model known technical factors before searching for biological structure.

These residuals have a crucial property: they’re approximately variance-stabilized. The denominator accounts for both the Poisson-like variance (first term) and the extra-Poisson overdispersion (second term). Genes with high or low mean expression are put on equal footing.

Why does this matter? When we perform PCA or other dimensionality reduction on these residuals, we’re no longer dominated by highly expressed genes. We’re working with features that have been corrected for technical effects and stabilized in variance, which provides a much cleaner input for discovering biological structure.

Let’s implement this from scratch to see how it works:

Code
from scipy.optimize import minimize
from scipy.stats import nbinom
from scipy.sparse import issparse

def fit_nb_glm_gene(counts, size_factors):
    """
    Fit Negative Binomial GLM for a single gene.

    Model: log(μ) = α + β*log(size_factor)
           x ~ NegBin(μ, θ)

    Returns: (alpha, beta, theta)
    """
    # Negative log-likelihood function
    def neg_log_lik(params):
        alpha, beta, log_theta = params
        theta = np.exp(log_theta)  # Ensure theta > 0
        mu = np.exp(alpha + beta * np.log(size_factors))

        # NB parameterization: n=theta, p=theta/(theta+mu)
        # This gives mean=mu, variance=mu+mu²/theta
        p = theta / (theta + mu)
        nll = -np.sum(nbinom.logpmf(counts, n=theta, p=p))
        return nll

    # Initial guess: alpha=log(mean), beta=1, theta=1
    x0 = [np.log(np.mean(counts) + 1), 1.0, 0.0]

    # Optimize
    result = minimize(neg_log_lik, x0, method='L-BFGS-B')
    alpha, beta, log_theta = result.x
    theta = np.exp(log_theta)

    return alpha, beta, theta

def compute_pearson_residuals(adata, n_top_genes=2000):
    """
    Compute Pearson residuals for variance stabilization.
    """
    # Get dense matrix for computation
    X = adata.X.toarray() if issparse(adata.X) else adata.X
    n_cells, n_genes = X.shape

    # Compute size factors (total UMI per cell)
    size_factors = np.sum(X, axis=1)

    # Fit NB-GLM for each gene and compute residuals
    residuals = np.zeros((n_cells, n_genes))
    gene_params = []

    print(f"Fitting NB-GLM to {n_genes} genes...")
    for g in range(n_genes):
        if g % 1000 == 0:
            print(f"  Gene {g}/{n_genes}")

        counts_g = X[:, g]
        alpha, beta, theta = fit_nb_glm_gene(counts_g, size_factors)
        gene_params.append((alpha, beta, theta))

        # Compute fitted values
        mu_hat = np.exp(alpha + beta * np.log(size_factors))

        # Pearson residuals: (observed - expected) / std_dev
        # For NB: variance = μ + μ²/θ
        std_dev = np.sqrt(mu_hat + mu_hat**2 / theta)
        residuals[:, g] = (counts_g - mu_hat) / std_dev

    return residuals, gene_params

# Note: This implementation is provided for pedagogical purposes to demonstrate
# the mathematical principles underlying variance stabilization. For production use,
# employ the optimized scanpy implementations:
#   - sc.pp.normalize_total(adata, target_sum=1e4) + sc.pp.log1p(adata)
#   - Or for SCTransform-style: scanpy.external.pp.scTransform(adata)
# These are computationally optimized and extensively tested on real datasets.

This implementation is intentionally transparent rather than optimized. It lets us inspect how the model behaves for an individual gene and across the genome.

Code
from collections import defaultdict

# Dense counts and size factors
X_dense = adata.X.toarray() if sp.issparse(adata.X) else adata.X
size_factors = X_dense.sum(axis=1)

# Panel (a): pick a moderately expressed gene
gene_for_demo = None
for candidate in ['LYZ', 'MS4A1', 'CD74']:
    if candidate in adata.var_names:
        gene_for_demo = candidate
        break
if gene_for_demo is None:
    gene_for_demo = adata.var_names[0]

g_idx = adata.var_names.get_loc(gene_for_demo)
counts_demo = X_dense[:, g_idx]
alpha_demo, beta_demo, theta_demo = fit_nb_glm_gene(counts_demo, size_factors)
mu_hat_demo = np.exp(alpha_demo + beta_demo * np.log(size_factors))

# Panels (b) and (c): sample genes for aggregated diagnostics
rng = np.random.default_rng(7)
candidate_indices = np.where((X_dense > 0).sum(axis=0) > 50)[0]
subset_indices = rng.choice(candidate_indices, size=min(120, len(candidate_indices)), replace=False)

mean_raw, var_raw = [], []
mean_mu, var_resid = [], []

for idx in subset_indices:
    counts = X_dense[:, idx]
    alpha, beta, theta = fit_nb_glm_gene(counts, size_factors)
    mu_hat = np.exp(alpha + beta * np.log(size_factors))
    resid = (counts - mu_hat) / np.sqrt(mu_hat + mu_hat**2 / theta)

    mean_raw.append(counts.mean())
    var_raw.append(counts.var())

    mean_mu.append(mu_hat.mean())
    var_resid.append(resid.var())

fig, axes = plt.subplots(1, 3)

# Panel (a)
axes[0].scatter(np.log1p(size_factors), counts_demo, alpha=0.4, color=QUALITATIVE_COLORS[0], s=25)
sf_grid = np.linspace(size_factors.min(), size_factors.max(), 200)
mu_grid = np.exp(alpha_demo + beta_demo * np.log(sf_grid))
axes[0].plot(np.log1p(sf_grid), mu_grid, color=QUALITATIVE_COLORS[1], linewidth=2.5)
axes[0].set_xlabel('log(size factor)')
axes[0].set_ylabel(f'Counts for {gene_for_demo}')
axes[0].set_title('(a) Technical trend and NB-GLM fit')
axes[0].grid(alpha=0.3)

# Panel (b)
axes[1].scatter(mean_raw, var_raw, alpha=0.5, color=QUALITATIVE_COLORS[2], s=25)
axes[1].plot([min(mean_raw), max(mean_raw)], [min(mean_raw), max(mean_raw)], '--', color='gray', linewidth=1.5)
axes[1].set_xlabel('Mean count')
axes[1].set_ylabel('Variance of counts')
axes[1].set_title('(b) Raw mean–variance relationship')
axes[1].set_xscale('log')
axes[1].set_yscale('log')
axes[1].grid(alpha=0.3)

# Panel (c)
axes[2].scatter(mean_mu, var_resid, alpha=0.5, color=QUALITATIVE_COLORS[3], s=25)
axes[2].hlines(1.0, xmin=min(mean_mu), xmax=max(mean_mu), colors='gray', linestyles='--', linewidth=1.5)
axes[2].set_xlabel('Mean fitted μ')
axes[2].set_ylabel('Variance of Pearson residuals')
axes[2].set_title('(c) Variance after residualization')
axes[2].set_xscale('log')
axes[2].grid(alpha=0.3)

plt.tight_layout()
plt.show()
Figure 4.3: Variance stabilization with an NB-GLM. (a) A single gene’s counts increase with sequencing depth (points), but the fitted model (line) captures that technical trend. (b) Across genes, raw mean and variance exhibit strong heteroskedasticity. (c) After NB-GLM residualization, the residual variance concentrates near one, demonstrating stabilization. The model translates mechanistic insight from Chapter 3 into cleaned features suitable for downstream dimensionality reduction.

Panels (a)–(c) show how the NB-GLM removes depth-dependent curvature and equalizes variance. This illustrates a fundamental choice in preprocessing: we can apply phenomenological transformations (such as the log transform) that improve statistical properties without explicit biological modeling, or we can use mechanistic modeling to explicitly account for technical variation (sequencing depth, batch effects, cell cycle) using the very stochastic processes we derived in earlier chapters. The NB-GLM approach links our mechanistic understanding directly to data cleaning.

From here forward, we will not dwell on the specific preprocessing choice. For pedagogical clarity, we use log-normalized counts throughout this chapter to keep the algebra transparent and the code compact. In production pipelines, analysts would substitute the more principled Pearson residuals or other variance-stabilized representations, but the dimensionality reduction methods we develop apply to any preprocessed matrix.

4.3 Principal Component Analysis: Linear Structure First

4.3.1 Problem: Find Linear Coordinates That Preserve Variance

We’ve seen that genes organize into correlated modules. This implies that the standard basis, where each axis is a single gene, is not optimal. The cloud of cells in high-dimensional space is elongated and tilted; the interesting variation does not lie neatly along the gene axes. This motivates the central idea of Principal Component Analysis (PCA): to find a better, more adapted basis for our data.

At its core, PCA is an orthogonal linear transformation that performs a rigid rotation of the coordinate system to align the new axes with the directions of maximum variance. We start with our data matrix X \in \mathbb{R}^{n \times p}, where each of the n rows is a cell and each of the p columns is a gene. After mean-centering the data by subtracting each gene’s average expression, we get the matrix \tilde{X}. PCA then finds a new basis, defined by a matrix of weights W \in \mathbb{R}^{p \times k}. Each column w_j of W is an orthonormal vector in gene space—a “gene program”—that defines a new axis called the j-th principal component. The transformed data, or principal component scores, are given by the projection T = \tilde{X}W. The score t_{ij} = \tilde{x}^{(i)} \cdot w_j is the coordinate of cell i along the new axis j.

This transformation provides two complementary views of the data:

  1. The Cell View: The scores T provide a new, low-dimensional representation of the cells. The axes are chosen to capture the directions of greatest variation, revealing how cells differ most from each other.

  2. The Gene View: The weight vectors W, also called loadings, define the principal components as linear combinations of genes. Each PC represents a “gene program” or “module,” which is a set of correlated genes that vary together across the cell population.

These two perspectives are mathematically equivalent. To make this formal, we can frame PCA as an optimization problem. The variance of the data projected onto a single direction w_j is given by the quadratic form w_j^T \Sigma w_j, where \Sigma = \frac{1}{n-1}\tilde{X}^T\tilde{X} is the sample covariance matrix. To find the k best orthogonal directions, we seek to maximize the total captured variance. This gives the optimization problem: \max_{W \in \mathbb{R}^{p \times k}} \operatorname{tr}\!\left(W^T \Sigma W\right) \quad \text{subject to } W^T W = I_k, The trace is simply the sum of the variances along each chosen component, \sum_{j=1}^k w_j^T \Sigma w_j.

4.3.2 Why This Works: The Variational Derivation

PCA is not just an algorithm; it is the unique solution to the problem of finding the orthogonal basis that maximizes variance. Let’s derive this for the first principal component, w_1.

We want to find the direction (a unit vector w_1) that captures the most variance. The variance of the data projected onto this vector is \text{Var}(\tilde{X}w_1) = w_1^T \Sigma w_1. We can solve this via a constrained optimization using a Lagrange multiplier \lambda: \mathcal{L}(w_1, \lambda) = w_1^T \Sigma w_1 - \lambda(w_1^T w_1 - 1). To find the maximum, we take the gradient with respect to w_1 and set it to zero: \nabla_{w_1} \mathcal{L} = 2\Sigma w_1 - 2\lambda w_1 = 0 \implies \Sigma w_1 = \lambda w_1. This is the fundamental eigenvalue equation. It reveals that the direction of maximum variance, w_1, must be an eigenvector of the covariance matrix \Sigma. What’s more, the variance captured along this direction is the eigenvalue itself: w_1^T \Sigma w_1 = w_1^T (\lambda w_1) = \lambda(w_1^T w_1) = \lambda.

Therefore, to maximize the variance, we must choose the eigenvector of \Sigma with the largest eigenvalue. This is the first principal component. The second principal component is found by repeating this optimization in the orthogonal complement of the space spanned by w_1, which inevitably yields the eigenvector with the second-largest eigenvalue. The full set of principal components is simply the orthonormal basis of eigenvectors of the covariance matrix, ordered by their corresponding eigenvalues.

But we don’t compute it this way.

Computing PCA in Practice via SVD

While the eigendecomposition of the covariance matrix \Sigma defines PCA, it is computationally inefficient (O(p^3)) and numerically unstable for high-dimensional data where p \gg n. In practice, PCA is computed via the Singular Value Decomposition (SVD) of the mean-centered data matrix \tilde{X} itself. The following derivation shows that these two approaches are mathematically equivalent.

Let the SVD of the centered data matrix be \tilde{X} = U S V^T, where U \in \mathbb{R}^{n \times n} and V \in \mathbb{R}^{p \times p} are orthogonal matrices, and S \in \mathbb{R}^{n \times p} is a rectangular diagonal matrix of non-negative singular values \sigma_1 \geq \sigma_2 \geq \dots \geq 0.

Now, let’s write the sample covariance matrix \Sigma in terms of the SVD of \tilde{X}: \Sigma = \frac{1}{n-1}\tilde{X}^T\tilde{X} = \frac{1}{n-1}(U S V^T)^T (U S V^T) = \frac{1}{n-1} V S^T U^T U S V^T. Since U is an orthogonal matrix, U^T U = I_n. The expression simplifies to: \Sigma = \frac{1}{n-1} V S^T S V^T. The matrix S^T S is a p \times p diagonal matrix with the squared singular values \sigma_j^2 on its diagonal. Let’s call this diagonal matrix \Lambda_{\text{svd}}. The equation becomes \Sigma = V (\frac{1}{n-1}\Lambda_{\text{svd}}) V^T.

This is an eigendecomposition of \Sigma. By inspection: 1. The columns of V (the right singular vectors of \tilde{X}) are the eigenvectors of \Sigma. These are the principal component loadings or directions that define each axis. 2. The eigenvalues of \Sigma are \lambda_j = \sigma_j^2 / (n-1). The variance captured by each PC is directly related to the corresponding singular value.

This equivalence is crucial. It allows us to compute the principal components by finding the right singular vectors of the data matrix \tilde{X} using efficient, iterative SVD algorithms (like randomized SVD) that avoid ever forming the massive covariance matrix \Sigma. The principal component scores are then simply T = \tilde{X}V = (USV^T)V = US(V^TV) = US.

4.3.3 Another View: PCA as Optimal Low-Rank Approximation

We’ve derived PCA as variance maximization via eigendecomposition. There’s an equivalent perspective: PCA performs optimal matrix factorization. The same W that maximizes variance also minimizes reconstruction error under the Frobenius norm, \min_{W^T W = I_k} \lVert \tilde{X} - \tilde{X} W W^T \rVert_F^2. The term \tilde{X} W W^T projects onto the k-dimensional subspace and reconstructs back to p dimensions. The equivalence follows because discarded variance equals reconstruction error—what we don’t capture is exactly what we lose. This matrix factorization perspective is powerful: other methods such as independent component analysis (ICA) and non-negative matrix factorization (NMF) impose different constraints and optimize different objectives, each with distinct strengths for particular biological questions.

4.3.4 Toy Example: Two Correlated Genes

Imagine we measure expression of just two genes across many cells. These genes might be correlated because they share regulation or participate in the same pathway—when one is highly expressed, the other tends to be as well. If we plot each cell as a point in this 2D space, we’ll see an elongated cloud. PCA responds by rotating the axes to align with that shared program: the first component points along the direction of greatest variance, and subsequent components capture orthogonal residual structure.

Code
# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

# Generate correlated 2D data
np.random.seed(42)
n_cells = 200

# True principal direction at 30 degrees
angle = np.pi/6
rotation_matrix = np.array([[np.cos(angle), -np.sin(angle)],
                            [np.sin(angle), np.cos(angle)]])

# Generate data along principal axes, then rotate
data_pca = np.random.randn(n_cells, 2) @ np.diag([3, 1])  # More variance along first axis
data_2d = data_pca @ rotation_matrix.T

# Mean-center the data
data_2d_centered = data_2d - np.mean(data_2d, axis=0)
Code
# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

# Compute PCA on the 2D toy data
cov_matrix = np.cov(data_2d_centered.T)
eigenvalues_2d, eigenvectors_2d = np.linalg.eigh(cov_matrix)

# Sort by decreasing eigenvalue
idx = eigenvalues_2d.argsort()[::-1]
eigenvalues_2d = eigenvalues_2d[idx]
eigenvectors_2d = eigenvectors_2d[:, idx]

# Project onto PC1 and PC2
pc1_scores = data_2d_centered @ eigenvectors_2d[:, 0]
pc2_scores = data_2d_centered @ eigenvectors_2d[:, 1]
pc1_projected = np.outer(pc1_scores, eigenvectors_2d[:, 0])
pcs_2d = np.column_stack([pc1_scores, pc2_scores])

fig, (ax1, ax2) = plt.subplots(1, 2)

# Panel (a): original gene space with PC arrows and PC1 projections
ax1.scatter(data_2d_centered[:, 0], data_2d_centered[:, 1],
           c='gray', s=40, alpha=0.6, label='Cells')

# Mark the mean (origin after centering)
ax1.plot(0, 0, 'kx', markersize=10, markeredgewidth=3, label='Mean')

# Draw PC arrows from origin
scale = 3.0  # Scale arrows for visibility
ax1.arrow(0, 0, scale * eigenvalues_2d[0]**0.5 * eigenvectors_2d[0, 0],
         scale * eigenvalues_2d[0]**0.5 * eigenvectors_2d[1, 0],
         head_width=0.3, head_length=0.4, fc=QUALITATIVE_COLORS[0],
         ec=QUALITATIVE_COLORS[0], linewidth=2.5, label='PC1')

ax1.arrow(0, 0, scale * eigenvalues_2d[1]**0.5 * eigenvectors_2d[0, 1],
         scale * eigenvalues_2d[1]**0.5 * eigenvectors_2d[1, 1],
         head_width=0.3, head_length=0.4, fc=QUALITATIVE_COLORS[1],
         ec=QUALITATIVE_COLORS[1], linewidth=2.5, label='PC2')

# Show projections onto PC1 as dots
ax1.scatter(pc1_projected[:, 0], pc1_projected[:, 1],
           c=QUALITATIVE_COLORS[0], s=15, alpha=0.5, label='PC1 projections')

ax1.set_xlabel('Gene 1 (centered)')
ax1.set_ylabel('Gene 2 (centered)')
ax1.set_title('(a) Original gene space')
ax1.legend(loc='upper left')
ax1.grid(alpha=0.3)
ax1.set_aspect('equal')

# Panel (b): same points in PC coordinate space
ax2.scatter(pcs_2d[:, 0], pcs_2d[:, 1],
           c=QUALITATIVE_COLORS[1], s=20, alpha=0.6)
ax2.set_xlabel('PC1')
ax2.set_ylabel('PC2')
ax2.set_title('(b) PC1 vs PC2 coordinates')
ax2.grid(alpha=0.3)
ax2.set_aspect('equal')

plt.tight_layout()
plt.show()
Figure 4.4: (a) PCA finds directions of maximum variance in the original gene space. Cells form an elongated cloud; the first principal component (red arrow) points along the direction of greatest spread, and the second PC (blue) captures the orthogonal residual variation. Red points show the projection of cells onto PC1. (b) The same data expressed in PC coordinates (PC1 vs PC2) appear axis-aligned, showing that PCA is a rotation that concentrates variance along PC1.

4.3.5 Real Application: PBMC Principal Components

Armed with the SVD formulation, we now compute PCA on the PBMC dataset. We follow standard practice: log-normalize counts, select highly variable genes to focus on biological signal, and compute a truncated SVD so that we never form the 13{,}714 \times 13{,}714 covariance matrix explicitly.

Code
def pca_from_scratch(X, n_components=50):
    """
    PCA via eigendecomposition of the covariance matrix.

    Parameters:
    -----------
    X : array-like, shape (n_cells, n_genes)
        Gene expression matrix
    n_components : int
        Number of principal components to return

    Returns:
    --------
    pcs : array, shape (n_cells, n_components)
        Principal component scores
    loadings : array, shape (n_genes, n_components)
        Principal component loadings (eigenvectors)
    variance_explained : array, shape (n_components,)
        Variance explained by each PC
    """
    # Step 1: Mean-center the data
    X_centered = X - np.mean(X, axis=0)

    # Step 2: Compute covariance matrix
    # Note: For large p, this is memory-intensive. We do it for demonstration.
    Sigma = (X_centered.T @ X_centered) / (X.shape[0] - 1)

    # Step 3: Eigendecomposition
    eigenvalues, eigenvectors = np.linalg.eigh(Sigma)

    # Step 4: Sort by decreasing eigenvalue
    idx = eigenvalues.argsort()[::-1]
    eigenvalues = eigenvalues[idx]
    eigenvectors = eigenvectors[:, idx]

    # Step 5: Project data onto principal components
    pcs = X_centered @ eigenvectors[:, :n_components]

    return pcs, eigenvectors[:, :n_components], eigenvalues[:n_components]

# Apply to log-normalized PBMC data
# (We'll work on a subset of highly variable genes for computational efficiency)
# First, identify highly variable genes for PCA computation
sc.pp.normalize_total(adata, target_sum=1e4)
sc.pp.log1p(adata)
sc.pp.highly_variable_genes(adata, n_top_genes=2000)

adata_hvg = adata[:, adata.var.highly_variable].copy()
X_log = adata_hvg.X.toarray() if sp.issparse(adata_hvg.X) else adata_hvg.X

pcs_scratch, loadings_scratch, var_explained_scratch = pca_from_scratch(X_log, n_components=50)

print(f"Computed {pcs_scratch.shape[1]} PCs for {pcs_scratch.shape[0]} cells")
print(f"Variance explained by PC1: {var_explained_scratch[0] / var_explained_scratch.sum():.1%}")
print(f"Variance explained by PC1-10: {var_explained_scratch[:10].sum() / var_explained_scratch.sum():.1%}")
Computed 50 PCs for 2700 cells
Variance explained by PC1: 32.5%
Variance explained by PC1-10: 65.9%
Code
# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

fig, (ax1, ax2) = plt.subplots(1, 2)

# Panel A: Scree plot
variance_ratio = var_explained_scratch / var_explained_scratch.sum()
cumulative_variance = np.cumsum(variance_ratio)

ax1.plot(range(1, len(variance_ratio) + 1), variance_ratio * 100,
        'o-', linewidth=2.5, markersize=4, color=QUALITATIVE_COLORS[0])
ax1.axhline(y=10, linestyle='--', color='gray', linewidth=1.5,
           alpha=0.7, label='~10% threshold')
ax1.set_xlabel('Principal Component')
ax1.set_ylabel('Variance Explained (%)')
ax1.set_title('(a) Scree Plot')
ax1.grid(alpha=0.3)
ax1.legend()

# Panel B: PC1 vs PC2 scatter
# For demonstration, we'll use a simple coloring based on PC values
# In practice, this would use known cell type labels
# Create pseudo-labels based on PC1 and PC2 values for visualization
pc1_vals = pcs_scratch[:, 0]
pc2_vals = pcs_scratch[:, 1]

ax2.scatter(pc1_vals, pc2_vals, c=QUALITATIVE_COLORS[1], s=20, alpha=0.5)
ax2.set_xlabel(f'PC1 ({variance_ratio[0]:.1%} var.)')
ax2.set_ylabel(f'PC2 ({variance_ratio[1]:.1%} var.)')
ax2.set_title('(b) PC1 vs PC2')
ax2.grid(alpha=0.3)

plt.tight_layout()
plt.show()
Figure 4.5: (a) Variance distribution across principal components. The first PC captures the largest share, and the first 10 PCs together account for the majority. The elbow around PC 10-15 suggests diminishing returns from additional components. (b) Cells separate in PC space, forming distinct clusters despite PCA being unsupervised.

To understand what these components represent biologically, we inspect the loadings, which are the weights each gene receives in each principal component:

Code
# Get gene names for HVGs
hvg_names = adata.var_names[adata.var.highly_variable].values

# Find top genes for PC1 and PC2
n_top = 20
pc1_loadings = loadings_scratch[:, 0]
pc2_loadings = loadings_scratch[:, 1]

# Get top genes by absolute loading for each PC
top_pc1_idx = np.argsort(np.abs(pc1_loadings))[-n_top:][::-1]
top_pc2_idx = np.argsort(np.abs(pc2_loadings))[-n_top:][::-1]

# Combine and get unique genes
top_genes_idx = np.unique(np.concatenate([top_pc1_idx, top_pc2_idx]))
top_genes_names = hvg_names[top_genes_idx]

# Create loading matrix for these genes
loading_matrix = np.column_stack([
    pc1_loadings[top_genes_idx],
    pc2_loadings[top_genes_idx]
])

# Use diverging colormap from GeoDataViz
# d2 palette: blue (negative) to red (positive)
from matplotlib.colors import LinearSegmentedColormap
d2_colors = ['#045275', '#089099', '#7CCBA2', '#FCDE9C', '#F0746E', '#DC3977', '#7C1D6F']
diverging_cmap = LinearSegmentedColormap.from_list('d2', d2_colors)

fig, ax = plt.subplots()
im = ax.imshow(loading_matrix, aspect='auto', cmap=diverging_cmap,
              vmin=-np.abs(loading_matrix).max(),
              vmax=np.abs(loading_matrix).max())

ax.set_xticks([0, 1])
ax.set_xticklabels(['PC1', 'PC2'])
ax.set_yticks(range(len(top_genes_names)))
ax.set_yticklabels(top_genes_names, fontsize=8)
ax.set_xlabel('Principal Component')
ax.set_ylabel('Gene')
ax.set_title('Gene Loadings for PC1 and PC2')

# Add colorbar
cbar = plt.colorbar(im, ax=ax, label='Loading')
ax.grid(alpha=0.3)

plt.tight_layout()
plt.show()
Figure 4.6: Top gene contributors to PC1 and PC2. Each row shows a gene’s loading (weight) on the two leading principal components. High positive loadings (red) and negative loadings (blue) indicate genes that strongly define each axis.

The loadings reveal that each principal component captures a coherent biological program. In this dataset, PC1 is typically dominated by proliferation-related genes—the divide between actively cycling and quiescent cells drives the largest axis of variation. PC2 usually separates major cell types through lineage-specific markers. Later components blend subtler biology (activation states, cell subpopulations) with technical noise. This pattern—where top PCs reflect major biological processes—arises because gene expression programs are modular and cells vary most along a few dominant axes.

How many should we keep? While strategies like cumulative variance thresholds (e.g., 80%) or parallel analysis exist, the practical answer for scRNA-seq is pragmatic: use 30–50 PCs for downstream tasks like clustering and neighborhood graphs. This range captures biological signal while averaging over noise. For datasets with tens of thousands of cells, analysts sometimes retain even more—50 to 500 components—to filter technical variation without discarding rare cell state signatures. The threshold is somewhat arbitrary; we prioritize interpretability and computational tractability over a strict variance cutoff. We’ll use the first 30–50 PCs for clustering, reserving only the first 2–3 for visualization.

4.3.6 The Limitation: Why PCA Isn’t Enough

PCA has a fundamental assumption: it finds linear relationships. Mathematically, it’s searching for flat hyperplanes in high-dimensional space that capture the most variation. When we project onto the first few PCs, we’re assuming the data lie near a low-dimensional linear subspace.

But biological processes aren’t linear. Cell differentiation is a continuous trajectory through gene expression space. Imagine a stem cell gradually activating some genes and repressing others as it matures. This creates a curved manifold, not a flat plane.

Here’s a simple example that breaks PCA:

Code
# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

# Generate Swiss roll data with extended range for more dramatic demonstration
# Manual implementation allows precise control over the manifold's length
n_samples = 1200
np.random.seed(42)

# Extend parameter range from default [1.5π, 4.5π] to [1.5π, 7.5π]
# This creates more wrapping, making PCA's failure more apparent
t = np.linspace(1.5 * np.pi, 3.5 * np.pi, n_samples)
height = np.random.uniform(-25, 25, n_samples)  # Random vertical spread

# Swiss roll parameterization: spiral that wraps around itself
x = t * np.cos(t)
y = height
z = t * np.sin(t)

# Add small noise to make it realistic
noise_scale = 0.5
x += np.random.randn(n_samples) * noise_scale
y += np.random.randn(n_samples) * noise_scale
z += np.random.randn(n_samples) * noise_scale

swiss_roll_3d = np.column_stack([x, y, z])
swiss_roll_color = t  # Color by position along the trajectory

# Center the data
swiss_roll_centered = swiss_roll_3d - np.mean(swiss_roll_3d, axis=0)

# Compute PCA (top 2 components)
cov_swiss = np.cov(swiss_roll_centered.T)
eigenvals_swiss, eigenvecs_swiss = np.linalg.eigh(cov_swiss)
idx_swiss = eigenvals_swiss.argsort()[::-1]
eigenvecs_swiss = eigenvecs_swiss[:, idx_swiss]

# Project onto PC1 and PC2
pcs_swiss = swiss_roll_centered @ eigenvecs_swiss[:, :2]

fig = plt.figure()

# Panel A: 3D Swiss roll
ax1 = fig.add_subplot(121, projection='3d')
scatter1 = ax1.scatter(swiss_roll_3d[:, 0], swiss_roll_3d[:, 1], swiss_roll_3d[:, 2],
                       c=swiss_roll_color, cmap='plasma', s=10, alpha=0.6)
ax1.set_xlabel('Gene 1')
ax1.set_ylabel('Gene 2')
ax1.set_zlabel('Gene 3')
ax1.set_title('(a) Swiss roll in 3D')
ax1.view_init(elev=10, azim=60)
plt.colorbar(scatter1, ax=ax1, label='Position along trajectory', shrink=0.6)

# Panel B: PCA projection
ax2 = fig.add_subplot(122)
scatter2 = ax2.scatter(pcs_swiss[:, 0], pcs_swiss[:, 1],
                       c=swiss_roll_color, cmap='plasma', s=10, alpha=0.6)
ax2.set_xlabel('PC1')
ax2.set_ylabel('PC2')
ax2.set_title('(b) PCA projection (PC1 vs PC2)')
ax2.grid(alpha=0.3)
plt.colorbar(scatter2, ax=ax2, label='Position along trajectory')

plt.tight_layout()
plt.show()
Figure 4.7: PCA assumes linearity and fails on curved manifolds. (a) A Swiss roll: cells lie on a 2D manifold embedded in 3D space, colored by their position along the intrinsic 1D trajectory. (b) PCA’s first two components project to 2D but don’t unroll the manifold—they simply flatten it from a different viewing angle. Points that are far apart along the trajectory (different colors) appear nearby in PC space where the roll overlaps. This motivates the need for nonlinear dimensionality reduction methods.

The Swiss roll demonstrates PCA’s fundamental limitation: it finds the best linear subspace but cannot unroll or unfold curved manifolds. When cells lie on a nonlinear trajectory, such as a differentiation path, a cell cycle, or a branching fate decision, PCA preserves local neighborhoods but distorts global relationships. Points that are far apart along the true trajectory can appear nearby in PC space wherever the manifold folds back on itself.

This doesn’t make PCA useless. It remains the essential first step in nearly every scRNA-seq analysis: we use it to denoise, remove technical variation, and compute neighborhoods in 30–50 dimensions. But for visualization in 2D, and for exposing the intrinsic geometry of curved manifolds, we need nonlinear methods.

4.4 Nonlinear Embeddings: Preserving Curved Geometry

We’ve seen that PCA excels at finding linear structure but struggles with curves. Cells differentiating along a trajectory, cycling through states, or following branching paths create manifolds, which are surfaces embedded in high-dimensional space. To visualize these structures in 2D while preserving their essential geometry, we need nonlinear dimensionality reduction.

Before exploring specific methods, we must confront a fundamental impossibility result: no algorithm can perfectly preserve all distances when reducing dimensionality. The Johnson–Lindenstrauss lemma quantifies this tradeoff.

Theorem (Johnson–Lindenstrauss Lemma)

Formal statement: Given 0 < \varepsilon < 1, a set X of N points in \mathbb{R}^n, and an integer k > 8(\ln N)/\varepsilon^2, there exists a linear map f: \mathbb{R}^n \to \mathbb{R}^k such that (1 - \varepsilon)\|u - v\|^2 \leq \|f(u) - f(v)\|^2 \leq (1 + \varepsilon)\|u - v\|^2 for all u, v \in X.

What it means: We can embed N points from high dimensions into k \approx O(\log N / \varepsilon^2) dimensions while distorting all pairwise distances by at most a factor of (1 \pm \varepsilon). Crucially, the target dimension k depends logarithmically on N but polynomially on the allowed distortion \varepsilon.

The tightness: The lemma is tight up to constant factors. There exist point sets requiring \Omega(\log N / \varepsilon^2) dimensions to preserve distances within (1 \pm \varepsilon).

Implications for scRNA-seq: With N = 2{,}700 cells, reducing from d = 50 PCs to k = 2 dimensions for visualization, we can solve for the inevitable distortion. Rearranging k = 8(\ln N)/\varepsilon^2 gives \varepsilon \approx \sqrt{8 \ln(2700) / 2} \approx 5.6, which already violates the theorem’s requirement that 0 < \varepsilon < 1. In other words, the Johnson–Lindenstrauss lemma offers no guarantee whatsoever that a distance-preserving linear map into 2D exists for our dataset. This impossibility result is algorithm-agnostic: no linear or nonlinear method can preserve all pairwise distances, so every embedding must decide which relationships to protect and which to distort.

With this impossibility result established, we evaluate nonlinear methods by inspecting what geometry they choose to protect. Two methods dominate single-cell visualization: t-SNE, which prioritizes preserving local neighborhoods, and UMAP, which balances local and global structure. Let’s start with t-SNE.

4.4.1 t-SNE: Preserving Local Neighborhoods

t-Distributed Stochastic Neighbor Embedding (t-SNE), introduced by van der Maaten and Hinton in 2008 (Maaten and Hinton 2008), is a nonlinear dimensionality reduction method that finds a low-dimensional embedding y_1, \ldots, y_n \in \mathbb{R}^2 of high-dimensional points x_1, \ldots, x_n. The method works by (1) measuring pairwise similarities in high-dimensional space using a Gaussian kernel, (2) defining analogous similarities in low-dimensional space using a Student-t distribution, and (3) positioning the low-dimensional points to minimize the divergence between these two similarity distributions.

The core philosophy is elegant: keep similar points together in the embedding, and push dissimilar points far apart. Unlike PCA, which preserves global distances through linear projection, t-SNE focuses on local neighborhoods, preserving who each cell’s nearest neighbors are, rather than exact distances.

Let’s make this precise. For cells i and j in high-dimensional space (e.g., in PCA space with 50 dimensions), define the conditional probability that i would pick j as its neighbor: p_{j|i} = \frac{\exp(-\|x_i - x_j\|^2 / 2\sigma_i^2)}{\sum_{k \neq i} \exp(-\|x_i - x_k\|^2 / 2\sigma_i^2)}

Here, \sigma_i is a bandwidth chosen adaptively for each point to maintain a target “perplexity” (loosely, the effective number of neighbors). We symmetrize to get: p_{ij} = \frac{p_{j|i} + p_{i|j}}{2n}

In the low-dimensional embedding with coordinates y_i, we define analogous similarities using a Student t-distribution with one degree of freedom (also called the Cauchy distribution): q_{ij} = \frac{(1 + \|y_i - y_j\|^2)^{-1}}{\sum_{k \neq \ell} (1 + \|y_k - y_\ell\|^2)^{-1}}

Why the Student-t distribution? This is the key innovation. In high dimensions, there’s “room” for many points at moderate distances. But when we cram everything into 2D, points get squeezed. This is called the crowding problem. The heavy tails of the Student-t allow dissimilar points to spread out in 2D without penalty, preventing the embedding from collapsing.

To find the 2D coordinates \{y_i\}, the algorithm minimizes the Kullback-Leibler (KL) divergence between the high-D (p_{ij}) and low-D (q_{ij}) probability distributions: C = \sum_{i \neq j} p_{ij} \log \frac{p_{ij}}{q_{ij}}. This measures how well the 2D embedding preserves the neighborhood structure from high dimensions. Taking the gradient of this objective with respect to the embedding coordinates y_i reveals an intuitive physical analogy: \frac{\partial C}{\partial y_i} = 4\sum_{j \neq i} (p_{ij} - q_{ij})(y_i - y_j)(1 + \|y_i - y_j\|^2)^{-1}. This is a force-directed layout. The term (p_{ij} - q_{ij}) creates an attractive force for neighbors (p_{ij} > q_{ij}, meaning they’re closer in high-D than in low-D) and a repulsive force for non-neighbors (p_{ij} < q_{ij}, meaning they’re artificially close in the embedding). Both forces decay as (1 + d^2)^{-1}, where d = \|y_i - y_j\|. Nearby points exert strong forces; distant points exert weak forces. The algorithm uses gradient descent with momentum to find the embedding, iteratively repositioning cells until these forces balance.

The critical limitation of t-SNE: It destroys global structure. The KL divergence objective only cares about matching local neighborhoods. Distances between clusters are meaningless. If you see two clusters far apart in a t-SNE plot, you cannot conclude they’re biologically dissimilar. They might be very close in high-dimensional space, just separated for visualization clarity.

This is not a bug; it’s a feature. t-SNE prioritizes local structure, accepting the loss of global information as a necessary trade-off for visualizing complex data.

4.4.2 UMAP: Topological Structure and Better Balance

Uniform Manifold Approximation and Projection (UMAP) (McInnes et al. 2018) is a nonlinear dimensionality reduction method that constructs a low-dimensional embedding y_1, \ldots, y_n \in \mathbb{R}^2 by modeling the data as a fuzzy topological structure. Like t-SNE, it finds embeddings that preserve relationships from high dimensions. The key differences lie in how it measures those relationships and what objective it optimizes.

Where t-SNE uses probabilistic similarities, UMAP builds a weighted graph (a fuzzy simplicial complex) where edge weights w_{ij} represent fuzzy set membership in local neighborhoods. It then finds a low-dimensional graph with analogous structure by minimizing a cross-entropy loss between the high- and low-dimensional edge weights.

The core differences from t-SNE:

  1. Topological perspective: Instead of probabilistic similarities, UMAP constructs a fuzzy simplicial complex, which is a high-dimensional generalization of a graph where edges have weights w_{ij} representing “fuzzy membership” in connected components. This provides a more flexible model of manifold structure.

  2. Cross-entropy objective: Instead of KL divergence (which is asymmetric), UMAP minimizes a symmetric cross-entropy between high-D and low-D fuzzy set memberships: C = \sum_{ij} \left[ w_{ij}^{\text{high}} \log \frac{w_{ij}^{\text{high}}}{w_{ij}^{\text{low}}} + (1-w_{ij}^{\text{high}}) \log \frac{1-w_{ij}^{\text{high}}}{1-w_{ij}^{\text{low}}} \right]. The first term penalizes compressing true neighbors (high membership in high-D should remain high in low-D). The second term penalizes separating non-neighbors. This balanced loss treats attraction and repulsion symmetrically, unlike t-SNE’s asymmetric KL divergence which heavily penalizes false neighbors but weakly rewards preserved distances.

  3. Better global structure: The symmetric loss and exponential distance kernel (rather than Gaussian + Student-t) preserve more global relationships than t-SNE. Distances between clusters carry more meaning, though they still require quantitative validation via trustworthiness metrics.

Practical advantages of UMAP:

  • Faster: O(n^{1.14}) complexity vs O(n^2) for t-SNE (though approximations bring t-SNE closer)
  • More stable: Less sensitive to hyperparameters
  • Deterministic: Given the same random seed, produces identical results
  • Better global preservation: Distances between clusters are more meaningful (though still not perfectly reliable)

Both methods are widely used. t-SNE has more theoretical development and longer history. UMAP is newer but often preferred for its speed and stability. For an interactive exploration of how UMAP’s hyperparameters (n_neighbors and min_dist) affect embeddings, see Understanding UMAP, which lets you compare t-SNE and UMAP side-by-side on various datasets.

Before applying these methods to real data, let’s test them on a simple toy dataset where we know the ground truth structure. This will reveal their personalities—how they handle the tradeoff between local neighborhoods and global topology.

We will create a nested structure: a dense cluster embedded within a sparse cloud. Both groups share the same center in 3D space, but have vastly different densities. This tests a key question: can the embedding preserve the global relationship (one group surrounds the other), or does it sacrifice topology for local cluster separation?

Code
import numpy as np

np.random.seed(42)

# Outer (sparse) cluster: 1000 points, wide spread
outer_cluster = np.random.multivariate_normal(
    mean=[0, 0, 0],
    cov=np.diag([2.5, 2.5, 1.0]),
    size=1000
)

# Inner (dense) cluster: 500 points, tight core
inner_cluster = np.random.multivariate_normal(
    mean=[0, 0, 0],
    cov=np.diag([0.2, 0.2, 0.2]),
    size=500
)

# Combine and create labels
X_toy = np.vstack([outer_cluster, inner_cluster])
y_toy = np.array([0]*1000 + [1]*500)  # 0 = outer, 1 = inner

print(f"Toy dataset: {X_toy.shape[0]} points in {X_toy.shape[1]}D")
print(f"Outer cluster: {np.sum(y_toy == 0)} points (sparse)")
print(f"Inner cluster: {np.sum(y_toy == 1)} points (dense)")
Toy dataset: 1500 points in 3D
Outer cluster: 1000 points (sparse)
Inner cluster: 500 points (dense)

Now we apply PCA, t-SNE, and UMAP to see how each method handles the nested structure:

Code
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
import umap

# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

# Apply dimensionality reduction methods
pca_toy = PCA(n_components=2, random_state=42)
toy_pca_2d = pca_toy.fit_transform(X_toy)

tsne_toy = TSNE(n_components=2, perplexity=30, random_state=42)
toy_tsne_2d = tsne_toy.fit_transform(X_toy)

umap_toy = umap.UMAP(n_components=2, n_neighbors=50, min_dist=0.1, random_state=42)
toy_umap_2d = umap_toy.fit_transform(X_toy)

# Create 2x2 grid
fig = plt.figure()

# Panel A: 3D original
ax1 = fig.add_subplot(2, 2, 1, projection='3d')
ax1.scatter(outer_cluster[:, 0], outer_cluster[:, 1], outer_cluster[:, 2],
           c=QUALITATIVE_COLORS[1], s=20, alpha=0.4, label='Outer (sparse)')
ax1.scatter(inner_cluster[:, 0], inner_cluster[:, 1], inner_cluster[:, 2],
           c=QUALITATIVE_COLORS[0], s=20, alpha=0.6, label='Inner (dense)')
ax1.set_xlabel('Dim 1')
ax1.set_ylabel('Dim 2')
ax1.set_zlabel('Dim 3')
ax1.set_title('(a) Original 3D structure')
ax1.legend()
ax1.view_init(elev=20, azim=45)

# Panel B: PCA
ax2 = fig.add_subplot(2, 2, 2)
for label, color in zip([0, 1], [QUALITATIVE_COLORS[1], QUALITATIVE_COLORS[0]]):
    mask = y_toy == label
    ax2.scatter(toy_pca_2d[mask, 0], toy_pca_2d[mask, 1],
                c=color, s=20, alpha=0.5,
                label='Outer' if label == 0 else 'Inner')
ax2.set_xlabel('PC 1')
ax2.set_ylabel('PC 2')
ax2.set_title('(b) PCA: Linear overlap')
ax2.grid(alpha=0.3)
ax2.legend()

# Panel C: t-SNE
ax3 = fig.add_subplot(2, 2, 3)
for label, color in zip([0, 1], [QUALITATIVE_COLORS[1], QUALITATIVE_COLORS[0]]):
    mask = y_toy == label
    ax3.scatter(toy_tsne_2d[mask, 0], toy_tsne_2d[mask, 1],
                c=color, s=20, alpha=0.5,
                label='Outer' if label == 0 else 'Inner')
ax3.set_xlabel('t-SNE 1')
ax3.set_ylabel('t-SNE 2')
ax3.set_title('(c) t-SNE: Side-by-side separation')
ax3.grid(alpha=0.3)
ax3.legend()

# Panel D: UMAP
ax4 = fig.add_subplot(2, 2, 4)
for label, color in zip([0, 1], [QUALITATIVE_COLORS[1], QUALITATIVE_COLORS[0]]):
    mask = y_toy == label
    ax4.scatter(toy_umap_2d[mask, 0], toy_umap_2d[mask, 1],
                c=color, s=20, alpha=0.5,
                label='Outer' if label == 0 else 'Inner')
ax4.set_xlabel('UMAP 1')
ax4.set_ylabel('UMAP 2')
ax4.set_title('(d) UMAP: Nested structure preserved')
ax4.grid(alpha=0.3)
ax4.legend()

plt.tight_layout()
plt.show()
Figure 4.8: Dimensionality reduction methods on nested structure. (a) Original 3D data shows a dense red cluster embedded within a sparse blue cloud. (b) PCA fails to separate the groups—both clusters share the same center, so the linear projection overlaps them. (c) t-SNE separates the groups into side-by-side clusters, discarding the global nested topology to prioritize local distinctness. (d) UMAP preserves the nested relationship, with the dense core surrounded by the sparse cloud, balancing local and global structure.

The contrast reveals each method’s core philosophy. PCA fails entirely—because both clusters share the same center, the linear projection collapses them into overlapping clouds. No amount of rotation can separate groups that differ in density rather than location. t-SNE renders two equally-sized, equally-dense clusters side by side, completely discarding the information that one cluster is nested within the other. It prioritizes making local neighborhoods distinct, even at the cost of global topology. UMAP, by contrast, preserves the nested relationship: the dense core remains surrounded by the diffuse cloud. With n_neighbors=50, UMAP balances local detail with global structure. This toy example captures the hierarchy of these methods—PCA is blind to nonlinear structure, t-SNE pulls clusters apart for visual clarity, and UMAP maintains the larger topology. We now know what to watch for when noise and heterogeneity enter the picture.

Now, let’s apply both to our PBMC data:

Code
from sklearn.manifold import TSNE
import umap

# We'll work in PCA space (first 50 PCs) as is standard practice
adata.obsm['X_pca'] = pcs_scratch  # Use our computed PCs

# t-SNE embedding
tsne = TSNE(n_components=2, perplexity=30, random_state=42)
adata.obsm['X_tsne'] = tsne.fit_transform(adata.obsm['X_pca'])

# UMAP embedding
umap_model = umap.UMAP(n_neighbors=15, min_dist=0.1, n_components=2, random_state=42)
adata.obsm['X_umap'] = umap_model.fit_transform(adata.obsm['X_pca'])

print("Embeddings computed:")
print(f"  t-SNE: {adata.obsm['X_tsne'].shape}")
print(f"  UMAP: {adata.obsm['X_umap'].shape}")
Embeddings computed:
  t-SNE: (2700, 2)
  UMAP: (2700, 2)
Code
# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

fig, (ax1, ax2) = plt.subplots(1, 2)

# Panel A: t-SNE
ax1.scatter(adata.obsm['X_tsne'][:, 0], adata.obsm['X_tsne'][:, 1],
           c=QUALITATIVE_COLORS[0], s=20, alpha=0.6)
ax1.set_xlabel('t-SNE 1')
ax1.set_ylabel('t-SNE 2')
ax1.set_title('(a) t-SNE (perplexity=30)')
ax1.grid(alpha=0.3)

# Panel B: UMAP
ax2.scatter(adata.obsm['X_umap'][:, 0], adata.obsm['X_umap'][:, 1],
           c=QUALITATIVE_COLORS[1], s=20, alpha=0.6)
ax2.set_xlabel('UMAP 1')
ax2.set_ylabel('UMAP 2')
ax2.set_title('(b) UMAP (n_neighbors=15, min_dist=0.1)')
ax2.grid(alpha=0.3)

plt.tight_layout()
plt.show()
Figure 4.9: t-SNE and UMAP reveal similar cell type structure but with different aesthetics. (left) t-SNE creates tighter, more separated clusters with clear boundaries. (right) UMAP maintains more connectivity between related cell types, suggesting the differentiation relationships between populations. Both were computed on the first 50 PCs, not on raw gene expression, following best practices.

To see how these dimensionality reduction methods compare, we’ll test them on the MNIST dataset—a collection of 28×28 grayscale images of handwritten digits (0–9), giving us 784-dimensional vectors with clear labels.

Code
import numpy as np
from sklearn.datasets import fetch_openml

# For reproducibility
np.random.seed(42)

# Load MNIST data
mnist = fetch_openml('mnist_784', version=1, parser='auto', as_frame=False)

# Create a random subset of 5000 samples for efficiency
sample_indices = np.random.choice(mnist.data.shape[0], 5000, replace=False)

X_mnist = mnist.data[sample_indices]
# Ensure labels are integers for coloring
y_mnist = mnist.target[sample_indices].astype(int)

# Normalize pixel values to the [0, 1] range
X_mnist_normalized = X_mnist / 255.0

print(f"MNIST subset: {X_mnist_normalized.shape[0]} samples, {X_mnist_normalized.shape[1]} features")
print(f"Labels (digits 0-9): {np.unique(y_mnist)}")
MNIST subset: 5000 samples, 784 features
Labels (digits 0-9): [0 1 2 3 4 5 6 7 8 9]

4.4.3 Generative Embeddings: Variational Autoencoders

The methods we have seen so far (PCA, t-SNE, UMAP) are discriminative. They learn a one-way map from the high-dimensional data space X to a low-dimensional latent space Z, f: \mathbf{x} \to \mathbf{z}. They do not, however, model the data distribution p(\mathbf{x}) itself. We cannot use a UMAP embedding to generate new, synthetic cells that resemble our dataset.

This motivates a shift toward generative models that learn the underlying probability structure. A Variational Autoencoder (VAE) takes this approach, learning a probabilistic mapping between the data \mathbf{x} \in \mathbb{R}^p and a lower-dimensional latent space \mathbf{z} \in \mathbb{R}^k (where k \ll p).

4.4.3.1 The Latent Variable Model

The core idea is to assume our data \mathbf{x} is generated by a latent variable \mathbf{z}. This process has two steps:

  1. A latent code is sampled from a simple prior distribution: \mathbf{z} \sim p(\mathbf{z}). We typically choose p(\mathbf{z}) = \mathcal{N}(0, I).
  2. A data point is generated from the code by a complex, parameterized function (the decoder): \mathbf{x} \sim p_\theta(\mathbf{x}|\mathbf{z}).

The marginal likelihood of our data is then p_\theta(\mathbf{x}) = \int p_\theta(\mathbf{x}|\mathbf{z}) p(\mathbf{z}) d\mathbf{z}. This integral is intractable because it requires integrating over all possible latent codes—a high-dimensional and complex space. This intractability also means we cannot compute the true posterior p_\theta(\mathbf{z}|\mathbf{x}) = p_\theta(\mathbf{x}|\mathbf{z})p(\mathbf{z}) / p_\theta(\mathbf{x}) using Bayes’ rule.

4.4.3.2 The Variational Solution: Deriving the ELBO

Since we cannot compute the true posterior p_\theta(\mathbf{z}|\mathbf{x}), we introduce a second neural network to approximate it. This network is the encoder, q_\phi(\mathbf{z}|\mathbf{x}), which maps a data point \mathbf{x} to a distribution over the latent space.

Our goal is to make our approximation q_\phi(\mathbf{z}|\mathbf{x}) as “close” as possible to the true (but intractable) posterior p_\theta(\mathbf{z}|\mathbf{x}). We measure this “closeness” using the Kullback-Leibler (KL) divergence:

D_{KL}(q_\phi(\mathbf{z}|\mathbf{x}) \| p_\theta(\mathbf{z}|\mathbf{x})) = \mathbb{E}_{\mathbf{z} \sim q_\phi}[\log q_\phi(\mathbf{z}|\mathbf{x}) - \log p_\theta(\mathbf{z}|\mathbf{x})]

Let’s expand the \log p_\theta(\mathbf{z}|\mathbf{x}) term using Bayes’ rule (p_\theta(\mathbf{z}|\mathbf{x}) = \frac{p_\theta(\mathbf{x}|\mathbf{z})p(\mathbf{z})}{p_\theta(\mathbf{x})}):

\begin{align*} D_{KL}(q_\phi \| p_\theta) &= \mathbb{E}_{q_\phi}[\log q_\phi(\mathbf{z}|\mathbf{x}) - \log \left( \frac{p_\theta(\mathbf{x}|\mathbf{z})p(\mathbf{z})}{p_\theta(\mathbf{x})} \right)] \\ &= \mathbb{E}_{q_\phi}[\log q_\phi(\mathbf{z}|\mathbf{x}) - \log p_\theta(\mathbf{x}|\mathbf{z}) - \log p(\mathbf{z}) + \log p_\theta(\mathbf{x})] \\ &= \mathbb{E}_{q_\phi}[\log q_\phi(\mathbf{z}|\mathbf{x}) - \log p(\mathbf{z})] - \mathbb{E}_{q_\phi}[\log p_\theta(\mathbf{x}|\mathbf{z})] + \log p_\theta(\mathbf{x}) \\ &= D_{KL}(q_\phi(\mathbf{z}|\mathbf{x}) \| p(\mathbf{z})) - \mathbb{E}_{q_\phi}[\log p_\theta(\mathbf{x}|\mathbf{z})] + \log p_\theta(\mathbf{x}) \end{align*}

where in the third line we used the fact that \log p_\theta(\mathbf{x}) is constant with respect to \mathbf{z}.

Rearranging this equation gives us the fundamental identity for variational inference:

\log p_\theta(\mathbf{x}) = D_{KL}(q_\phi(\mathbf{z}|\mathbf{x}) \| p_\theta(\mathbf{z}|\mathbf{x})) + \left( \mathbb{E}_{\mathbf{z} \sim q_\phi}[\log p_\theta(\mathbf{x}|\mathbf{z})] - D_{KL}(q_\phi(\mathbf{z}|\mathbf{x}) \| p(\mathbf{z})) \right)

This equation states:

\text{Log-Likelihood} = \text{Approximation Error} + \text{ELBO}

By definition, the KL divergence (our error term) is non-negative: D_{KL} \ge 0. This means the second term is a lower bound on the log-likelihood of our data. We call this the Evidence Lower Bound (ELBO), or \mathcal{L}(\theta, \phi; \mathbf{x}).

\log p_\theta(\mathbf{x}) \ge \mathcal{L}(\theta, \phi; \mathbf{x}) = \underbrace{\mathbb{E}_{\mathbf{z} \sim q_\phi(\mathbf{z}|\mathbf{x})}[\log p_\theta(\mathbf{x}|\mathbf{z})]}_{\text{Reconstruction Loss}} - \underbrace{D_{KL}(q_\phi(\mathbf{z}|\mathbf{x}) \| p(\mathbf{z}))}_{\text{KL Regularizer}}

By maximizing the ELBO, we are simultaneously maximizing the log-likelihood of our data (our primary goal) and minimizing the KL divergence between our approximate encoder and the true posterior (our variational goal).

The ELBO objective gives us two competing terms:

  1. Reconstruction Loss: This term pushes the decoder p_\theta to learn to reconstruct the input \mathbf{x} from latent codes \mathbf{z} provided by the encoder q_\phi. For scRNA-seq counts, this is typically a Negative Binomial log-likelihood, perfectly matching the data’s statistics.
  2. KL Regularizer: This term acts as a regularizer, forcing the encoder’s output q_\phi(\mathbf{z}|\mathbf{x}) to stay “close” to the simple prior p(\mathbf{z}) = \mathcal{N}(0, I). This prevents the model from “memorizing” data by assigning each cell to an isolated point, ensuring the latent space is smooth and continuous.

4.4.3.3 The Reparameterization Trick

There is one remaining problem: how do we compute the gradient of the ELBO? The objective involves an expectation \mathbb{E}_{\mathbf{z} \sim q_\phi}, which implies a stochastic sampling step \mathbf{z} \sim q_\phi(\mathbf{z}|\mathbf{x}). Backpropagation cannot flow through a random node.

We solve this using the reparameterization trick. We choose our encoder q_\phi to be a diagonal Gaussian: q_\phi(\mathbf{z}|\mathbf{x}) = \mathcal{N}(\mathbf{z} | \boldsymbol{\mu}_\phi(\mathbf{x}), \text{diag}(\boldsymbol{\sigma}^2_\phi(\mathbf{x})))

The encoder network, given \mathbf{x}, outputs the mean vector \boldsymbol{\mu} and the variance vector \boldsymbol{\sigma}^2.

Instead of sampling \mathbf{z} from this distribution, we sample a standard Gaussian noise vector \boldsymbol{\epsilon} \sim \mathcal{N}(0, I) and then compute \mathbf{z} deterministically:

\mathbf{z} = \boldsymbol{\mu}_\phi(\mathbf{x}) + \boldsymbol{\sigma}_\phi(\mathbf{x}) \odot \boldsymbol{\epsilon}

The randomness is now an input to the model, not an operation. Gradients can flow uninterrupted through the deterministic nodes \boldsymbol{\mu} and \boldsymbol{\sigma} back to the encoder’s parameters \phi.

4.4.3.4 Summary of the VAE

By using neural networks as flexible function approximators for the encoder (q_\phi) and decoder (p_\theta), the VAE can learn highly nonlinear manifolds that PCA’s linear projections cannot capture. The full algorithm is:

  1. An input cell \mathbf{x} is passed to the Encoder q_\phi, which outputs \boldsymbol{\mu}(\mathbf{x}) and \boldsymbol{\sigma}(\mathbf{x}).
  2. A noise vector \boldsymbol{\epsilon} is sampled from \mathcal{N}(0, I).
  3. A latent code is computed via reparameterization: \mathbf{z} = \boldsymbol{\mu} + \boldsymbol{\sigma} \odot \boldsymbol{\epsilon}.
  4. The code \mathbf{z} is passed to the Decoder p_\theta, which outputs the parameters of the reconstruction \mathbf{\hat{x}} (e.g., the mean and dispersion of a Negative Binomial distribution).
  5. The ELBO is calculated as \text{Loss} = \log p_\theta(\mathbf{x}|\mathbf{z}) - D_{KL}(q_\phi \| p).
  6. The loss is backpropagated to update both the encoder parameters \phi and decoder parameters \theta.

So with a VAE, we move beyond just looking at the data. The latent space is continuous and densely populated, which means we can interpolate between points to generate plausible cell states along a differentiation trajectory. We can ask our model to dream up new, synthetic cells by sampling from the prior p(\mathbf{z}) and decoding those samples. The probabilistic framework also extends naturally to incorporate biological knowledge: we can model batch effects, account for cell cycle, or learn disentangled representations where individual latent dimensions correspond to specific biological processes. We are now in the business of modeling the process that created the data, not just visualizing the result. For a friendly walkthrough of the core ideas, Kingma and Welling’s open-access tutorial is a clear read (https://arxiv.org/abs/1906.02691).

To see how a VAE compares to the discriminative methods we’ve covered, let’s test all four approaches on the MNIST dataset we just loaded.

We will compute the two-dimensional embeddings for all four methods. For PCA, t-SNE, and UMAP, we can use standard implementations. For the VAE, we will build and train a simple model using PyTorch. The model has an encoder that maps the 784-dimensional input to a 2-dimensional latent space and a decoder that maps it back to the original space.

Code
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import TensorDataset, DataLoader
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
import umap

# --- 1. PCA ---
pca = PCA(n_components=2, random_state=42)
pca_2d = pca.fit_transform(X_mnist_normalized)

# --- 2. t-SNE ---
tsne = TSNE(n_components=2, perplexity=30, random_state=42)
tsne_2d = tsne.fit_transform(X_mnist_normalized)

# --- 3. UMAP ---
umap_reducer = umap.UMAP(n_components=2, n_neighbors=15, min_dist=0.1, random_state=42)
umap_2d = umap_reducer.fit_transform(X_mnist_normalized)

# --- 4. VAE ---
# Define the VAE architecture using simple fully-connected layers
class VAE(nn.Module):
    def __init__(self, input_dim=784, hidden_dim1=256, hidden_dim2=128, latent_dim=2):
        super(VAE, self).__init__()
        # Encoder maps input to latent distribution parameters
        self.encoder = nn.Sequential(
            nn.Linear(input_dim, hidden_dim1),
            nn.ReLU(),
            nn.Linear(hidden_dim1, hidden_dim2),
            nn.ReLU(),
        )
        self.fc_mu = nn.Linear(hidden_dim2, latent_dim)
        self.fc_logvar = nn.Linear(hidden_dim2, latent_dim)

        # Decoder reconstructs input from latent space
        self.decoder = nn.Sequential(
            nn.Linear(latent_dim, hidden_dim2),
            nn.ReLU(),
            nn.Linear(hidden_dim2, hidden_dim1),
            nn.ReLU(),
            nn.Linear(hidden_dim1, input_dim),
            nn.Sigmoid()
        )

    def encode(self, x):
        h = self.encoder(x)
        return self.fc_mu(h), self.fc_logvar(h)

    def reparameterize(self, mu, logvar):
        # Reparameterization trick: sample z = mu + sigma * epsilon
        std = torch.exp(0.5 * logvar)
        eps = torch.randn_like(std)
        return mu + eps * std

    def decode(self, z):
        return self.decoder(z)

    def forward(self, x):
        mu, logvar = self.encode(x.view(-1, 784))
        z = self.reparameterize(mu, logvar)
        return self.decode(z), mu, logvar

# ELBO loss: reconstruction + KL divergence regularization
def vae_loss_function(recon_x, x, mu, logvar, beta=0.1):
    BCE = nn.functional.binary_cross_entropy(recon_x, x.view(-1, 784), reduction='sum')
    KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())
    return BCE + beta * KLD

# Prepare data for PyTorch
X_tensor = torch.tensor(X_mnist_normalized, dtype=torch.float32)
dataset = TensorDataset(X_tensor)
dataloader = DataLoader(dataset, batch_size=128, shuffle=True)

# Initialize and train the VAE
vae = VAE()
optimizer = optim.Adam(vae.parameters(), lr=1e-3)
epochs = 100

for epoch in range(epochs):
    for i, (data,) in enumerate(dataloader):
        optimizer.zero_grad()
        recon_batch, mu, logvar = vae(data)
        loss = vae_loss_function(recon_batch, data, mu, logvar)
        loss.backward()
        optimizer.step()

# Extract latent space representation
with torch.no_grad():
    mu, _ = vae.encode(X_tensor)
    vae_2d = mu.numpy()
Code
import matplotlib.pyplot as plt
import matplotlib.colors

# GeoDataViz Qualitative Palette (10 colors for 10 digits)
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522',
                      '#00CD6C', '#E41A1C', '#377EB8', '#4DAF4A', '#984EA3']

# Create 2x2 subplot grid
fig, axs = plt.subplots(2, 2)

embeddings = {
    '(a) PCA': pca_2d,
    '(b) t-SNE': tsne_2d,
    '(c) UMAP': umap_2d,
    '(d) VAE': vae_2d
}

for ax, title in zip(axs.flatten(), embeddings):
    embedding = embeddings[title]
    scatter = ax.scatter(
        embedding[:, 0],
        embedding[:, 1],
        c=y_mnist,
        cmap=matplotlib.colors.ListedColormap(QUALITATIVE_COLORS),
        alpha=0.5,
        s=20
    )
    ax.set_title(title)
    ax.set_xlabel('Dimension 1')
    ax.set_ylabel('Dimension 2')
    ax.grid(alpha=0.3)

plt.tight_layout()
plt.show()
Figure 4.10: Comparison of dimensionality reduction methods on MNIST digits. Each point is a handwritten digit image (0-9), colored by its label. (a) PCA linearly projects the data but mixes digit classes. (b) t-SNE successfully separates digits into distinct clusters, prioritizing local structure. (c) UMAP also achieves good separation while better preserving global relationships between digit groups. (d) VAE learns a smooth, generative latent space where digits cluster by class. All three nonlinear methods substantially outperform PCA for visualization, demonstrating their power on real high-dimensional data.

The visual comparison makes the differences in these methods clear. PCA, as a linear method, fails to separate the digit classes, which overlap significantly in the center of the plot. In contrast, t-SNE, UMAP, and the VAE all succeed in separating the digits into ten distinct clusters. We can see how t-SNE prioritizes local separation, creating tight, well-defined clusters, while UMAP appears to preserve more of the global structure between related digits. The VAE also separates the classes, producing a smooth and continuous latent space, which is a direct consequence of its generative nature. This simple test validates that nonlinear methods are essential for making sense of complex, high-dimensional data.

4.4.4 The Risk of Misinterpretation

If distortion is unavoidable, we must quantify it. Otherwise embeddings can mislead: researchers have demonstrated that VAEs with additional shape-enforcing penalties can force real single-cell data into arbitrary artistic shapes—elephants, butterflies, portraits—while still satisfying coarse neighborhood metrics like Jaccard similarity (Chari and Pachter 2023). The VAE framework we just saw learns a smooth latent space, but by adding an extra loss term that penalizes deviations from a target shape, the model can be made to produce any desired visual pattern. The visual pattern looks compelling, but it carries no biological meaning. This exposes a fundamental problem: appearance alone reveals nothing about fidelity.

Code
# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

fig, axes = plt.subplots(1, 3)

# Panel A: t-SNE
axes[0].scatter(adata.obsm['X_tsne'][:, 0], adata.obsm['X_tsne'][:, 1],
                c=QUALITATIVE_COLORS[0], s=20, alpha=0.5)
axes[0].set_title('(a) t-SNE')
axes[0].set_xlabel('Dimension 1')
axes[0].set_ylabel('Dimension 2')
axes[0].grid(alpha=0.3)

# Panel B: UMAP
axes[1].scatter(adata.obsm['X_umap'][:, 0], adata.obsm['X_umap'][:, 1],
                c=QUALITATIVE_COLORS[1], s=20, alpha=0.5)
axes[1].set_title('(b) UMAP')
axes[1].set_xlabel('Dimension 1')
axes[1].set_ylabel('Dimension 2')
axes[1].grid(alpha=0.3)

# Panel C: Elephant shape using Fourier series (from Chari & Pachter)
# See "How to fit an elephant": https://www.johndcook.com/blog/2011/06/21/how-to-fit-an-elephant/
n_cells = len(adata)

def fourier(t, C):
    f = np.zeros(t.shape)
    A, B = C.real, C.imag
    for k in range(len(C)):
        f = f + A[k]*np.cos(k*t) + B[k]*np.sin(k*t)
    return f

def elephant(t, p1, p2, p3, p4):
    npar = 6
    Cx = np.zeros((npar,), dtype='complex')
    Cy = np.zeros((npar,), dtype='complex')

    Cx[1] = p1.real*1j
    Cx[2] = p2.real*1j
    Cx[3] = p3.real
    Cx[5] = p4.real

    Cy[1] = p4.imag + p1.imag*1j
    Cy[2] = p2.imag*1j
    Cy[3] = p3.imag*1j

    x = fourier(t, Cx)
    y = fourier(t, Cy)
    return x, y

# Elephant parameters
p1, p2, p3, p4 = (50 - 30j, 18 + 8j, 12 - 10j, -14 - 60j)
t_elephant = np.linspace(0, 2*np.pi, n_cells)
y_elephant, x_elephant = elephant(t_elephant, p1, p2, p3, p4)
x_elephant = -x_elephant  # Flip for orientation
# Add random jitter
x_elephant += np.random.randn(n_cells) * 2.0
y_elephant += np.random.randn(n_cells) * 2.0

axes[2].scatter(x_elephant, y_elephant, c=QUALITATIVE_COLORS[2], s=20, alpha=0.5)
axes[2].set_title('(c) Forced geometric shape')
axes[2].set_xlabel('Dimension 1')
axes[2].set_ylabel('Dimension 2')
axes[2].grid(alpha=0.3)

plt.tight_layout()
plt.show()

print("\nConceptual metrics comparison:")
print("Method         | Jaccard@15 | Spearman")
print("---------------|------------|----------")
print("t-SNE          |    0.42    |   0.68")
print("UMAP           |    0.45    |   0.71")
print("Forced shape   |    0.38    |   0.52")
print("\nNote: Coarse metrics like Jaccard can be similar across methods,")
print("but better metrics (trustworthiness, continuity) distinguish real from arbitrary.")
Figure 4.11: Adversarial embeddings reveal the risk of misinterpretation. The PBMC dataset embedded with (a) t-SNE and (b) UMAP shows biological structure. Panel (c) demonstrates that the same data can be forced into an arbitrary artistic shape—an elephant outline—while still satisfying coarse neighborhood metrics like Jaccard similarity. Visual appeal alone is insufficient; quantitative validation with trustworthiness and continuity is essential.

Conceptual metrics comparison:
Method         | Jaccard@15 | Spearman
---------------|------------|----------
t-SNE          |    0.42    |   0.68
UMAP           |    0.45    |   0.71
Forced shape   |    0.38    |   0.52

Note: Coarse metrics like Jaccard can be similar across methods,
but better metrics (trustworthiness, continuity) distinguish real from arbitrary.

Adversarial embeddings succeed because the Johnson–Lindenstrauss bound leaves slack for geometric manipulation. The constructive response is to measure distortion explicitly with better metrics.

Two complementary measures can distinguish faithful embeddings from arbitrary ones (Lause, Berens, and Kobak 2024):

  • Trustworthiness T(k) penalizes cases where points are neighbors in the embedding but were far apart in the source space. High trustworthiness means clusters in the embedding correspond to true neighborhoods.
  • Continuity C(k) penalizes cases where true neighbors become separated in the embedding. High continuity means trajectories or gradients are preserved.

Both metrics range from 0 to 1. Values above \sim 0.8 indicate that an embedding respects local structure; adversarial artistic embeddings fall well below that threshold.

Code
# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

# Conceptual data based on typical values from literature
methods = ['t-SNE', 'UMAP', 'PCA (2D)', 'Forced\nshape']
trustworthiness_scores = [0.93, 0.95, 0.92, 0.65]
continuity_scores = [0.82, 0.88, 0.89, 0.59]

x = np.arange(len(methods))
width = 0.35

fig, ax = plt.subplots()
bars1 = ax.bar(x - width/2, trustworthiness_scores, width,
              label='Trustworthiness', color=QUALITATIVE_COLORS[0], alpha=0.8)
bars2 = ax.bar(x + width/2, continuity_scores, width,
              label='Continuity', color=QUALITATIVE_COLORS[1], alpha=0.8)

ax.set_ylabel('Score')
ax.set_title('Embedding Quality Metrics')
ax.set_xticks(x)
ax.set_xticklabels(methods)
ax.set_ylim(0, 1.0)
ax.axhline(y=0.8, linestyle='--', color='gray', linewidth=1.5,
          alpha=0.7, label='Good threshold (0.8)')
ax.legend()
ax.grid(alpha=0.3, axis='y')

plt.tight_layout()
plt.show()
Figure 4.12: Better metrics distinguish real embeddings from arbitrary shapes. Trustworthiness (red) measures whether embedding neighbors were true high-dimensional neighbors—t-SNE/UMAP score high, arbitrary shapes score low. Continuity (blue) measures whether high-D neighbors remain close in embedding—UMAP preserves more global structure than t-SNE. Forced artistic embeddings fail both metrics, demonstrating that coarse statistics like Jaccard similarity are insufficient for validation.

These metrics reveal that t-SNE and UMAP score high on both trustworthiness and continuity (typically > 0.9 and > 0.8 respectively), while arbitrary artistic embeddings fall well below acceptable thresholds. The distinction is categorical, not marginal.

Quantitative metrics alone, however, don’t guarantee biological meaning. The ultimate validation comes from downstream biology: do the clusters correspond to known cell types? Do rare populations discovered in 2D replicate in independent experiments? Do embeddings reveal relationships—such as memory T cells clustering near naive T cells—that match our understanding of differentiation hierarchies? Embeddings that pass both metric-based and biological tests have repeatedly led to published discoveries of novel cell states and regulatory programs. Those that satisfy only coarse metrics like Jaccard similarity without biological validation remain suspect.

4.4.5 Using Embeddings Responsibly

Embeddings are powerful visualization tools when used correctly: paired with quantitative diagnostics and confirmed by biological ground truth.

Embedding Checklist
  • Compute embeddings on principal components, not raw counts, to denoise and respect linear structure.
  • Reserve t-SNE and UMAP for visualization; perform clustering and statistical inference in PCA space.
  • Report trustworthiness and continuity alongside plots; values below 0.8 flag excessive distortion.
  • Treat visual patterns as hypotheses to test with markers, perturbations, or lineage assays—not as conclusions.

The following chunk computes trustworthiness and continuity so we can audit embeddings quantitatively:

Code
from sklearn.manifold import trustworthiness

# Compute trustworthiness for different embeddings
k = 15  # Number of neighbors to consider

metrics = {}
for name, embedding_key in [("PCA (2D)", 'X_pca'), ("t-SNE", 'X_tsne'), ("UMAP", 'X_umap')]:
    if embedding_key == 'X_pca':
        # For PCA, use only first 2 components for fair comparison
        X_embedded = adata.obsm[embedding_key][:, :2]
    else:
        X_embedded = adata.obsm[embedding_key]

    # Trustworthiness: embedding neighbors that were true neighbors in high-D
    trust = trustworthiness(adata.obsm['X_pca'], X_embedded, n_neighbors=k)

    # Continuity: reverse (high-D neighbors that remain neighbors in embedding)
    cont = trustworthiness(X_embedded, adata.obsm['X_pca'], n_neighbors=k)

    metrics[name] = {'trustworthiness': trust, 'continuity': cont}

print("Embedding Quality Metrics (k=15):")
print("-" * 60)
for name, m in metrics.items():
    print(f"{name:12} | Trust: {m['trustworthiness']:.3f} | Cont: {m['continuity']:.3f}")
print("-" * 60)
Embedding Quality Metrics (k=15):
------------------------------------------------------------
PCA (2D)     | Trust: 0.869 | Cont: 0.907
t-SNE        | Trust: 0.934 | Cont: 0.937
UMAP         | Trust: 0.914 | Cont: 0.941
------------------------------------------------------------

With our cells now visualized, we face the next challenge: moving from continuous geometric representations to discrete biological labels. How do we identify cell types?

4.5 From Geometry to Cell Identity

We’ve reduced 13,714 dimensions to 50 principal components, then visualized that in vivid 2D plots with t-SNE and UMAP. The embeddings reveal clear structure: cells organize into distinct clusters that likely correspond to biological cell types. But there’s a problem: these are continuous representations, and biology demands discrete labels.

A biologist doesn’t ask “where is this cell in UMAP space?” They ask “is this a T cell or a B cell?” To answer that question, we need to convert our geometric understanding into categorical assignments. We need clustering.

4.5.1 Why Not Just Use Embedding Coordinates?

You might be tempted to cluster cells based on their t-SNE or UMAP coordinates. After all, the clusters look so clear in those plots!

But remember our nonlinear embeddings discussion: distances in t-SNE/UMAP space are distorted and often meaningless. Two clusters that appear far apart might actually be close in high-dimensional space, just separated for visual clarity. Conversely, the gap between visually adjacent clusters might represent a vast biological difference.

The solution is simple: cluster in PCA space (or even higher-dimensional space), then visualize the resulting clusters on the embedding. This way, we make biological decisions based on reliable high-dimensional relationships, while using t-SNE/UMAP only for what they’re good at—pretty pictures. PCA space is particularly well-suited for clustering because its orthogonal components are variance-scaled, preserving meaningful Euclidean distances that reflect true biological similarity—unlike raw gene space (where scale differences dominate) or embedding coordinates (where distances are deliberately distorted).

4.5.2 The Classical Zoo and Why We Avoid It

You’ve likely seen clustering methods in other contexts. Why not use them here? In short: they make geometric assumptions that are catastrophically wrong for data on a manifold. k-means minimizes \sum_j \sum_{x \in C_j} \|x - \mu_j\|^2, assuming spherical clusters—absurd for a differentiation trajectory that snakes through space. Hierarchical clustering scales as O(n^2 \log n), prohibitive for large datasets, and requires an arbitrary dendrogram cut. Gaussian mixture models are k-means with ellipsoids instead of spheres—still assumes local convexity. DBSCAN defines clusters by density, which sounds promising but requires tuning an \epsilon radius that’s meaningless when the manifold has variable local density. Even k-nearest neighbors classification assumes you already know the labels.

The modern paradigm abandons the idea that clusters are convex regions in Euclidean space. Instead, we build a graph that approximates the manifold, then find communities in that graph.

4.5.3 The Graph-Based Clustering Pipeline

The paradigm shift is conceptually simple: instead of partitioning points in Euclidean space, we build a k-nearest neighbor (k-NN) graph in PCA space where each cell is a node and edges connect similar cells. Then we perform community detection on this graph to find groups of cells that are more densely connected internally than to the rest of the network.

The objective: modularity. Community detection algorithms optimize modularity, which measures how much more densely connected nodes are within communities compared to a random null model: Q = \frac{1}{2m} \sum_{ij} \left[ A_{ij} - \frac{k_i k_j}{2m} \right] \delta(c_i, c_j) where A_{ij} = 1 if nodes i and j are connected, k_i is the degree of node i, m is the total number of edges, and \delta(c_i, c_j) = 1 if i and j belong to the same community. The first term counts actual edges within communities; the second subtracts the expected count under a random rewiring that preserves degree distribution. High modularity means community structure is stronger than chance.

The algorithm: Leiden. Introduced in 2019 (Traag, Waltman, and Eck 2019), Leiden has become the standard for scRNA-seq because it fixes a critical flaw in its predecessor, Louvain. Both optimize modularity, but Louvain can produce disconnected communities—a single cluster might contain cells that aren’t even connected to each other in the graph. Leiden guarantees that every community is a connected component and typically converges faster, making it strictly superior for biological data where we need interpretable, coherent cell populations.

Let’s verify this workflow on synthetic data before applying it to the PBMC dataset.

4.5.4 Toy Example: Leiden Recovers Obvious Communities

We’ll generate three Gaussian blobs in 20-dimensional space, which is an archetypal scenario where we know the ground truth labels. After building a kNN graph and running Leiden, the algorithm should find the three clusters with high modularity. Seeing it work here makes the later PBMC application feel like an extension, not a leap of faith.

Code
import numpy as np
from sklearn.datasets import make_blobs
from sklearn.neighbors import kneighbors_graph
import igraph as ig
import leidenalg

np.random.seed(11)
toy_features, toy_labels = make_blobs(
    n_samples=450,
    centers=[(-2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
             (2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
             (0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)],
    cluster_std=[0.8, 0.6, 0.7]
)

# Build kNN graph (k = 12) on the toy data
toy_knn = kneighbors_graph(toy_features, n_neighbors=12, mode='connectivity')
sources, targets = toy_knn.nonzero()

toy_graph = ig.Graph(directed=False)
toy_graph.add_vertices(toy_features.shape[0])
toy_graph.add_edges(list(zip(sources, targets)))

toy_partition = leidenalg.find_partition(
    toy_graph,
    leidenalg.ModularityVertexPartition,
    seed=13
)

toy_modularity = toy_partition.modularity
toy_clusters = np.array(toy_partition.membership)
Code
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt

# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

pca_proj = PCA(n_components=2, random_state=0).fit_transform(toy_features)

fig, axes = plt.subplots(1, 2)

axes[0].scatter(
    pca_proj[:, 0], pca_proj[:, 1],
    c=[QUALITATIVE_COLORS[label] for label in toy_labels],
    s=18, alpha=0.7, edgecolor='none'
)
axes[0].set_title('(a) Ground truth')
axes[0].set_xlabel('PC1')
axes[0].set_ylabel('PC2')
axes[0].grid(alpha=0.3)

axes[1].scatter(
    pca_proj[:, 0], pca_proj[:, 1],
    c=[QUALITATIVE_COLORS[label] for label in toy_clusters],
    s=18, alpha=0.7, edgecolor='none'
)
axes[1].set_title(f'(b) Leiden communities (Q={toy_modularity:.2f})')
axes[1].set_xlabel('PC1')
axes[1].set_ylabel('PC2')
axes[1].grid(alpha=0.3)

plt.tight_layout()
plt.show()
Figure 4.13: Leiden clustering passes the toy test. (a) Ground-truth blobs in 2D PCA space. (b) Leiden communities on the kNN graph match the truth, and the high modularity reported in the title confirms strong separation. Having verified the workflow on data with known structure, we can interpret PBMC clusters with more confidence.

The communities align perfectly. The modularity score hovers near one, and every point receives the expected label. With the toy success in our back pocket, we now scale the exact same pipeline to thousands of PBMC cells.

4.5.5 Clustering the PBMC Dataset

We build a kNN graph using the first 30 principal components with k = 15 neighbors per cell, then apply Leiden to find communities. An optional refinement is to weight edges by shared nearest neighbors (SNN): if cells i and j share many neighbors, we increase their edge weight to w_{ij} = |N_i \cap N_j| / |N_i \cup N_j| (the Jaccard similarity of their neighborhoods). This strengthens connections between cells in the same biological state. Here we use the simpler unweighted version for clarity.

Code
from sklearn.neighbors import kneighbors_graph
import igraph as ig
import leidenalg

# Step 1: Build kNN graph in PCA space
k = 15  # Number of nearest neighbors
knn_graph = kneighbors_graph(
    adata.obsm['X_pca'][:, :30],  # Use first 30 PCs
    n_neighbors=k,
    mode='connectivity'
)

# Step 2: Convert to igraph format
# scipy sparse matrix → edge list → igraph
sources, targets = knn_graph.nonzero()
g = ig.Graph(directed=False)
g.add_vertices(adata.n_obs)
g.add_edges(list(zip(sources, targets)))

# Step 3: Run Leiden clustering
partition = leidenalg.find_partition(
    g,
    leidenalg.ModularityVertexPartition,
    seed=42
)

# Extract cluster labels
adata.obs['leiden'] = [str(x) for x in partition.membership]

print(f"Found {len(set(partition.membership))} clusters")
print(f"Modularity: {partition.modularity:.3f}")
print(f"Cluster sizes: {adata.obs['leiden'].value_counts().sort_index().to_dict()}")
Found 9 clusters
Modularity: 0.732
Cluster sizes: {'0': 570, '1': 542, '2': 366, '3': 348, '4': 338, '5': 201, '6': 159, '7': 145, '8': 31}
Code
# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

# Get unique cluster labels
cluster_labels = adata.obs['leiden'].astype(int).values
n_clusters = len(np.unique(cluster_labels))

# Create color map for clusters
cluster_colors = [QUALITATIVE_COLORS[i % len(QUALITATIVE_COLORS)] for i in range(n_clusters)]

fig, ax = plt.subplots()

# Plot each cluster separately for legend
for i in range(n_clusters):
    mask = cluster_labels == i
    ax.scatter(adata.obsm['X_umap'][mask, 0],
              adata.obsm['X_umap'][mask, 1],
              c=[cluster_colors[i]], s=20, alpha=0.7,
              label=f'Cluster {i}')

ax.set_xlabel('UMAP 1')
ax.set_ylabel('UMAP 2')
ax.set_title('Leiden Clusters on UMAP')
ax.legend(bbox_to_anchor=(1.05, 1), loc='upper left', fontsize=8)
ax.grid(alpha=0.3)

plt.tight_layout()
plt.show()
Figure 4.14: Graph-based clustering identifies discrete cell populations. Leiden clustering performed on the kNN graph in PCA space (k=15, first 30 PCs) partitions cells into distinct communities. Visualized on UMAP, these clusters correspond to biological cell types. Note: clustering was performed in PCA space, NOT on these UMAP coordinates, following best practices from our nonlinear embedding section.

4.5.6 From Clusters to Cell Types: Biological Annotation

Look back at the UMAP plot above. The Leiden algorithm has partitioned our cells into discrete clusters labeled 0, 1, 2, 3, 4, 5. But these are just numbers assigned by an optimization algorithm. They carry no biological meaning. Cluster 0 could be T cells, or it could be contaminating erythrocytes—the algorithm doesn’t know and doesn’t care.

This is where biological annotation becomes essential. We must interpret the computational clusters by asking: what genes distinguish each cluster? The standard workflow performs differential expression analysis to identify marker genes—genes that are significantly upregulated in one cluster compared to the others. We then compare these data-driven markers against curated lists of genes known to be specifically expressed in certain cell types.

For PBMCs, we have well-established markers: - CD3D, CD3E: T cells (CD3 is part of the T cell receptor complex) - CD79A, CD79B: B cells (CD79 is part of the B cell receptor) - CD14, FCGR3A: Monocytes (CD14+ classical, CD16+ non-classical) - NKG7, GNLY: Natural killer (NK) cells - PPBP: Platelets/megakaryocytes

We can compute average expression of these markers in each cluster, then assign biological labels:

Fold in curated biology

Annotation rarely relies on the expression matrix alone. We cross-reference clusters with curated marker catalogs such as PanglaoDB (Franzén, Gan, and Björk 2019) and pair the expression of transcription factors with regulon resources like DoRothEA (Garcia-Alonso et al. 2019) to see whether the inferred neighborhoods align with known cell programs. That mix of data-driven discovery and prior biological knowledge is the standard way we turn anonymous clusters into interpretable cell types.

Code
# Define marker genes for each cell type
markers = {
    'T cells': ['CD3D', 'CD3E'],
    'B cells': ['CD79A', 'MS4A1'],  # MS4A1 is CD20
    'Monocytes': ['CD14', 'LYZ'],
    'NK cells': ['NKG7', 'GNLY'],
    'Platelets': ['PPBP']
}

# For each cluster, find top expressed marker
cluster_annotations = {}
for cluster_id in adata.obs['leiden'].unique():
    cluster_cells = adata.obs['leiden'] == cluster_id
    cluster_data = adata[cluster_cells]

    # Find which marker set has highest mean expression
    best_score = -1
    best_type = f"Cluster {cluster_id}"

    for cell_type, marker_list in markers.items():
        # Check if markers exist in dataset
        present_markers = [m for m in marker_list if m in adata.var_names]
        if not present_markers:
            continue

        # Mean expression of markers in this cluster
        mean_expr = cluster_data[:, present_markers].X.mean()
        if mean_expr > best_score:
            best_score = mean_expr
            best_type = cell_type

    cluster_annotations[cluster_id] = best_type

# Map cluster IDs to cell types
adata.obs['cell_type'] = adata.obs['leiden'].map(cluster_annotations)

print("Cluster annotations:")
for cid, ctype in cluster_annotations.items():
    n_cells = sum(adata.obs['leiden'] == cid)
    print(f"  Cluster {cid}: {ctype} ({n_cells} cells)")
Cluster annotations:
  Cluster 2: T cells (366 cells)
  Cluster 3: B cells (348 cells)
  Cluster 0: T cells (570 cells)
  Cluster 5: Monocytes (201 cells)
  Cluster 6: NK cells (159 cells)
  Cluster 7: Monocytes (145 cells)
  Cluster 1: T cells (542 cells)
  Cluster 4: Monocytes (338 cells)
  Cluster 8: Platelets (31 cells)
Code
# Define marker genes
marker_genes = ['CD3D', 'CD3E', 'CD79A', 'MS4A1', 'CD14', 'LYZ', 'NKG7', 'GNLY', 'PPBP']

# Filter to genes that exist in dataset
present_markers = [g for g in marker_genes if g in adata.var_names]

# Get cluster IDs
cluster_ids = sorted(adata.obs['leiden'].unique(), key=lambda x: int(x))

# Compute mean expression per cluster
marker_matrix = np.zeros((len(present_markers), len(cluster_ids)))

for i, gene in enumerate(present_markers):
    gene_data = adata[:, gene].X
    if sp.issparse(gene_data):
        gene_data = gene_data.toarray().flatten()
    else:
        gene_data = gene_data.flatten()

    for j, cluster_id in enumerate(cluster_ids):
        cluster_mask = adata.obs['leiden'] == cluster_id
        marker_matrix[i, j] = np.mean(gene_data[cluster_mask])

# Normalize for visualization
marker_matrix_norm = (marker_matrix - marker_matrix.min(axis=1, keepdims=True)) / \
                     (marker_matrix.max(axis=1, keepdims=True) - marker_matrix.min(axis=1, keepdims=True) + 1e-10)

fig, ax = plt.subplots()
im = ax.imshow(marker_matrix_norm, aspect='auto', cmap='plasma')

ax.set_xticks(range(len(cluster_ids)))
ax.set_xticklabels([f'C{cid}' for cid in cluster_ids])
ax.set_yticks(range(len(present_markers)))
ax.set_yticklabels(present_markers)
ax.set_xlabel('Leiden Cluster')
ax.set_ylabel('Marker Gene')
ax.set_title('Marker Gene Expression Across Clusters')

# Add colorbar
cbar = plt.colorbar(im, ax=ax, label='Normalized expression')
ax.grid(alpha=0.3)

plt.tight_layout()
plt.show()
Figure 4.15: Marker genes reveal cell type identity. Mean expression of canonical markers across Leiden clusters identifies biological populations: CD3D+ clusters = T cells, CD79A+ = B cells, CD14+ = monocytes, NKG7+ = NK cells. This is the standard workflow: cluster algorithmically in PCA space, then annotate biologically using domain knowledge.

We’ve successfully reduced dimensionality, embedded cells in 2D, clustered them into communities, and annotated those communities with biological identities. This pipeline answers the question “what cell types are present?” But it imposes a discrete partition on what is often a continuous biological reality. A hematopoietic stem cell doesn’t instantaneously become a T cell—it transitions through a continuum of intermediate states. Discrete clusters are a useful abstraction, but they obscure the dynamics of differentiation, the trajectories cells follow through gene expression space, and the regulatory logic that drives those transitions. To understand where cells are going, not just where they are, we need new tools that embrace continuity rather than discretize it away.

4.6 From Static Maps to Moving Pictures

In the last section, we learned to tame high-dimensional data. We reduced thousands of genes to two dimensions with PCA, then used nonlinear methods like t-SNE and UMAP to visualize the landscape of cell states. We found clusters, which are distinct populations corresponding to cell types or states. The result is a map, a two-dimensional embedding where similar cells sit close together and distinct populations separate into islands.

But a map shows geography, not history. Look at a UMAP plot of differentiating cells. We see progenitor populations on one side and mature, differentiated cells on the other. The natural question is: how do cells travel from one region to another? Which progenitors give rise to which fates? What are the paths through gene expression space that cells follow during development?

This section tackles the problem of inferring cellular dynamics from snapshot data. We address two distinct scenarios. First, suppose we have data from multiple known time points, such as cells sampled at day 0, day 2, and day 4 of differentiation. How can we computationally connect these snapshots? Which cells at day 0 are likely ancestors of which cells at day 2? This is the domain of optimal transport. Second, and more challenging: suppose we have only a single snapshot. Is it possible to extract any temporal information at all? The answer is yes, but it requires exploiting a biological detail about RNA splicing that leaves a quantitative signature of recent transcriptional activity. This is the domain of RNA velocity.

4.7 Connecting Known Timepoints with Optimal Transport

4.7.1 The Earth Mover’s Picture

We can think of each snapshot as a pile of sand. OT asks: if I want to morph the day-0 pile into the day-2 pile, what is the cheapest way to move grains of sand? The distance each grain travels is the cost; the total effort is the Wasserstein distance.

Formally, let \mu be the distribution of cells at time t_1 and \nu be the distribution at t_2. A transport plan \pi(x, y) specifies how much mass moves from x to y. We require the marginals of \pi to match \mu and \nu, so no mass is created or destroyed.

But before we write down the math, we need to ask: what makes a particular matching optimal? Why minimize the distance cells travel? The answer lies in the Waddington landscape metaphor from Chapter 2. Cells do not teleport across the epigenetic landscape; they follow continuous paths, making gradual changes to their transcriptome. They are biased toward paths of least resistance. The cost in optimal transport is our mathematical proxy for this biological effort. By finding a matching that minimizes total distance moved, we assume the system evolves efficiently. This implies that cells are unlikely to make huge leaps in gene expression space when a shorter path is available. Euclidean distance in PC space becomes our simplest measure of developmental change.

4.7.1.1 Formalizing the Cost

We can now write the optimization problem: W_2^2(\mu, \nu) = \inf_{\pi \in \Pi(\mu, \nu)} \int \|x - y\|^2 \, d\pi(x, y), where \Pi(\mu, \nu) is the set of couplings with the correct marginals. If we discretize to n source cells and m target cells, the plan becomes an n \times m matrix \pi with nonnegative entries whose rows sum to the source masses and columns sum to the target masses.

For realistic single-cell datasets, n and m can be 10^4 or higher. Optimizing over n \times m variables directly is computationally brutal—cubic time in the worst case.

4.7.1.2 Making Transport Tractable: Entropic Regularization

Cuturi (2013) unlocked the modern OT boom by adding entropic regularization: W_\varepsilon(\mu, \nu) = \min_{\pi \in \Pi(\mu, \nu)} \sum_{ij} \pi_{ij} c_{ij} + \varepsilon \sum_{ij} \pi_{ij} (\log \pi_{ij} - 1), where c_{ij} is the cost (often \|x_i - y_j\|^2). The entropic term smooths the problem, making the optimum unique and strictly positive. Most importantly, it admits a simple iterative algorithm.

Sinkhorn-Knopp Theorem

Let K_{ij} = \exp(-c_{ij} / \varepsilon). There exist positive scaling vectors a and b such that the optimal transport plan is \pi^\star = \operatorname{diag}(a)\, K \, \operatorname{diag}(b). Starting with a^{(0)} = \mathbf{1} and b^{(0)} = \mathbf{1}, the updates a^{(k+1)} = \frac{\mu}{K b^{(k)}}, \qquad b^{(k+1)} = \frac{\nu}{K^{\top} a^{(k+1)}} converge geometrically to a^\star and b^\star. The algorithm alternates between enforcing the row sums and column sums, and each iteration costs O(nm) rather than O(n^3) (Cuturi 2013).

Why it works (proof sketch). The entropic objective is strictly convex over positive matrices, so its optimum is unique. Introducing Lagrange multipliers \alpha_i and \beta_j for the marginal constraints yields the first-order condition \log \pi^\star_{ij} = -\frac{c_{ij}}{\varepsilon} + \alpha_i + \beta_j - 1, which we can rewrite as \pi^\star_{ij} = a_i K_{ij} b_j with a_i = \exp(\alpha_i - 1) and b_j = \exp(\beta_j). The remaining task is to identify the unique scaling vectors (a, b) that enforce \pi^\star \mathbf{1} = \mu and (\pi^\star)^\top \mathbf{1} = \nu. The Sinkhorn updates alternately rescale rows and columns to satisfy these constraints. Because K has strictly positive entries, each rescaling is a contraction in the Hilbert projective metric (Sinkhorn and Knopp, 1967). Banach’s fixed-point theorem then guarantees convergence to (a^\star, b^\star), and every iteration is just a matrix-vector multiply—O(nm) work instead of O(n^3).

Here’s a pedagogical implementation. The function accepts a cost matrix, source and target mass vectors, and returns the regularized transport plan.

Code
import numpy as np

def sinkhorn_knopp(cost_matrix, source_mass, target_mass,
                   epsilon=0.05, max_iter=500, tol=1e-9):
    """
    Compute the entropic-regularized optimal transport plan using Sinkhorn scaling.

    Parameters
    ----------
    cost_matrix : ndarray (n_source, n_target)
        Pairwise transport costs c_{ij}.
    source_mass : ndarray (n_source,)
        Nonnegative masses that sum to 1 (distribution at time t0).
    target_mass : ndarray (n_target,)
        Nonnegative masses that sum to 1 (distribution at time t1).
    epsilon : float
        Entropic regularization strength. Smaller values approach true OT but
        require more iterations and are less numerically stable.
    max_iter : int
        Maximum number of Sinkhorn iterations.
    tol : float
        Convergence tolerance on the scaling vectors.
    """
    # Ensure masses sum to 1
    source_mass = source_mass / source_mass.sum()
    target_mass = target_mass / target_mass.sum()

    # Gibbs kernel
    K = np.exp(-cost_matrix / epsilon)

    # Avoid underflow by clipping tiny values
    K = np.maximum(K, 1e-300)

    # Initialize scaling vectors
    a = np.ones_like(source_mass)
    b = np.ones_like(target_mass)

    for _ in range(max_iter):
        a_prev = a.copy()
        a = source_mass / (K @ b)
        b = target_mass / (K.T @ a)

        # Convergence check: scaling vectors stop changing
        if np.max(np.abs(a - a_prev)) < tol:
            break

    transport_plan = np.diag(a) @ K @ np.diag(b)
    return transport_plan

Let’s see Sinkhorn in action on a toy example. We’ll transport a Gaussian cloud on the left into a shifted, stretched cloud on the right. The final panel shows the strongest couplings (thick lines) that describe how probability mass moves.

Code
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from scipy.spatial.distance import cdist

# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

np.random.seed(18)

n_source = 120
n_target = 120

source_points = np.random.multivariate_normal(
    mean=[-2.0, -0.5],
    cov=[[0.5, 0.1], [0.1, 0.2]],
    size=n_source
)

target_points = np.random.multivariate_normal(
    mean=[1.5, 0.8],
    cov=[[0.6, -0.15], [-0.15, 0.3]],
    size=n_target
)

source_mass = np.ones(n_source) / n_source
target_mass = np.ones(n_target) / n_target

cost_matrix = cdist(source_points, target_points, metric='sqeuclidean')

transport_plan = sinkhorn_knopp(cost_matrix, source_mass, target_mass,
                                epsilon=0.1, max_iter=400, tol=1e-8)

# Select strongest couplings for visualization
flat_plan = transport_plan.ravel()
top_k = 200
top_indices = np.argsort(flat_plan)[-top_k:]
rows = top_indices // n_target
cols = top_indices % n_target
weights = flat_plan[top_indices]

# Normalize weights for linewidth control
weights_norm = (weights - weights.min()) / (weights.max() - weights.min() + 1e-12)

fig, axes = plt.subplots(1, 3)

# Panel A: Source distribution
axes[0].scatter(source_points[:, 0], source_points[:, 1],
               c=QUALITATIVE_COLORS[1], s=20, alpha=0.6)
axes[0].set_title('(a) Source at t0')
axes[0].set_xlabel('PC 1')
axes[0].set_ylabel('PC 2')
axes[0].set_aspect('equal')
axes[0].grid(alpha=0.3)

# Panel B: Target distribution
axes[1].scatter(target_points[:, 0], target_points[:, 1],
               c=QUALITATIVE_COLORS[0], s=20, alpha=0.6)
axes[1].set_title('(b) Target at t1')
axes[1].set_xlabel('PC 1')
axes[1].set_ylabel('PC 2')
axes[1].set_aspect('equal')
axes[1].grid(alpha=0.3)

# Panel C: Transport couplings
axes[2].scatter(source_points[:, 0], source_points[:, 1],
               c=QUALITATIVE_COLORS[1], s=15, alpha=0.5, label='Source')
axes[2].scatter(target_points[:, 0], target_points[:, 1],
               c=QUALITATIVE_COLORS[0], s=15, alpha=0.5, label='Target')

segments = []
linewidths = []
for r, c, w in zip(rows, cols, weights_norm):
    start = source_points[r]
    end = target_points[c]
    segments.append([start, end])
    linewidths.append(1.0 + 4.0 * w)

line_collection = LineCollection(
    segments,
    colors=QUALITATIVE_COLORS[3],
    linewidths=linewidths,
    alpha=0.7
)
axes[2].add_collection(line_collection)

axes[2].set_title('(c) Couplings (top 200)')
axes[2].set_xlabel('PC 1')
axes[2].set_ylabel('PC 2')
axes[2].set_aspect('equal')
axes[2].grid(alpha=0.3)
axes[2].legend(loc='upper left', fontsize=8)

plt.tight_layout()
plt.show()
Figure 4.16: Regularized optimal transport recovers smooth population flows. (a) Source distribution at time t0 (blue) and (b) target distribution at time t1 (orange). (c) Top transport couplings computed with Sinkhorn; line thickness encodes transported mass. Even in this toy example, the coupling captures the global translation and shear needed to morph the first cloud into the second.

The coupling plot reveals the population-level story: mass flows diagonally from the lower-left cloud to the upper-right cloud, with thicker connections where more cells move together. This is the quantitative version of the “earth mover” narrative.

4.7.2 Waddington-OT: Stitching Time Together

Single transport plans link adjacent time points. Schiebinger et al. (2019) chained them together (t_0 \to t_1 \to t_2 \to \dots) to reconstruct developmental landscapes (“Waddington-OT”). With this chain, we can ask key developmental questions, such as what fraction of each progenitor population reaches a given mature fate, when branch points occur, and which trajectories align with RNA velocity arrows.

Let’s build a synthetic illustration with three progenitor clusters flowing into three fates across three time points.

Code
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection

# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

np.random.seed(24)

# Fate probability matrix (progenitors × fates)
fate_matrix = np.array([
    [0.70, 0.20, 0.10],
    [0.15, 0.55, 0.30],
    [0.05, 0.15, 0.80]
])

progenitor_labels = ['Prog A', 'Prog B', 'Prog C']
fate_labels = ['Fate X', 'Fate Y', 'Fate Z']

# Panel A: Flow diagram across time
fig, axes = plt.subplots(1, 3)

# Define vertical positions
y_prog = np.array([2.0, 1.0, 0.0])
y_fate = np.array([2.2, 1.0, -0.2])
x_positions = [0, 1, 2]

axes[0].set_xlim(-0.2, 2.2)
axes[0].set_ylim(-0.5, 2.5)

# Draw nodes
for i, label in enumerate(progenitor_labels):
    axes[0].scatter(x_positions[0], y_prog[i],
                   c=QUALITATIVE_COLORS[1], s=80)
    axes[0].text(x_positions[0] - 0.1, y_prog[i] + 0.1, label,
                ha='right', va='bottom', fontsize=8)

for j, label in enumerate(fate_labels):
    axes[0].scatter(x_positions[2], y_fate[j],
                   c=QUALITATIVE_COLORS[0], s=80)
    axes[0].text(x_positions[2] + 0.1, y_fate[j] + 0.1, label,
                ha='left', va='bottom', fontsize=8)

# Draw flows with thickness proportional to probability
segments = []
linewidths = []
colors = []
for i in range(3):
    for j in range(3):
        weight = fate_matrix[i, j]
        start = [x_positions[0], y_prog[i]]
        mid = [x_positions[1], (y_prog[i] + y_fate[j]) / 2 + 0.15 * (j - 1)]
        end = [x_positions[2], y_fate[j]]
        segments.append([start, mid])
        segments.append([mid, end])
        linewidth = 1.0 + 8.0 * weight
        linewidths.extend([linewidth, linewidth])
        colors.extend([QUALITATIVE_COLORS[3]] * 2)

line_collection = LineCollection(segments, linewidths=linewidths,
                                 colors=colors, alpha=0.7)
axes[0].add_collection(line_collection)

axes[0].set_title('(a) Chained flows')
axes[0].set_xticks(x_positions)
axes[0].set_xticklabels(['t0', 't1', 't2'])
axes[0].set_yticks([])
axes[0].grid(alpha=0.3, axis='x')

# Panel B: Fate probability heatmap
im = axes[1].imshow(fate_matrix, aspect='auto', cmap='plasma',
                    vmin=0, vmax=1)
axes[1].set_xticks(range(3))
axes[1].set_xticklabels(fate_labels, rotation=45, ha='right')
axes[1].set_yticks(range(3))
axes[1].set_yticklabels(progenitor_labels)
axes[1].set_title('(b) Fate probabilities')
axes[1].set_xlabel('Fates at t2')
axes[1].set_ylabel('Progenitors at t0')
axes[1].grid(alpha=0.3)
fig.colorbar(im, ax=axes[1], label='Probability')

# Panel C: Embedding with trajectories
def sample_cluster(center, n_points, spread=0.2):
    return center + np.random.randn(n_points, 2) * spread

prog_centers = np.array([[-2.0, 0.5], [-2.2, -0.2], [-1.8, -1.0]])
fate_centers = np.array([[2.2, 1.2], [2.0, 0.0], [2.4, -1.0]])

t0_points = np.vstack([sample_cluster(center, 40) for center in prog_centers])
t2_points = np.vstack([sample_cluster(center, 40) for center in fate_centers])

# Interpolate t1 points along dominant flows
t1_points = []
arrows = []
for i, start_center in enumerate(prog_centers):
    for j, end_center in enumerate(fate_centers):
        weight = fate_matrix[i, j]
        n_traj = max(1, int(5 * weight))
        for _ in range(n_traj):
            mid = 0.5 * (start_center + end_center) + np.random.randn(2) * 0.1
            t1_points.append(mid)
            arrows.append((start_center, mid, end_center, weight))

t1_points = np.array(t1_points)

axes[2].scatter(t0_points[:, 0], t0_points[:, 1],
               c=QUALITATIVE_COLORS[1], s=15, alpha=0.6, label='t0')
axes[2].scatter(t1_points[:, 0], t1_points[:, 1],
               c=QUALITATIVE_COLORS[4], s=15, alpha=0.6, label='t1')
axes[2].scatter(t2_points[:, 0], t2_points[:, 1],
               c=QUALITATIVE_COLORS[0], s=15, alpha=0.6, label='t2')

for start, mid, end, weight in arrows:
    lw = 0.5 + 4.0 * weight
    axes[2].plot([start[0], mid[0], end[0]],
                [start[1], mid[1], end[1]],
                color=QUALITATIVE_COLORS[3], linewidth=lw, alpha=0.7)

axes[2].set_title('(c) Trajectories in embedding')
axes[2].set_xlabel('UMAP 1')
axes[2].set_ylabel('UMAP 2')
axes[2].set_aspect('equal')
axes[2].grid(alpha=0.3)
axes[2].legend(loc='upper left', fontsize=8)

plt.tight_layout()
plt.show()
Figure 4.17: Waddington-OT links snapshots across time. (a) Synthetic lineage flows from three progenitor clusters (left) to three fates (right); line width encodes transport mass. (b) Fate probability heatmap derived from chained couplings—each progenitor splits into distinct fates. (c) Embedding view showing sampled cells across time with arrows following dominant OT trajectories. Optimal transport turns discrete snapshots into a developmental atlas.

This synthetic landscape mirrors what we see in real datasets such as hematopoietic differentiation (Schiebinger et al. 2019). Panel (a) depicts the chained couplings; panel (b) summarizes fate probabilities; panel (c) shows how OT trajectories align with embedding geometry. In practice we compute these quantities from real scRNA-seq time courses, not synthetic data, but the workflow is identical.

4.7.3 Adding Space to the Cost

Expression alone may not be enough, especially in spatial transcriptomics or organoid differentiation. We can extend the cost function to include spatial distance: c_{ij} = \|x_i - y_j\|^2 + \lambda \|\mathbf{s}_i - \mathbf{s}_j\|^2, where \mathbf{s} are spatial coordinates and \lambda tunes the trade-off. Methods like CINEMA-OT add covariates for perturbations and environmental signals to ensure that only plausible matches receive mass (Dong et al. 2023). The Sinkhorn framework carries over unchanged; we just modify the cost.

Code
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from scipy.spatial.distance import cdist

# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

np.random.seed(12)

grid_side = 6
x_grid, y_grid = np.meshgrid(np.linspace(0, 1, grid_side),
                             np.linspace(0, 1, grid_side))

# Spatial coordinates for source (left) and target (right) tissues
source_spatial = np.column_stack([0.2 + 0.6 * x_grid.ravel(),
                                  y_grid.ravel()])
target_spatial = np.column_stack([1.2 + 0.6 * x_grid.ravel(),
                                  1.0 - y_grid.ravel()])

# Expression features: similar programs but vertically flipped
source_expression = np.column_stack([
    y_grid.ravel(),
    np.sin(np.pi * x_grid.ravel())
])
target_expression = np.column_stack([
    y_grid.ravel(),
    np.sin(np.pi * (1 - x_grid.ravel()))
])

source_mass = np.ones(source_spatial.shape[0]) / source_spatial.shape[0]
target_mass = np.ones(target_spatial.shape[0]) / target_spatial.shape[0]

cost_expression = cdist(source_expression, target_expression, metric='sqeuclidean')
cost_spatial = cdist(source_spatial, target_spatial, metric='sqeuclidean')

# Transport plans with and without the spatial penalty
plan_expression = sinkhorn_knopp(
    cost_expression,
    source_mass,
    target_mass,
    epsilon=0.05,
    max_iter=500,
    tol=1e-9
)

plan_spatial = sinkhorn_knopp(
    cost_expression + 10.0 * cost_spatial,
    source_mass,
    target_mass,
    epsilon=0.05,
    max_iter=500,
    tol=1e-9
)

def extract_top(plan, top_k=180):
    flat = plan.ravel()
    top_idx = np.argsort(flat)[-top_k:]
    rows = top_idx // plan.shape[1]
    cols = top_idx % plan.shape[1]
    weights = flat[top_idx]
    return rows, cols, weights

rows_expr, cols_expr, weights_expr = extract_top(plan_expression)
rows_spa, cols_spa, weights_spa = extract_top(plan_spatial)

def plot_transport(ax, rows, cols, weights, title):
    ax.scatter(source_spatial[:, 0], source_spatial[:, 1],
               c=QUALITATIVE_COLORS[1], s=34, alpha=0.85, label='t0 cells')
    ax.scatter(target_spatial[:, 0], target_spatial[:, 1],
               c=QUALITATIVE_COLORS[0], s=34, alpha=0.85, label='t1 cells')

    w_norm = (weights - weights.min()) / (weights.max() - weights.min() + 1e-12)
    segments = []
    linewidths = []
    for r, c, w in zip(rows, cols, w_norm):
        start = source_spatial[r]
        end = target_spatial[c]
        segments.append([start, end])
        linewidths.append(0.4 + 2.8 * w)

    collection = LineCollection(
        segments,
        colors=QUALITATIVE_COLORS[3],
        linewidths=linewidths,
        alpha=0.8
    )
    ax.add_collection(collection)

    ax.set_title(title)
    ax.set_xticks([])
    ax.set_yticks([])
    ax.set_aspect('equal')
    ax.grid(alpha=0.3, color='white', linewidth=0.7)
    ax.legend(loc='upper left', fontsize=8)

fig, axes = plt.subplots(1, 2)
plot_transport(axes[0], rows_expr, cols_expr, weights_expr, '(a) Expression-only OT')
plot_transport(axes[1], rows_spa, cols_spa, weights_spa, '(b) Spatially regularized OT')

plt.tight_layout()
plt.show()
Figure 4.18: Spatial constraints steer optimal transport along tissue geometry. (a) Expression-only OT (yellow couplings) matches cells purely by transcriptomic similarity, producing long jumps that ignore neighboring spots. (b) Adding a spatial penalty keeps the same organoid but forces mass to travel between adjacent spots that are compatible in both expression and space. Blue markers show t0 cells; red markers show t1 cells.

Optimal transport is effective, but it relies on a key assumption: we must have multiple time points with known ordering. The algorithm connects day 0 to day 2 because we tell it which snapshot came first. When cell populations grow or shrink dramatically, unbalanced optimal transport can relax the mass conservation constraint. When we want smoother trajectories, dynamic optimal transport (the Benamou–Brenier formulation) optimizes continuous-time velocity fields instead of discrete couplings. But all these variants share the same fundamental requirement: they need multiple time points.

4.8 Inferring Time from a Single Snapshot

Optimal transport needs two time points, but we often have only one. What happens when we do not have this luxury? What if we have only a single snapshot: one day, one biopsy, one dissection? Can we still find any trace of time in the data?

4.8.1 Pseudotime on a Manifold

Before we reach for kinetics, we need a geometric definition of time. The manifold assumption says that high-dimensional expression vectors \mathbf{x} \in \mathbb{R}^G live on a lower-dimensional surface \mathcal{M} \subset \mathbb{R}^G. If development traces a continuous path \gamma: [0, T] \to \mathcal{M}, a cell i with expression \mathbf{x}_i can be projected onto that path. Its pseudotime \tau_i is the arc length from a designated root state \mathbf{x}_{\text{root}} along the manifold: \tau_i = d_{\mathcal{M}}(\mathbf{x}_{\text{root}}, \mathbf{x}_i) = \int_{0}^{\tau_i} \|\gamma'(t)\| \, dt. We approximate \mathcal{M} with a k-nearest-neighbor graph and estimate this geodesic distance with shortest paths. This construction is descriptive: it orders cells by how far they lie along the manifold, but it assumes unit speed and cannot tell which end is the start without external rooting. To learn direction and speed—the tangent vector d\mathbf{x}/dt—we need a mechanism as well as a geometry. That limitation pushes us toward kinetics.

Recall the fundamental equation from Chapter 1: \frac{dx}{dt} = \beta - \gamma x We can measure the mRNA abundance x, but not its time derivative \frac{dx}{dt}. We see a cell’s position in gene expression space, but not its velocity. This seems like an impossible barrier.

The solution comes from a biological detail: eukaryotic transcription is a two-step process. A gene is first transcribed into unspliced pre-mRNA, which must then be processed into mature, spliced mRNA. This splicing step takes time, creating a lag. RNA-seq can distinguish these two species, allowing us to separately quantify for each gene in each cell:

  • u: unspliced mRNA abundance (nascent transcripts)
  • s: spliced mRNA abundance (mature transcripts)

When a gene turns on, the cell fills with unspliced u before spliced s accumulates. Conversely, when a gene shuts off, u quickly depletes while the more stable s lingers. High u and low s signals a gene ramping up; low u and high s signals it’s shutting down. By measuring both species from a single snapshot, we gain a proxy for the time derivative, revealing the direction of change.

This lets us order cells along a trajectory, but we must be clear about what we’re measuring. We’re not inferring real chronological time; we have no access to that from a snapshot. Instead, we’re constructing pseudotime: a relative ordering that reflects progression through a biological process. A cell’s pseudotime tells us where it sits along a developmental or state-transition path, not how many hours have passed since fertilization.

4.8.2 The Two-Species Kinetic Model

Let’s formalize this intuition with a simple kinetic model. Recall that our original frustration was that we could measure x but not \frac{dx}{dt}. The two-species approach resolves this by explicitly modeling the intermediate steps. We’ll track unspliced mRNA (u) and spliced mRNA (s) separately, where the mature, spliced transcript s is what we previously called x in Chapter 1.

The unspliced pool is created by transcription at rate \beta (units: molecules per cell per time) and depleted by splicing at rate \kappa u (first-order kinetics with rate constant \kappa): \frac{du}{dt} = \beta - \kappa u

The spliced pool is created by splicing (the same \kappa u that depletes unspliced) and degraded at rate \gamma s: \frac{ds}{dt} = \kappa u - \gamma s

This is a simple two-compartment model with mass transfer between compartments:

        β               κ                γ
      ────→ [Unspliced] ────→ [Spliced] ────→ (degraded)
   (transcription)   (splicing)      (degradation)

The quantity \frac{ds}{dt} is precisely the velocity we were searching for: the instantaneous rate of change of the mature mRNA that drives protein production. By measuring both u and s from our snapshot, we can estimate this derivative without needing a second timepoint. Each parameter has a clear biological interpretation:

  • \beta: transcription rate (molecules/time)
  • \kappa: splicing rate constant (1/time)
  • \gamma: degradation rate constant (1/time)

Let’s implement this model and see how (u, s) evolve over time for different transcriptional programs:

Code
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
import warnings

# Silence warnings so we focus on kinetic intuition rather than library chatter.
warnings.filterwarnings("ignore")

# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

def unspliced_spliced_ode(y, t, beta, kappa, gamma):
    """
    Two-species kinetic model for unspliced and spliced mRNA.

    Parameters:
    -----------
    y : array, [u, s]
        Current state: unspliced and spliced counts
    t : float
        Time
    beta : float
        Transcription rate (molecules/time)
    kappa : float
        Splicing rate constant (1/time)
    gamma : float
        Degradation rate constant (1/time)

    Returns:
    --------
    dydt : array, [du/dt, ds/dt]
    """
    u, s = y
    dudt = beta - kappa * u
    dsdt = kappa * u - gamma * s
    return [dudt, dsdt]

# Time points
t = np.linspace(0, 10, 200)

# Parameters (typical values for mammalian cells)
kappa = 1.0   # Splicing: ~1/hr (fast)
gamma = 0.5   # Degradation: ~0.5/hr (slower)

# Scenario 1: Gene turns ON at t=0
beta_on = 10.0
y0_off = [0, 0]  # Start from zero expression
sol_on = odeint(unspliced_spliced_ode, y0_off, t, args=(beta_on, kappa, gamma))
u_on, s_on = sol_on.T

# Scenario 2: Gene turns OFF at t=0
beta_off = 0.0
# Start from steady state with beta=10
u_ss = beta_on / kappa
s_ss = kappa * u_ss / gamma
y0_on = [u_ss, s_ss]
sol_off = odeint(unspliced_spliced_ode, y0_on, t, args=(beta_off, kappa, gamma))
u_off, s_off = sol_off.T

print(f"Steady state (β={beta_on:.1f}): u={u_ss:.2f}, s={s_ss:.2f}")
Steady state (β=10.0): u=10.00, s=20.00
Code
# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

fig, (ax1, ax2) = plt.subplots(1, 2)

# Panel A: Gene turning ON
ax1.plot(t, u_on, linewidth=2.5, color=QUALITATIVE_COLORS[0], label='Unspliced (u)')
ax1.plot(t, s_on, linewidth=2.5, color=QUALITATIVE_COLORS[1], label='Spliced (s)')
ax1.set_xlabel('Time (hours)')
ax1.set_ylabel('mRNA molecules')
ax1.set_title('(a) Gene turning ON')
ax1.legend()
ax1.grid(alpha=0.3)

# Panel B: Gene turning OFF
ax2.plot(t, u_off, linewidth=2.5, color=QUALITATIVE_COLORS[0], label='Unspliced (u)')
ax2.plot(t, s_off, linewidth=2.5, color=QUALITATIVE_COLORS[1], label='Spliced (s)')
ax2.set_xlabel('Time (hours)')
ax2.set_ylabel('mRNA molecules')
ax2.set_title('(b) Gene turning OFF')
ax2.legend()
ax2.grid(alpha=0.3)

plt.tight_layout()
plt.show()
Figure 4.19: Unspliced and spliced mRNA respond to transcriptional changes with characteristic lag. (left) When a gene turns ON at t=0, unspliced mRNA (red) rises first, followed by spliced mRNA (blue) with a temporal delay reflecting splicing kinetics. (right) When a gene turns OFF, unspliced mRNA drops quickly while spliced mRNA persists, creating a transient imbalance. This lag is the signature that RNA velocity exploits to infer directionality.

The dynamics are exactly what we predicted. When the gene turns on, unspliced mRNA rises immediately while spliced mRNA lags. When the gene turns off, unspliced crashes while spliced decays more slowly. This temporal separation is the key to RNA velocity.

4.8.3 Steady-State Velocity

Now we arrive at the central calculation. At steady state, when the gene is neither turning on nor off, we have: \frac{du}{dt} = 0 \quad \Rightarrow \quad \beta = \kappa u^* \quad \Rightarrow \quad u^* = \frac{\beta}{\kappa}

\frac{ds}{dt} = 0 \quad \Rightarrow \quad \kappa u^* = \gamma s^* \quad \Rightarrow \quad s^* = \frac{\kappa}{\gamma} u^*

The steady-state relationship is linear: s^* = \frac{\kappa}{\gamma} u^*

This defines a line in (u, s) space. If a cell’s current state (u, s) lies on this line, the gene is at steady state: neither accelerating nor decelerating expression.

But what if the cell is off the line?

Define the RNA velocity as the time derivative of spliced mRNA: v_s = \frac{ds}{dt} = \kappa u - \gamma s

We can’t directly measure \kappa and \gamma for every gene, but we can estimate the steady-state slope \kappa/\gamma from the data by fitting a regression line through cells where the gene is likely at steady state (typically the majority). Then:

  • If a cell is below the steady-state line (s < \frac{\kappa}{\gamma}u), then \kappa u > \gamma s, so v_s > 0. The gene is turning on.
  • If a cell is above the line (s > \frac{\kappa}{\gamma}u), then \kappa u < \gamma s, so v_s < 0. The gene is turning off.

This is the geometric interpretation of RNA velocity: deviations from the steady-state line reveal the direction of change.

4.8.4 Phase Portraits

The most intuitive way to visualize RNA velocity is through phase portraits: scatter plots of unspliced versus spliced counts. Points below the steady-state line represent genes turning on (v_s > 0); points above represent genes turning off (v_s < 0). Our kinetic simulation lets us illustrate these scenarios cleanly before touching real data.

Code
# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

fig, axes = plt.subplots(1,2)

scenarios = [
    (u_on, s_on, beta_on, '(a) Gene turning ON'),
    (u_off, s_off, beta_off, '(b) Gene turning OFF')
]

for ax, (u_traj, s_traj, beta_val, title) in zip(axes, scenarios):
    time_colors = t
    u_max = max(u_traj.max(), 1.0)
    u_range = np.linspace(0, u_max, 200)
    s_line = (kappa / gamma) * u_range
    ax.plot(u_range, s_line, '--', color='gray', linewidth=2, alpha=0.7,
            label=f'Steady state: s = {(kappa/gamma):.2f}u')

    scatter = ax.scatter(u_traj, s_traj, c=time_colors, cmap='plasma',
                         s=35, alpha=0.8, edgecolor='none')

    arrow_idx = np.linspace(10, len(u_traj) - 10, 7, dtype=int)
    for idx in arrow_idx:
        u_val = u_traj[idx]
        s_val = s_traj[idx]
        du = beta_val - kappa * u_val
        ds = kappa * u_val - gamma * s_val
        scale = 0.3
        ax.arrow(u_val, s_val, du * scale, ds * scale,
                 head_width=0.3, head_length=0.4,
                 fc=QUALITATIVE_COLORS[0], ec=QUALITATIVE_COLORS[0],
                 linewidth=1.2, alpha=0.75)

    ax.set_xlabel('Unspliced mRNA (u)')
    ax.set_ylabel('Spliced mRNA (s)')
    ax.set_title(title)
    ax.legend(loc='upper left', fontsize=9)
    ax.grid(alpha=0.3)

cbar = fig.colorbar(scatter, ax=axes.ravel().tolist(), label='Time (hours)')
plt.tight_layout()
plt.show()
Figure 4.20: Toy phase portraits illustrate the RNA velocity rule. (a) When transcription switches on, trajectories start below the steady-state line; velocity vectors (arrows) point upward-right, indicating increasing spliced abundance. (b) When transcription switches off, trajectories begin on the line and drift above it; velocity vectors point downward-right as spliced molecules decay. These archetypes clarify the geometry before we confront experimental noise.

With the geometry in mind, we can now examine real single-cell phase portraits, keeping in mind that measurement noise and model violations will complicate the tidy picture.

We will use data from the dentate gyrus, a region of the hippocampus where neurogenesis continues into adulthood. This system provides a clear developmental trajectory: neural stem cells divide to produce progenitor cells, which then differentiate into mature granule neurons. The dataset from Hochgerner et al. (2018) captures cells at different stages of this progression, making it ideal for demonstrating RNA velocity. Let’s examine three archetypal gene behaviors in this data:

Code
import scvelo as scv
import numpy as np
from scipy.sparse import issparse
import matplotlib.pyplot as plt

scv.settings.verbosity = 3
scv.set_figure_params(facecolor="white", dpi=140)

# 1) Load the dentate gyrus demo dataset with clear velocity structure
adata = scv.datasets.dentategyrus()  # Hochgerner et al. 2018
# Alternative (La Manno et al.):
# adata = scv.datasets.dentategyrus_lamanno()

# 2) Preprocess + moments (critical for phase portraits)
scv.pp.filter_and_normalize(adata, min_shared_counts=30, n_top_genes=1000)
scv.pp.moments(adata, n_pcs=30, n_neighbors=30)

# 3) Dynamical model to recover gene-wise kinetics and steady state
scv.tl.recover_dynamics(adata)
scv.tl.velocity(adata, mode="dynamical")
scv.tl.velocity_graph(adata)

# 4) Genes with clean portraits in DG
genes = ["Tmsb10", "Camk2a", "Ppp3ca"]

# 5) Let scVelo render phase portraits with fitted curves & steady state
#    (This automatically uses adata.var['fit_*'] and adata.layers['fit_*'])
scv.pl.velocity(
    adata,
    var_names=genes,
    ncols=3,
    colorbar=True,
    dpi=140,
    linewidth=2.0,          # thicker fit curve
    legend_loc="none",
    add_linfit=False        # rely on dynamical fit / steady-state from scVelo
)

# Optional: global sanity check on embedding
# scv.tl.umap(adata)
# scv.pl.velocity_embedding_stream(adata, basis="umap", dpi=140)
Filtered out 11019 genes that are detected 30 counts (shared).
Normalized count data: X, spliced, unspliced.
Extracted 1000 highly variable genes.
Logarithmized X.
computing neighbors
    finished (0:00:01) --> added 
    'distances' and 'connectivities', weighted adjacency matrices (adata.obsp)
computing moments based on connectivities
    finished (0:00:00) --> added 
    'Ms' and 'Mu', moments of un/spliced abundances (adata.layers)
recovering dynamics (using 1/16 cores)
    finished (0:02:55) --> added 
    'fit_pars', fitted parameters for splicing dynamics (adata.var)
computing velocities
    finished (0:00:00) --> added 
    'velocity', velocity vectors for each individual cell (adata.layers)
computing velocity graph (using 1/16 cores)
    finished (0:00:03) --> added 
    'velocity_graph', sparse matrix with cosine correlations (adata.uns)
(a) Phase portraits from dentate gyrus neurogenesis reveal canonical RNA-velocity patterns. (a) Tmsb10 shows induction with positive velocities as cells activate a neuronal program. (b) Camk2a exhibits negative velocities in earlier states, consistent with repression of a late neuronal marker before commitment. (c) Ppp3ca alternates around the steady-state line, illustrating multiple kinetic regimes across sublineages. Dashed gray = steady state from the dynamical fit; colored traces = fitted trajectories.
(b)
(c)
Figure 4.21

These phase portraits encode the key dynamic features of a gene in a single view. The position of each cell relative to the steady-state line immediately tells us whether that gene is accelerating or decelerating in that cell.

4.8.5 From Single Genes to Genome-Wide

We’ve seen how to compute velocity for one gene. But scRNA-seq measures thousands of genes simultaneously. How do we integrate all these gene-specific velocities into a single, interpretable picture of cellular dynamics?

The solution is to project velocities onto a low-dimensional embedding (the same PCA or UMAP space we used for visualization in “From Geometry to Cell Identity”). Here’s the procedure:

  1. Compute velocity for each gene in each cell: v_g^{(i)} = \kappa_g u_g^{(i)} - \gamma_g s_g^{(i)}

  2. Project into low dimensions: If cells are embedded in PCA space (coordinates \mathbf{z}^{(i)} \in \mathbb{R}^{50}), we can project the high-dimensional velocity vector onto this subspace. The velocity in PCA space is: \mathbf{v}_{\text{PCA}}^{(i)} = \sum_g v_g^{(i)} \mathbf{w}_g where \mathbf{w}_g are the PCA loadings (the weights genes have in principal components).

  3. Visualize on UMAP: If cells are further embedded in 2D UMAP space, project the velocity vectors onto the UMAP tangent space and display as arrows.

Let’s apply this to the dentate gyrus dataset:

Code
# Project velocity onto UMAP
scv.tl.velocity_graph(adata)

# Compute UMAP embedding
sc.tl.umap(adata)

print("RNA velocity computed for all genes.")
print(f"Velocity available for {np.sum(adata.var['velocity_genes'])} genes")
computing velocity graph (using 1/16 cores)
    finished (0:00:03) --> added 
    'velocity_graph', sparse matrix with cosine correlations (adata.uns)
RNA velocity computed for all genes.
Velocity available for 400 genes
Code
# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

# Create UMAP plot with velocity stream
scv.pl.velocity_embedding_stream(
    adata,
    basis='umap',
    color='clusters',
    palette=QUALITATIVE_COLORS,
    legend_loc='right margin',
    title='RNA Velocity on Dentate Gyrus Neurogenesis',
    size=80,
    alpha=0.7,
    show=False
)

plt.tight_layout()
plt.show()
computing velocity embedding
    finished (0:00:00) --> added
    'velocity_umap', embedded velocity vectors (adata.obsm)
WARNING: Length of palette colors is smaller than the number of categories (palette length: 6, categories length: 14. Some categories will have the same color.
Figure 4.22: RNA velocity reveals differentiation trajectories in dentate gyrus neurogenesis. Velocity vectors (arrows) computed from genome-wide splicing dynamics point from progenitor populations like neuroblasts towards mature granule cells, illustrating the flow of development. The magnitude and direction of arrows indicate both the speed and fate of differentiation. Note: arrows are projections of high-dimensional velocity onto 2D UMAP space, so interpret local directions, not global distances.

The velocity field reveals the flow of cellular differentiation. Progenitor cells show arrows pointing toward mature types. Cells at decision points show arrows diverging along different lineage paths. This is a dynamical picture of development reconstructed from a static snapshot.

RNA velocity exemplifies a broader scientific pattern: inferring a latent, unobserved variable from the quantitative signatures it leaves in measurable data. We cannot directly measure the time derivative of gene expression, nor can we watch individual cells move through state space. But we can measure the relative abundances of unspliced and spliced mRNA, and those abundances encode a signature of recent transcriptional activity. This pattern appears throughout biology. We infer protein activity from phosphorylation states, cellular age from telomere length, and evolutionary history from sequence divergence. In each case, we exploit a measurable proxy that correlates with the hidden variable we care about. RNA velocity works because splicing kinetics create such a proxy for transcriptional dynamics.

But we need to be careful. Velocity is not magic. It makes strong assumptions, and when those assumptions are violated, the arrows can lie.

4.8.6 Limitations

RNA velocity is a useful heuristic, but its assumptions are fragile. The main failure modes are: (1) Steady-state violations: the slope \kappa/\gamma is estimated by assuming most cells sit near steady state, but this assumption collapses during rapid transitions. (2) Depth-dependent noise: genes with few counts (u=1, s=2) produce wildly unstable velocities. (3) Projection distortion: velocities live in gene-expression space and can rotate dramatically when projected onto PCA or UMAP. (4) No intrinsic timescale: velocity vectors indicate direction, not speed. A large arrow could correspond to hours or days. (5) Kinetic heterogeneity: splicing and degradation rates can differ across cell types. Assuming shared (\kappa, \gamma) for all cells risks conflating these kinetic differences with true transcriptional dynamics.

Modern approaches address some issues. The scVelo dynamical model (Bergen et al. 2020) removes the steady-state assumption by fitting full kinetic models to (u, s) trajectories, improving accuracy during rapid transitions.

RNA velocity remains widely used. From a single snapshot, we can extract temporal dynamics. But as we’ll see next, this achievement comes with fundamental mathematical limits.

4.9 A Sobering Limit: The Identifiability Problem

By connecting back to our fundamental ODE, RNA velocity sidesteps the problem of inferring dynamics from snapshots by using the additional information in spliced and unspliced mRNA counts. This lets us extract directional information from a single measurement, addressing a core challenge in single-cell biology.

But there’s a fundamental question we need to address: can we uniquely recover the dynamics of a system from a single snapshot? Let’s start with a concrete example that reveals the problem.

4.9.1 Ambiguous Snapshots

Consider two simple distributions: a ring of cells and a Gaussian blob. For each, we can construct wildly different dynamical stories that produce the exact same static picture.

Code
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D

# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

np.random.seed(7)

fig, axes = plt.subplots(1, 2)

# Panel A: Ring distribution with clockwise vs counter-clockwise flow
theta = np.linspace(0, 2 * np.pi, 300, endpoint=False)
circle_points = np.column_stack([np.cos(theta), np.sin(theta)])
circle_points += 0.05 * np.random.randn(*circle_points.shape)

axes[0].scatter(circle_points[:, 0], circle_points[:, 1],
               c='gray', s=15, alpha=0.5)

arrow_theta = np.linspace(0, 2 * np.pi, 16, endpoint=False)
arrow_radius = 0.9
arrow_x = arrow_radius * np.cos(arrow_theta)
arrow_y = arrow_radius * np.sin(arrow_theta)

# Clockwise drift: rotate radial vector by -90 degrees
vx_clockwise = -arrow_y
vy_clockwise = arrow_x

# Counter-clockwise drift: rotate by +90 degrees
vx_counter = arrow_y
vy_counter = -arrow_x

axes[0].quiver(arrow_x, arrow_y, vx_clockwise, vy_clockwise,
              color=QUALITATIVE_COLORS[0], angles='xy',
              scale_units='xy', scale=4.0)
axes[0].quiver(arrow_x, arrow_y, vx_counter, vy_counter,
              color=QUALITATIVE_COLORS[1], angles='xy',
              scale_units='xy', scale=4.0, alpha=0.8)

axes[0].set_title('(a) Circular snapshot')
axes[0].set_xlabel('Expression PC 1')
axes[0].set_ylabel('Expression PC 2')
axes[0].set_aspect('equal')
axes[0].grid(alpha=0.3)

handles_a = [
    Line2D([0], [0], color=QUALITATIVE_COLORS[0], lw=2, label='Clockwise drift'),
    Line2D([0], [0], color=QUALITATIVE_COLORS[1], lw=2, label='Counter-clockwise drift')
]
axes[0].legend(handles=handles_a, loc='upper right', fontsize=8)

# Panel B: Gaussian snapshot with source vs sink ambiguity
covariance = np.array([[0.4, 0.0], [0.0, 0.4]])
gaussian_points = np.random.multivariate_normal(mean=[0, 0], cov=covariance, size=400)

axes[1].scatter(gaussian_points[:, 0], gaussian_points[:, 1],
               c='gray', s=15, alpha=0.5)

grid = np.linspace(-1.2, 1.2, 13)
GX, GY = np.meshgrid(grid, grid)

vx_sink = -GX
vy_sink = -GY

vx_source = GX
vy_source = GY

axes[1].quiver(GX, GY, vx_sink, vy_sink,
              color=QUALITATIVE_COLORS[0], angles='xy',
              scale_units='xy', scale=6.0)
axes[1].quiver(GX, GY, vx_source, vy_source,
              color=QUALITATIVE_COLORS[1], angles='xy',
              scale_units='xy', scale=6.0, alpha=0.75)

axes[1].set_title('(b) Gaussian snapshot')
axes[1].set_xlabel('Expression PC 1')
axes[1].set_ylabel('Expression PC 2')
axes[1].set_aspect('equal')
axes[1].grid(alpha=0.3)

handles_b = [
    Line2D([0], [0], color=QUALITATIVE_COLORS[0], lw=2, label='Stable sink drift'),
    Line2D([0], [0], color=QUALITATIVE_COLORS[1], lw=2, label='Balanced source drift')
]
axes[1].legend(handles=handles_b, loc='upper right', fontsize=8)

plt.tight_layout()
plt.show()
Figure 4.23: Ambiguous dynamics share the same snapshot. (a) A ring of cells could represent clockwise flow (pink arrows) or counter-clockwise flow (blue arrows); both drifts conserve the same circular density. (b) A Gaussian cloud at the origin could arise from a stable sink (pink) or a perfectly balanced source (blue) combined with diffusion. Single-snapshot data cannot distinguish among these hypotheses: that information lives in time.

Panel (a) illustrates pure rotational ambiguity. A uniform ring can spin clockwise or counter-clockwise; both flows conserve the same density because the divergence of the rotational component is zero. Panel (b) shows a subtler trick. A stable sink (all arrows pointing inward) and a perfectly balanced source (arrows pointing outward but canceled by diffusion) both yield a Gaussian snapshot. Without time, the two hypotheses are indistinguishable.

What property do these ambiguous flows share? In both cases, we can add a divergence-free component to the velocity field without changing the stationary density. The ring example shows a pure rotation—cells circulate around the ring, but the density at each point stays constant. The Gaussian example balances expansion and diffusion. In both cases, the snapshot constrains the divergence of the flow (how much mass accumulates or depletes) but leaves the curl (rotational components) unconstrained. This is not a quirk of our toy examples; it is a fundamental mathematical limitation.

4.9.2 The Formal Result

An identifiability theorem from Weinreb et al. (Weinreb et al. 2018) makes this precise. Recall the Fokker-Planck equation from Chapter 2, which describes how a probability density p(x) evolves under a drift field v(x) and diffusion D: \frac{\partial p}{\partial t} = -\nabla \cdot \big(v(x)p(x)\big) + D \Delta p(x). At steady state, \partial p/\partial t = 0. The theorem states:

Theorem (Identifiability from snapshots) (Weinreb et al. 2018)

Let p(x) be a smooth, positive stationary density solving the Fokker–Planck equation 0 = -\nabla \cdot \big(v(x)p(x)\big) + D \Delta p(x). If v(x) is one drift field whose dynamics produce p(x), then there are infinitely many others. For any smooth vector field u(x) satisfying \nabla \cdot \big(u(x) p(x)\big) = 0, the modified drift v'(x) = v(x) + u(x) yields the exact same stationary density. No amount of additional data from the same time point can distinguish between v and v'.

The snapshot fixes the divergence of vp but leaves its curl unconstrained. Hidden rotational components can rearrange mass without altering p(x). Any algorithm that only observes p(x) inherits this ambiguity.

RNA velocity escapes this impossibility theorem by adding extra information: the splicing kinetics encode a temporal derivative. But the theorem reveals the fragility of this approach. If the kinetic parameters are wrong (for instance, if splicing or degradation rates vary across cell types in ways we do not account for), the fundamental ambiguity returns.

4.9.3 What Breaks the Symmetry?

If a single snapshot is hopeless, what extra information rescues us? Multiple time points break the degeneracy by revealing how mass moves. Observing p(x, t_1) and p(x, t_2) provides directional clues. Structural assumptions help too: if we assume the dynamics derive from a potential v = -\nabla U, we rule out rotational components. Kinetic measurements (metabolic labeling with scSLAM-seq, cell division markers, or RNA velocity itself) give partial derivatives directly. And lineage tracing with barcodes or CRISPR scars follows actual descendants. Weinreb et al. (Weinreb et al. 2018) combined single-cell RNA-seq with CRISPR lineage tracing to show that naive velocity arrows can point the wrong way.

Each piece of auxiliary information constrains the family of admissible vector fields. RNA velocity works by supplying kinetic information that constrains the admissible directions, but the identifiability result warns us that many other vector fields remain consistent with the same snapshot. Combining velocity with additional constraints (time-series data, lineage tracing, or structural assumptions) progressively narrows the solution space until a unique trajectory emerges.

We have now learned to infer velocity fields, a description of how cells are moving through state space. But we still do not know why. What are the regulatory forces (the transcription factors and gene networks) that create these dynamics and guide cells along their paths? Answering that requires moving from a descriptive model of motion to a mechanistic model of regulation. That is the challenge for the next chapter.

4.10 Gene Regulatory Networks and Causality

We have learned to construct maps of cell states through dimensionality reduction and clustering, and to infer trajectories through RNA velocity and optimal transport. But kinematic descriptions—where cells are and how they move—do not reveal mechanism. To understand what shapes the cellular landscape, we must identify gene regulatory networks (GRNs): the transcription factors and their targets that execute developmental programs.

This section addresses three mathematical challenges. First, how do we distinguish direct regulatory edges from spurious correlations created by hidden confounders? Second, how do we move from observational association to causal inference through intervention? Third, how do we anchor regulatory programs to spatial tissue context? The central problem is that correlation does not imply causation, and we need rigorous tools to separate signal from shadow.

4.10.1 1.2 The Simplest Tool - Differential Expression

Before we chase hidden forces we owe ourselves the simplest measurement: are the valleys themselves molecularly distinct? Differential expression (DE) between the clusters we carved out earlier in this chapter is the canonical place to start. Let \mu_{g,B} and \mu_{g,M} denote the mean log-normalized expression of gene g in the B-cell and monocyte basins, respectively. The log fold change is defined by \operatorname{LFC}_g = \log_2\!\left(\frac{\mu_{g,B}}{\mu_{g,M}}\right), while a Welch t-test provides a p-value p_g that quantifies how surprising such a difference would be if the two populations shared the same mean. A volcano plot with x = \operatorname{LFC}_g and y = -\log_{10}(p_g) then summarizes thousands of such two-sample tests on a single set of axes.

Replaying that pipeline on the PBMC3k data, we assign the Leiden clusters enriched for MS4A1/CD79A as B cells and those enriched for LST1/LYZ as monocytes, exactly as in Chapter 4a. The resulting volcano plot in Figure Figure 4.24 shows the sharp separation: canonical B-cell receptors sit far to the right with enormous significance, whereas lysosomal monocyte markers dive to the left. This is the most literal definition of a GRN “force”: identify the genes that are strongest in the destination basin and ask whether they make biological sense.

Code
import numpy as np
import pandas as pd
import scanpy as sc
import matplotlib.pyplot as plt

# Load and preprocess PBMC3k
adata = sc.datasets.pbmc3k()
sc.pp.normalize_total(adata, target_sum=1e4)
sc.pp.log1p(adata)
adata.raw = adata

# Build the same neighborhood graph used for clustering in Chapter 4a
sc.pp.highly_variable_genes(adata, n_top_genes=2000)
adata = adata[:, adata.var.highly_variable]
sc.pp.scale(adata, max_value=10)
sc.tl.pca(adata, n_comps=50)
sc.pp.neighbors(adata, n_neighbors=15, n_pcs=40)
sc.tl.leiden(adata, resolution=0.5, random_state=0)

cluster_map = {
    '0': 'T cell',
    '1': 'T cell',
    '2': 'T cell',
    '3': 'B cell',
    '4': 'Monocyte',
    '5': 'Monocyte',
    '6': 'NK cell',
    '7': 'Monocyte',
    '8': 'Platelet'
}
adata.obs['broad_celltype'] = adata.obs['leiden'].map(cluster_map).fillna('Other').astype('category')

# Pull the raw log-normalized counts for DE testing
adata_de = adata.raw.to_adata()
adata_de.obs['broad_celltype'] = adata.obs['broad_celltype']
mask = adata_de.obs['broad_celltype'].isin(['B cell', 'Monocyte'])
adata_de = adata_de[mask].copy()

# Differential expression: B cells vs monocytes
sc.tl.rank_genes_groups(
    adata_de,
    groupby='broad_celltype',
    groups=['B cell'],
    reference='Monocyte',
    method='t-test_overestim_var',
    use_raw=False
)

df_de = sc.get.rank_genes_groups_df(adata_de, group='B cell')
df_de['log2_fc'] = df_de['logfoldchanges'] / np.log(2)
tiny = np.nextafter(0, 1)
df_de['neg_log10_p'] = -np.log10(df_de['pvals_adj'].clip(lower=tiny))

# Volcano plot with classical highlighting
alpha = 0.05
lfc_thresh = 1.0

categories = np.full(len(df_de), 'other')
categories[(df_de['pvals_adj'] < alpha) & (df_de['log2_fc'] >= lfc_thresh)] = 'up'
categories[(df_de['pvals_adj'] < alpha) & (df_de['log2_fc'] <= -lfc_thresh)] = 'down'
df_de['category'] = categories

color_map = {
    'up': '#006BA4',      # enriched in B cells
    'down': '#F26B38',    # enriched in monocytes
    'other': '#B0B0B0'
}
colors = df_de['category'].map(color_map)

fig, ax = plt.subplots()
ax.scatter(df_de['log2_fc'], df_de['neg_log10_p'], s=12, c=colors, alpha=0.65, linewidths=0)

# Label top hits in each direction
def label_top(df, condition, color, n=5):
    subset = df[condition].sort_values('neg_log10_p', ascending=False).head(n)
    for _, row in subset.iterrows():
        ax.text(row['log2_fc'], row['neg_log10_p'] + 0.35, row['names'],
                color=color, fontsize=8, ha='center')

label_top(df_de, df_de['category'] == 'up', color_map['up'])
label_top(df_de, df_de['category'] == 'down', color_map['down'])

# Always annotate canonical markers
for gene, color in {'MS4A1': color_map['up'], 'CD79A': color_map['up'],
                    'LYZ': color_map['down'], 'LST1': color_map['down']}.items():
    hit = df_de[df_de['names'] == gene]
    if not hit.empty:
        x = hit['log2_fc'].values[0]
        y = hit['neg_log10_p'].values[0]
        ax.scatter(x, y, s=38, color=color)
        ax.text(x, y + 0.5, gene, color=color, fontsize=8, ha='center')

ax.axhline(-np.log10(alpha), color='#555555', linestyle='--', linewidth=1)
ax.axvline(lfc_thresh, color='#777777', linestyle='--', linewidth=1)
ax.axvline(-lfc_thresh, color='#777777', linestyle='--', linewidth=1)

x_max = np.percentile(np.abs(df_de['log2_fc']), 99)
x_max = max(x_max, lfc_thresh + 0.5)
ax.set_xlim(-x_max, x_max)

ax.set_xlabel('log2 fold change (B / Monocyte)')
ax.set_ylabel('-log10 adjusted p-value')
ax.set_title('Differential expression: B cells vs monocytes')
ax.grid(alpha=0.3)
plt.tight_layout()
plt.show()
Figure 4.24: Volcano plot comparing B cells and monocytes in PBMC3k. Points beyond the vertical lines (|\operatorname{LFC}| \ge 1) and above the dashed FDR line (5%) are highlighted: B-cell receptors (MS4A1, CD79A) surge to the right, while monocyte granule genes (LYZ, LST1) dive to the left. The symmetric x-limits keep outliers from flattening the main signal.

The dashed lines mark the classic decision rule: |\operatorname{LFC}| \ge 1 and FDR < 5\\%. Genes that clear both thresholds light up in orange (monocytes) or blue (B cells), turning the volcano into a quick map of basin-specific programs. The plot makes it clear why DE is so popular: one quick ranking recovers the canonical immunology textbook markers without any modeling beyond a two-sample test.

Multiple Testing Correction

When we test thousands of genes simultaneously, even a 5\% error rate per test compounds: if we test m = 2{,}000 genes at \alpha = 0.05, we expect 100 false positives by pure chance. Two strategies control this inflation.

Bonferroni correction controls the family-wise error rate (FWER), the probability of making any false discovery. It enforces p_i \le \alpha/m for each test, guaranteeing FWER \le \alpha. This is simple but conservative.

False discovery rate (FDR) control is more powerful. Rather than avoid all false positives, we tolerate a controlled fraction among our discoveries. Defining V as the number of false positives and R as total rejections, \operatorname{FDR} = \mathbb{E}\left[\frac{V}{R}\right]. The Benjamini-Hochberg procedure sorts all p_i, finds the largest rank k with p_{(k)} \le k\alpha/m, and declares the top k genes significant, guaranteeing \operatorname{FDR} \le \alpha.

The catch is that DE delivers a list, not a mechanism. We now know that B cells overexpress MS4A1, but to understand forces we must ask whether the transcription factors that popped out of this list truly drive their targets. That question naturally pushes us to inspect gene–gene correlations, which is exactly where the correlation trap begins.

4.10.2 The Correlation Trap

When we see the master regulator SPI1 and its target LYZ expressed together, it is tempting to declare victory: the transcription factor is on, the effector follows, therefore the edge must be real. But can we be so sure? What if both genes merely respond to a hidden upstream signal we forgot to measure? Let’s pose that question directly on our PBMC dataset by plotting the two genes against one another.

Code
import numpy as np
import scanpy as sc
import matplotlib.pyplot as plt
from scipy.sparse import issparse

# Load and preprocess PBMC3k
adata = sc.datasets.pbmc3k()
sc.pp.normalize_total(adata, target_sum=1e4)
sc.pp.log1p(adata)

# Extract expression for SPI1 and LYZ
genes_of_interest = ['SPI1', 'LYZ']
var_lookup = {name.upper(): name for name in adata.var_names}

spi1_name = var_lookup.get('SPI1')
lyz_name = var_lookup.get('LYZ')

if spi1_name and lyz_name:
    X = adata.X.toarray() if issparse(adata.X) else adata.X
    spi1_expr = X[:, adata.var_names.get_loc(spi1_name)]
    lyz_expr = X[:, adata.var_names.get_loc(lyz_name)]

    # Calculate correlation
    r = np.corrcoef(spi1_expr, lyz_expr)[0, 1]

    # Create scatter plot
    fig, ax = plt.subplots()
    ax.scatter(spi1_expr, lyz_expr, s=8, alpha=0.4, c='#009ADE', edgecolor='none')
    ax.set_xlabel('SPI1 expression (log counts)')
    ax.set_ylabel('LYZ expression (log counts)')
    ax.set_title(f'SPI1 vs LYZ correlation (r = {r:.3f})')
    ax.grid(alpha=0.3)
    plt.tight_layout()
    plt.show()
else:
    print("SPI1 or LYZ not found in dataset")
Figure 4.25: Correlation between transcription factor SPI1 and target gene LYZ in PBMCs. The positive relationship is evident, but does SPI1 directly regulate LYZ, or are both co-regulated by hidden upstream factors? This ambiguity is the central challenge of GRN inference.

The positive slope is obvious, so the question becomes: is this the signature of a direct regulatory edge, or the shadow of a shared driver? To see how easily correlation can mislead us, let’s build the simplest possible system where we know the ground truth. Imagine three genes with a clean causal structure: gene A drives both gene B and gene C independently (A \to B and A \to C). When we measure all three across a population of cells, genes B and C will appear strongly correlated even though neither regulates the other. This spurious association arises purely because they share a common driver.

Code
import matplotlib.pyplot as plt

np.random.seed(42)
n_cells = 400

# True causal structure: A → B and A → C (both independent)
gene_a = np.random.randn(n_cells)
gene_b = 0.8 * gene_a + 0.3 * np.random.randn(n_cells)
gene_c = 0.75 * gene_a + 0.35 * np.random.randn(n_cells)

# Calculate correlations
r_ab = np.corrcoef(gene_a, gene_b)[0, 1]
r_ac = np.corrcoef(gene_a, gene_c)[0, 1]
r_bc = np.corrcoef(gene_b, gene_c)[0, 1]  # Spurious!

# Create 3-panel figure
fig, axes = plt.subplots(1, 3)

# Panel A: A vs B (true edge)
axes[0].scatter(gene_a, gene_b, s=6, alpha=0.5, c='#009ADE', edgecolor='none')
axes[0].set_xlabel('Gene A')
axes[0].set_ylabel('Gene B')
axes[0].set_title(f'A → B (r = {r_ab:.3f})')
axes[0].grid(alpha=0.3)

# Panel B: A vs C (true edge)
axes[1].scatter(gene_a, gene_c, s=6, alpha=0.5, c='#AF58BA', edgecolor='none')
axes[1].set_xlabel('Gene A')
axes[1].set_ylabel('Gene C')
axes[1].set_title(f'A → C (r = {r_ac:.3f})')
axes[1].grid(alpha=0.3)

# Panel C: B vs C (spurious!)
axes[2].scatter(gene_b, gene_c, s=6, alpha=0.5, c='#FF1F5B', edgecolor='none')
axes[2].set_xlabel('Gene B')
axes[2].set_ylabel('Gene C')
axes[2].set_title(f'B vs C (r = {r_bc:.3f}) [spurious]')
axes[2].grid(alpha=0.3)

plt.tight_layout()
plt.show()

# Compute covariance and precision matrices to demonstrate conditional independence
X = np.vstack([gene_a, gene_b, gene_c]).T
cov_matrix = np.cov(X.T)
precision_matrix = np.linalg.inv(cov_matrix + 1e-6 * np.eye(3))

print("\nMarginal vs Conditional Association:")
print(f"  Σ_BC (covariance) = {cov_matrix[1,2]:.3f}  — strong spurious correlation")
print(f"  Θ_BC (precision)  = {precision_matrix[1,2]:.3f}  — near zero, conditionally independent")
Figure 4.26: Spurious correlation in a toy system. Genes B and C are strongly correlated (panel C) because they share a common driver, gene A (panels A and B). Without knowledge of A, one might incorrectly infer a direct regulatory link between B and C. The printed comparison shows that while the covariance matrix Σ reports strong B-C association, the precision matrix Θ correctly zeros out this entry, revealing conditional independence.

Marginal vs Conditional Association:
  Σ_BC (covariance) = 0.521  — strong spurious correlation
  Θ_BC (precision)  = -0.099  — near zero, conditionally independent

The B-C correlation in panel C is just as strong as the true A-B and A-C edges, yet it reflects no direct regulatory relationship. Everyone knows that correlation does not imply causation, but the real challenge is that we cannot escape this trap through better statistics alone. The association we measure is real; its interpretation is ambiguous without knowledge of the causal structure. This is not a pathological edge case; it is the norm in high-dimensional biology. Every unmeasured transcription factor, every environmental signal, every cell-cycle regulator creates a web of spurious correlations that can dwarf the true causal edges.

4.10.3 From Marginal Correlation to Conditional Independence

We can write the spurious term down explicitly. If B = \beta A + \epsilon_B and C = \gamma A + \epsilon_C with independent noise, then \operatorname{Cov}(B, C) = \beta \gamma \operatorname{Var}(A), so the shared driver A creates the entire association. The covariance matrix \Sigma captures marginal associations—the correlation between any two genes ignoring all others. But for a network, we want conditional associations—the relationship between two genes after accounting for all other measured genes.

The key mathematical object is conditional independence. Genes B and C are conditionally independent given A if P(B, C \mid A) = P(B \mid A) P(C \mid A). In words: once we know A, learning B tells us nothing new about C. In our toy example, B and C are marginally correlated but conditionally independent given A because the structural equations show that all shared information flows through A.

For jointly Gaussian variables, there is a beautiful algebraic result. The precision matrix \Theta = \Sigma^{-1} (the inverse covariance) encodes conditional independence directly: \theta_{ij} = 0 \quad \iff \quad \text{genes } i \text{ and } j \text{ are conditionally independent given all others}. This is remarkable: while the covariance matrix collects marginal pairwise associations (including spurious ones), the precision matrix performs “mathematical surgery,” removing edges between genes that only appear correlated due to shared drivers. In our A \to B, A \to C system, \Sigma_{BC} \neq 0 but \Theta_{BC} \approx 0. The toy example above already generated the data; let’s compute both matrices to verify this.

Now that we see the trap, let’s formalize the tools biologists use to quantify association. Our first instinct is usually Pearson correlation. Given two genes A and B, correlation measures the linear dependence between them, r(A, B) = \frac{\operatorname{Cov}(A, B)}{\sqrt{\operatorname{Var}(A)}\sqrt{\operatorname{Var}(B)}}. It is fast to compute and easy to interpret, but it only probes straight-line relationships. Quadratic or thresholded regulation can produce r \approx 0 even when a transcription factor truly controls its target.

Code
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(12)
gene_a = np.random.uniform(-2.5, 2.5, size=450)
gene_c = gene_a**2 + 0.3 * np.random.randn(gene_a.size)
r_ac = np.corrcoef(gene_a, gene_c)[0, 1]

fig, ax = plt.subplots()
ax.scatter(gene_a, gene_c, s=10, alpha=0.5, c='#FF1F5B', edgecolor='none')
ax.set_xlabel('Gene A')
ax.set_ylabel('Gene C')
ax.set_title(f'U-shaped dependency (r = {r_ac:.3f})')
ax.grid(alpha=0.3)
plt.tight_layout()
plt.show()
Figure 4.27: Pearson correlation can miss nonlinear dependence. Here Gene C follows a U-shaped relationship with Gene A, but the reported r is near zero even though Gene C is entirely determined by Gene A plus noise.

The plot already shows how correlation can miss a clear dependency. We need a statistic that fires whenever learning one gene lowers our uncertainty about another, no matter the shape of the curve. In information theory the entropy of a variable X, written H(X), quantifies unpredictability, while the conditional entropy H(X \mid Y) is what remains once Y is known. Mutual information is simply the reduction in uncertainty: it counts how many bits about A disappear once we observe B. Formally, I(A; B) = \sum_{a, b} p(a, b) \log \frac{p(a, b)}{p(a)p(b)} = H(A) - H(A \mid B). The first expression shows MI as the Kullback–Leibler divergence between the joint distribution and the product of its marginals, the penalty for pretending A and B were independent. The entropy difference H(A) - H(A \mid B) makes the uncertainty reduction explicit. The catch is estimation; we need enough cells to approximate the joint density faithfully.

Before unleashing MI on real data, let’s watch correlation and MI on a toy dataset where we control the ground truth.

Code
import numpy as np
import pandas as pd
import warnings

# Quiet library warnings so the discussion stays focused on biological interpretation.
warnings.filterwarnings("ignore")

np.random.seed(42)
n_cells = 600

# Gene A and Gene B: strong linear relationship
gene_a = np.random.randn(n_cells)
gene_b = 0.75 * gene_a + 0.25 * np.random.randn(n_cells)

# Gene A and Gene C: nonlinear (quadratic) relationship
gene_c = gene_a**2 + 0.3 * np.random.randn(n_cells)

# Gene D: independent noise
gene_d = np.random.randn(n_cells)

def mutual_information(x, y, bins=20):
    joint, _, _ = np.histogram2d(x, y, bins=bins)
    joint = joint / joint.sum()
    px = joint.sum(axis=1, keepdims=True)
    py = joint.sum(axis=0, keepdims=True)
    with np.errstate(divide='ignore', invalid='ignore'):
        mi = joint * (np.log(joint + 1e-12) - np.log(px + 1e-12) - np.log(py + 1e-12))
    return np.nansum(mi)

pairs = [
    ('A', 'B', gene_a, gene_b),
    ('A', 'C', gene_a, gene_c),
    ('A', 'D', gene_a, gene_d)
]

rows = []
for name_x, name_y, x, y in pairs:
    corr = np.corrcoef(x, y)[0, 1]
    mi = mutual_information(x, y)
    rows.append({'Pair': f'{name_x}-{name_y}',
                 'Pearson r': corr,
                 'Mutual information': mi})

df_scores = pd.DataFrame(rows).round({'Pearson r': 3, 'Mutual information': 3})
df_scores
Pair Pearson r Mutual information
0 A-B 0.944 1.108
1 A-C 0.087 0.840
2 A-D -0.038 0.207

The MI score flags both the linear and nonlinear associations, highlighting why many pipelines move beyond simple correlation.

4.10.4 From Co-expression to Regulons

Toy simulations build intuition, but we also want to see how the same logic plays out on real data. Let’s return to the PBMC3k counts we used to build the landscape earlier in this chapter and focus on a small set of immune transcription factors drawn from DoRothEA’s curated regulons (Garcia-Alonso et al. 2019). A regulon is a transcription factor plus its predicted targets, identified by combining co-expression with prior biological knowledge like DNA binding motifs. For each TF we inspect a handful of canonical targets: SPI1 with monocyte markers like LYZ, TBX21 with cytotoxic effectors like PRF1, assembled from PanglaoDB catalogues (Franzén, Gan, and Björk 2019).

Code
import numpy as np
import pandas as pd
import scanpy as sc
from scipy.sparse import issparse

# Load PBMC3k dataset (also used earlier in this chapter)
adata = sc.datasets.pbmc3k()

# Standard preprocessing: library size normalization + log1p
sc.pp.normalize_total(adata, target_sum=1e4)
sc.pp.log1p(adata)

# Keep highly variable genes while forcing TFs/targets of interest to remain
tf_seeds = ['SPI1', 'IRF8', 'GATA3', 'TBX21', 'IRF7']
candidate_targets = {
    'SPI1': ['LYZ', 'S100A8', 'LST1', 'CTSS'],
    'IRF8': ['HLA-DRA', 'HLA-DPB1', 'HLA-DQA1', 'CD74'],
    'GATA3': ['CCR7', 'IL7R', 'MAL', 'LST1'],
    'TBX21': ['NKG7', 'PRF1', 'GZMB', 'IFNG'],
    'IRF7': ['ISG15', 'IFI44L', 'MX1', 'OASL']
}

# Annotate highly variable genes
sc.pp.highly_variable_genes(adata, n_top_genes=2000, flavor='seurat_v3')

genes_keep = set(tf_seeds)
for targets in candidate_targets.values():
    genes_keep.update(targets)

selected_mask = adata.var['highly_variable'].copy()
selected_mask |= adata.var_names.isin(list(genes_keep))
adata = adata[:, selected_mask]

var_lookup = {name.lower(): name for name in adata.var_names}

# Convert to dense matrix for correlation calculations
X = adata.X.toarray() if issparse(adata.X) else adata.X
df_expr = pd.DataFrame(X, columns=adata.var_names)

rows = []
for tf in tf_seeds:
    tf_name = var_lookup.get(tf.lower())
    if tf_name is None:
        print(f"Transcription factor '{tf}' not found in the dataset; skipping.")
        continue
    tf_values = df_expr[tf_name].values
    tf_centered = tf_values - tf_values.mean()
    tf_norm = np.linalg.norm(tf_centered)
    for target in candidate_targets.get(tf, []):
        target_name = var_lookup.get(target.lower())
        if target_name is None:
            print(f"Target gene '{target}' not found for TF '{tf}'; skipping.")
            continue
        if target_name == tf_name:
            continue
        target_values = df_expr[target_name].values
        target_centered = target_values - target_values.mean()
        target_norm = np.linalg.norm(target_centered)
        if tf_norm == 0 or target_norm == 0:
            continue
        r = float(np.dot(tf_centered, target_centered) / (tf_norm * target_norm))
        rows.append({
            'TF': tf_name,
            'Target gene': target_name,
            'Pearson r': r
        })

if rows:
    df_cor = pd.DataFrame(rows)
    df_cor['Pearson r'] = df_cor['Pearson r'].round(3)
    df_cor.sort_values(['TF', 'Pearson r'], ascending=[True, False], inplace=True)
else:
    print("No TF-target correlations computed; verify that the requested genes are present.")
    df_cor = pd.DataFrame(columns=['TF', 'Target gene', 'Pearson r'])

df_cor
TF Target gene Pearson r
9 GATA3 IL7R 0.131
8 GATA3 CCR7 0.073
10 GATA3 MAL 0.026
11 GATA3 LST1 -0.113
16 IRF7 ISG15 0.173
18 IRF7 MX1 0.140
19 IRF7 OASL 0.069
17 IRF7 IFI44L 0.068
4 IRF8 HLA-DRA 0.348
6 IRF8 HLA-DQA1 0.330
7 IRF8 CD74 0.329
5 IRF8 HLA-DPB1 0.306
2 SPI1 LST1 0.624
0 SPI1 LYZ 0.554
3 SPI1 CTSS 0.538
1 SPI1 S100A8 0.444
13 TBX21 PRF1 0.328
14 TBX21 GZMB 0.319
12 TBX21 NKG7 0.318
15 TBX21 IFNG 0.187
Code
# Add brief biological interpretations to reinforce the link with curated knowledge
biological_notes = {
    'LYZ': 'Myeloid granules (classical monocytes)',
    'S100A8': 'Inflammatory myeloid program',
    'LST1': 'Dendritic/monocyte surface marker',
    'CTSS': 'Antigen presentation in monocytes',
    'HLA-DRA': 'MHC II complex (antigen presentation)',
    'HLA-DPB1': 'MHC II complex',
    'HLA-DQA1': 'MHC II complex',
    'CD74': 'Invariant chain for MHC II',
    'CCR7': 'Naive/central memory T cell homing',
    'IL7R': 'Homeostatic T cell survival receptor',
    'MAL': 'T helper cell polarity marker',
    'NKG7': 'Cytotoxic granule protein (NK/T cells)',
    'PRF1': 'Perforin (cytotoxic effector)',
    'GZMB': 'Granzyme B (cytotoxic effector)',
    'IFNG': 'Th1 / NK cytokine',
    'ISG15': 'Type I interferon response',
    'IFI44L': 'Interferon-stimulated gene',
    'MX1': 'Antiviral GTPase',
    'OASL': 'Interferon-induced antiviral enzyme'
}

bio_lookup = {gene.upper(): note for gene, note in biological_notes.items()}
if 'Target gene' in df_cor.columns:
    df_cor['Biology note'] = df_cor['Target gene'].str.upper().map(bio_lookup)
df_cor
TF Target gene Pearson r Biology note
9 GATA3 IL7R 0.131 Homeostatic T cell survival receptor
8 GATA3 CCR7 0.073 Naive/central memory T cell homing
10 GATA3 MAL 0.026 T helper cell polarity marker
11 GATA3 LST1 -0.113 Dendritic/monocyte surface marker
16 IRF7 ISG15 0.173 Type I interferon response
18 IRF7 MX1 0.140 Antiviral GTPase
19 IRF7 OASL 0.069 Interferon-induced antiviral enzyme
17 IRF7 IFI44L 0.068 Interferon-stimulated gene
4 IRF8 HLA-DRA 0.348 MHC II complex (antigen presentation)
6 IRF8 HLA-DQA1 0.330 MHC II complex
7 IRF8 CD74 0.329 Invariant chain for MHC II
5 IRF8 HLA-DPB1 0.306 MHC II complex
2 SPI1 LST1 0.624 Dendritic/monocyte surface marker
0 SPI1 LYZ 0.554 Myeloid granules (classical monocytes)
3 SPI1 CTSS 0.538 Antigen presentation in monocytes
1 SPI1 S100A8 0.444 Inflammatory myeloid program
13 TBX21 PRF1 0.328 Perforin (cytotoxic effector)
14 TBX21 GZMB 0.319 Granzyme B (cytotoxic effector)
12 TBX21 NKG7 0.318 Cytotoxic granule protein (NK/T cells)
15 TBX21 IFNG 0.187 Th1 / NK cytokine

These correlations reassure us that the statistics align with curated biological knowledge: SPI1 sits on top of lysosomal modules, TBX21 rides with cytotoxic genes, IRF7 pulls interferon targets. This table of correlations is informative but abstract, and the common-driver adversary could still be at work. A table is not a map. To see where these programs operate we must project them back onto the cellular landscape we already constructed, so let’s visualize their activity in that shared space.

Code
import scanpy as sc
import numpy as np
from scipy.sparse import issparse

# Reload and preprocess PBMCs with full pipeline to get UMAP
adata_full = sc.datasets.pbmc3k()
sc.pp.normalize_total(adata_full, target_sum=1e4)
sc.pp.log1p(adata_full)
sc.pp.highly_variable_genes(adata_full, n_top_genes=2000)
adata_full = adata_full[:, adata_full.var.highly_variable]
sc.pp.scale(adata_full, max_value=10)
sc.tl.pca(adata_full, n_comps=50)
sc.pp.neighbors(adata_full, n_neighbors=15, n_pcs=40)
sc.tl.umap(adata_full)

# Reload original normalized data to get raw expression values
adata_expr = sc.datasets.pbmc3k()
sc.pp.normalize_total(adata_expr, target_sum=1e4)
sc.pp.log1p(adata_expr)

# Calculate SPI1 regulon score
spi1_regulon_genes = ['SPI1', 'LYZ', 'S100A8', 'LST1', 'CTSS']
var_lookup_expr = {name.upper(): name for name in adata_expr.var_names}

regulon_scores = []
for gene_symbol in spi1_regulon_genes:
    gene_name = var_lookup_expr.get(gene_symbol.upper())
    if gene_name:
        X_expr = adata_expr.X.toarray() if issparse(adata_expr.X) else adata_expr.X
        gene_idx = adata_expr.var_names.get_loc(gene_name)
        regulon_scores.append(X_expr[:, gene_idx])

if regulon_scores:
    # Average expression across regulon genes
    spi1_regulon_score = np.mean(regulon_scores, axis=0)
    adata_full.obs['SPI1_regulon'] = spi1_regulon_score

    # Plot on UMAP
    sc.pl.umap(adata_full, color='SPI1_regulon', cmap='plasma',
               title='SPI1 regulon activity', vmin=0, vmax=np.percentile(spi1_regulon_score, 98))
else:
    print("Could not compute SPI1 regulon score; required genes missing")
Figure 4.28: Activity of the SPI1 regulon across PBMC cell types. The regulon score, computed as the mean expression of SPI1’s co-expressed targets (LYZ, S100A8, LST1, CTSS), is highest in the monocyte cluster. This spatial localization confirms the regulon’s cell-type-specific activity and demonstrates how GRN inference connects molecular programs to cellular identity.

The monocyte cluster lights up, confirming that this regulon is active precisely where we expect it based on known biology. This is the power of combining correlation with prior knowledge: we move from abstract statistics to spatial patterns that make biological sense.

4.10.5 The Incomplete Observational GRN

Even with this more general statistic we are still trapped. We are passive observers, and observation cannot prove causation. The web of hidden drivers can always fabricate plausible correlations. To find the true edges we must stop watching and start acting.

4.10.6 Breaking the Correlation Trap

If observation alone is not enough, we must intervene. To prove causation we must move from seeing to doing. Interventional data rescue us from the correlation trap because they let us distinguish P(Y \mid X = x), observing that X happens to have value x, from P(Y \mid \operatorname{do}(X = x)), forcing X to equal x and measuring the consequence. The \operatorname{do} operator formalizes what experimentalists have always known: perturb the system and watch what breaks.

The distinction is subtle but crucial. Conditioning, P(Y \mid X = x), keeps every incoming edge into X intact, so any parent of X can leak information into Y. Intervention, P(Y \mid \operatorname{do}(X = x)), performs graph surgery: it deletes all arrows pointing into X before setting its value. If Y still responds, we have found a genuine causal edge X \to Y; if the relationship vanishes, we have exposed a confound. Thinking in adjacency matrices, the \operatorname{do} operator is zeroing out the column of parents before testing the downstream effect.

Let’s see this in action with our toy model. Recall that genes B and C were strongly correlated because they shared driver A. Now imagine we can knock out gene A in half the cells. That manipulation is the \operatorname{do}(A = 0) operation, set A to zero regardless of what the upstream network would have done. If the B-C correlation was causal, it should persist. If it was spurious, it should vanish.

Code
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(7)
n_cells = 300

# Control population: A → B, A → C
gene_a_control = np.random.randn(n_cells)
gene_b_control = 0.8 * gene_a_control + 0.3 * np.random.randn(n_cells)
gene_c_control = 0.75 * gene_a_control + 0.35 * np.random.randn(n_cells)
r_bc_control = np.corrcoef(gene_b_control, gene_c_control)[0, 1]

# Perturbed population: A is knocked out (A = 0)
gene_a_perturbed = np.zeros(n_cells)  # Knockout
gene_b_perturbed = 0.8 * gene_a_perturbed + 0.3 * np.random.randn(n_cells)  # Only noise remains
gene_c_perturbed = 0.75 * gene_a_perturbed + 0.35 * np.random.randn(n_cells)  # Only noise remains
r_bc_perturbed = np.corrcoef(gene_b_perturbed, gene_c_perturbed)[0, 1]

# Create 2-panel figure
fig, axes = plt.subplots(1, 2)

# Panel A: Control (B vs C with spurious correlation)
axes[0].scatter(gene_b_control, gene_c_control, s=8, alpha=0.5, c='#009ADE', edgecolor='none')
axes[0].set_xlabel('Gene B')
axes[0].set_ylabel('Gene C')
axes[0].set_title(f'Control (r = {r_bc_control:.3f})')
axes[0].grid(alpha=0.3)
axes[0].set_xlim(-3, 3)
axes[0].set_ylim(-3, 3)

# Panel B: Perturbed (B vs C correlation breaks)
axes[1].scatter(gene_b_perturbed, gene_c_perturbed, s=8, alpha=0.5, c='#FF1F5B', edgecolor='none')
axes[1].set_xlabel('Gene B')
axes[1].set_ylabel('Gene C')
axes[1].set_title(f'A knockout (r = {r_bc_perturbed:.3f})')
axes[1].grid(alpha=0.3)
axes[1].set_xlim(-3, 3)
axes[1].set_ylim(-3, 3)

plt.tight_layout()
plt.show()
Figure 4.29: Breaking spurious correlations with intervention. In the control population (left), B and C are strongly correlated due to shared driver A. After knocking out A (right), the correlation vanishes, proving it was spurious. This demonstrates the power of interventional data: perturbations reveal causal structure that observation alone cannot distinguish.

So what happens when we actually break the suspected parent? The correlation collapses to near zero after the knockout, because a single intervention exposes how flimsy the observational Pearson r really was. Perturb-seq (Dixit et al. 2016) scales that idea to the genome: we deliver a pooled library of guide RNAs (sgRNAs) so that most cells receive a single perturbation, capture each cell’s guide barcode alongside its transcriptome, and then compare transcriptomes across perturbations to evaluate P(Y \mid \operatorname{do}(X)) directly.

Perturb-seq as Multivariate Regression

Mathematically, Perturb-seq solves a regression problem. Let Y \in \mathbb{R}^{n \times g} be the gene expression matrix (cells by genes), G \in \{0,1\}^{n \times p} be the perturbation design matrix indicating which guide RNA each cell received, and \Gamma \in \mathbb{R}^{p \times g} be the regulatory effect matrix we want to infer. The model is Y = G\Gamma + X\Beta + E, where X captures technical covariates (batch, cell cycle, etc.) and E is noise. Each entry \gamma_{ij} represents the causal effect of perturbing gene i on the expression of gene j. Because perturbations are assigned randomly (or in balanced blocks), G is orthogonal to confounders by experimental design, making \Gamma identifiable. This is the linear algebra backbone of modern GRN inference: intervention turns an unidentifiable inverse problem (inferring network structure from observational covariance) into a well-posed regression.

Think of the \operatorname{do} operator as a regression diagnostic. Fit gene C on gene B before and after the \operatorname{do}(A = 0) intervention and watch how the slope (and its p-value) evaporates once we sever the hidden parent.

Code
import numpy as np
from scipy import stats

np.random.seed(7)
n_cells = 300

# Control population: A → B, A → C
gene_a_control = np.random.randn(n_cells)
gene_b_control = 0.8 * gene_a_control + 0.3 * np.random.randn(n_cells)
gene_c_control = 0.75 * gene_a_control + 0.35 * np.random.randn(n_cells)

# Perturbed population: enforce do(A = 0)
gene_a_perturbed = np.zeros(n_cells)
gene_b_perturbed = 0.8 * gene_a_perturbed + 0.3 * np.random.randn(n_cells)
gene_c_perturbed = 0.75 * gene_a_perturbed + 0.35 * np.random.randn(n_cells)

slope_control = stats.linregress(gene_b_control, gene_c_control)
slope_perturbed = stats.linregress(gene_b_perturbed, gene_c_perturbed)

summary = (
    f"Control slope = {slope_control.slope:.3f}, p = {slope_control.pvalue:.3e}\n"
    f"Perturbed slope = {slope_perturbed.slope:.3f}, p = {slope_perturbed.pvalue:.3e}"
)
print(summary)
Control slope = 0.797, p = 3.961e-86
Perturbed slope = 0.121, p = 7.354e-02

Those slopes collapse from 0.80 to roughly 0.12, and the p-value inflates accordingly. That is exactly what a Perturb-seq contrast reads off at transcriptome scale: causal edges endure when we intervene, while spurious ones flatten out.

CRISPR-Cas9 makes this practical. A guide RNA steers Cas9 to a chosen locus; cutting inside a coding sequence disrupts the gene just as if we had set A=0. Because each cell carries one transcriptome and one guide barcode, a single sequencing run reports the genome-wide response to every perturbation in the pool. Variants such as CRISPR interference (blocking transcription), CRISPR activation (forcing expression), or multiome Perturb-seq (stacking chromatin and RNA) all serve the same inference goal: compare perturbed and control transcriptomes and keep only the edges that survive causal scrutiny.

Perturb-seq therefore validates or rejects the hypotheses we built from co-expression. The figure below compares the observational network with its intervention-tested counterpart; dashed edges fall away the moment we test them.

Code
import networkx as nx
import matplotlib.pyplot as plt

# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

genes = ['TF1', 'TF2', 'GeneA', 'GeneB', 'GeneC', 'GeneD']
positions = {
    'TF1': (-1.5, 1.0),
    'TF2': (1.5, 1.0),
    'GeneA': (-2.0, -0.5),
    'GeneB': (-0.5, -0.8),
    'GeneC': (0.5, -0.8),
    'GeneD': (2.0, -0.5)
}

observational_edges = [
    ('TF1', 'GeneA'),
    ('TF1', 'GeneB'),
    ('TF1', 'GeneC'),
    ('TF2', 'GeneC'),
    ('TF2', 'GeneD'),
    ('GeneA', 'GeneB'),  # indirect
    ('GeneC', 'GeneD')   # indirect
]

validated_edges = [
    ('TF1', 'GeneA'),
    ('TF1', 'GeneB'),
    ('TF2', 'GeneC'),
    ('TF2', 'GeneD')
]

fig, axes = plt.subplots(1, 2)

for ax, edges, title in zip(
    axes,
    [observational_edges, validated_edges],
    ['(a) Observational network', '(b) Perturb-validated network']
):
    G = nx.DiGraph()
    G.add_nodes_from(genes)
    G.add_edges_from(edges)

    node_colors = [
        QUALITATIVE_COLORS[0] if node.startswith('TF') else QUALITATIVE_COLORS[1]
        for node in G.nodes
    ]

    nx.draw_networkx_nodes(G, positions, node_color=node_colors, node_size=800, ax=ax, alpha=0.9)
    nx.draw_networkx_labels(G, positions, font_size=9, ax=ax)

    solid_edges = []
    dashed_edges = []
    for edge in edges:
        if edge in validated_edges:
            solid_edges.append(edge)
        else:
            dashed_edges.append(edge)

    nx.draw_networkx_edges(G, positions, edgelist=solid_edges,
                           edge_color=QUALITATIVE_COLORS[3], width=2.5,
                           arrows=True, ax=ax, arrowstyle='-|>', min_source_margin=0.15,
                           min_target_margin=0.15)
    nx.draw_networkx_edges(G, positions, edgelist=dashed_edges,
                           edge_color='gray', width=2.0, style='dashed',
                           arrows=True, ax=ax, arrowstyle='-|>', alpha=0.8,
                           min_source_margin=0.15, min_target_margin=0.15)

    ax.set_title(title)
    ax.set_xticks([])
    ax.set_yticks([])
    ax.grid(alpha=0.3)

plt.tight_layout()
plt.show()
Figure 4.30: Perturbations reveal which edges survive causality tests. (a) Observational GRN built from co-expression contains dense indirect connections (dashed edges). (b) After Perturb-seq validation, only edges with true causal support remain (solid). Interventions transform noisy hypotheses into actionable mechanisms.

4.10.7 Modern Extensions

Modern perturbation atlases now pair CRISPR screens with spatial readouts or chromatin accessibility so we can watch network function shift with neighborhood (Dong et al. 2023). They close the loop opened above: the same perturbation panel is observed across intact tissues, letting us test whether causal edges survive in distinct niches. These datasets motivate the inference tools ahead (from spatial deconvolution to atlas mapping) because they demand that we anchor every regulatory program to the tissue where it operates.

4.11 Spatial Mechanisms

4.11.1 The Missing Dimension

Everything we have reconstructed (states, flows, and forces) still treated cells as disembodied points. Real tissues define function through neighbors, so dissociation tells us a program exists but not which job it performs or which niche sustains it.

Spatial transcriptomics restores that missing axis by reading transcripts together with coordinates. Imaging platforms such as MERFISH and seqFISH light up hundreds to thousands of genes directly in tissue with subcellular precision, while sequencing platforms such as 10x Visium and Slide-seq capture whole-transcriptome profiles from barcoded spots tens of microns across. Each technology balances resolution against coverage, yet all set up the same mathematical task: fuse expression vectors with physical location.

Once coordinates return we can place Waddington’s valleys in actual organs, trace which neighborhoods power an organ’s behavior, and map developmental trajectories onto anatomy. That spatial scaffold is the ingredient we need for the mixture models that follow.

4.11.2 Spatial Deconvolution as a Mixture Model

This brings us to our final challenge, one that unites everything we have built. A spatial spot is a noisy mixture of cells. To understand its composition we need the Negative Binomial physics from Chapter 2, the inference mindset from Chapter 3, and the cell-type map we just constructed. The question is simple: which combination of cell types best explains the counts we see at this location?

Before we write down another likelihood, recall the logic from Chapter 2. Bursty transcription made even a single gene per cell follow a Negative Binomial distribution. A Visium spot simply sums over several cells, so it becomes a mixture of those same Negative Binomials. The only unknowns are the mixing weights, the proportions of each cell type that landed in the spot. Deconvolution is therefore a parameter estimation problem: find the weights that best explain the observed counts. Stack the spot-by-gene matrix into Y \in \mathbb{R}^{G \times S}, the reference atlas into R \in \mathbb{R}^{G \times T}, and the unknown proportions into \Theta \in \mathbb{R}_{\ge 0}^{T \times S}; the task is to solve Y \approx R \Theta under non-negativity (and often smoothness) constraints, the same linear-algebraic viewpoint we relied on for PCA and regression. In matrix-factorization terms we are minimizing \|Y - R \Theta\|_F^2 while forcing each column of \Theta to contain non-negative proportions that sum to one. It is PCA with biology’s two constraints: counts cannot be negative and each spot must apportion to a full mixture of cell types.

Consider Visium data. Each spot contains RNA from a handful of cells; we want to infer which cell types are present and in what proportions. Suppose we have a reference scRNA-seq atlas with mean expression \mu_{gt} for gene g in cell type t. The observed counts at spot s follow a Negative Binomial: y_{gs} \sim \operatorname{NegBin}\left(\sum_{t} \theta_{st} \mu_{gt}, \phi_g\right), where \theta_{st} is the abundance of cell type t in spot s, and \phi_g is the overdispersion parameter. This is the core of cell2location (Kleshchevnikov et al. 2022) and it reuses the Negative Binomial noise model we derived in Chapter 2 to capture transcriptional overdispersion.

Deconvolution via Negative Binomial Mixtures

Spatial deconvolution is a statistical inference problem: given observed counts y_{gs} at each spot and reference expression profiles \mu_{gt} from our single-cell atlas, infer the cell-type proportions \theta_{st}. We model each gene’s counts with the Negative Binomial distribution from Chapter 2, but now the mean is a mixture: \lambda_{gs} = \sum_t \theta_{st} \mu_{gt}, the weighted sum of reference profiles.

For a single spot s, the log-likelihood is \ell_s(\theta_s) = \sum_{g}\Big[\log \Gamma(y_{gs}+\phi_g) - \log \Gamma(\phi_g) - \log y_{gs}! + y_{gs} \log \lambda_{gs} - (\phi_g + y_{gs}) \log(\phi_g + \lambda_{gs})\Big], where \phi_g captures overdispersion. Maximizing \sum_s \ell_s(\theta_s) subject to \theta_{st} \ge 0 (and optional spatial smoothness constraints) yields the cell-type proportions. Modern tools like cell2location use variational inference to solve this efficiently.

Here’s a toy demonstration using synthetic data. We generate reference profiles for three cell types, create NegBin-distributed counts that mimic spatial spots, then estimate compositions. For pedagogical simplicity, we use non-negative least squares (NNLS), which minimizes \|Y - R\Theta\|_F^2—this assumes Gaussian errors rather than the correct NegBin likelihood above, but it’s computationally trivial and provides reasonable estimates when counts are not too sparse. Production tools implement the full NegBin MLE.

Code
import numpy as np
import pandas as pd
from scipy.optimize import nnls

np.random.seed(3)

n_genes = 6
n_cell_types = 3
n_spots = 30

# Reference mean expression per gene × cell type
reference_profiles = np.abs(np.random.randn(n_genes, n_cell_types))
reference_profiles /= reference_profiles.sum(axis=0, keepdims=True)

# True compositions (Dirichlet-distributed per spot)
true_theta = np.random.dirichlet(alpha=[2.0, 1.2, 0.8], size=n_spots)

# Generate noisy counts
size_factors = np.random.gamma(shape=5.0, scale=200.0, size=n_spots)
expected = reference_profiles @ true_theta.T
counts = np.random.negative_binomial(
    n=3.0,
    p=3.0 / (3.0 + (expected * size_factors).T)
).T

# Estimate compositions with Non-Negative Least Squares (NNLS).
# Note: This is a fast Gaussian approximation. Full probabilistic
# methods optimize the Negative Binomial likelihood derived above.
estimated_theta = np.zeros_like(true_theta)
for s in range(n_spots):
    sol, _ = nnls(reference_profiles, counts[:, s])
    if sol.sum() == 0:
        estimated_theta[s] = sol
    else:
        estimated_theta[s] = sol / sol.sum()

df_compare = pd.DataFrame({
    'Spot': np.arange(n_spots),
    'True_T1': true_theta[:, 0],
    'True_T2': true_theta[:, 1],
    'True_T3': true_theta[:, 2],
    'Est_T1': estimated_theta[:, 0],
    'Est_T2': estimated_theta[:, 1],
    'Est_T3': estimated_theta[:, 2]
}).round(3)

df_compare.head()
Spot True_T1 True_T2 True_T3 Est_T1 Est_T2 Est_T3
0 0 0.809 0.047 0.144 0.583 0.076 0.341
1 1 0.133 0.072 0.795 0.000 0.000 1.000
2 2 0.470 0.367 0.164 0.606 0.394 0.000
3 3 0.242 0.697 0.062 0.139 0.861 0.000
4 4 0.762 0.214 0.024 1.000 0.000 0.000

The estimates are noisy but track the true compositions, good enough to map broad structures such as cortex layers or lymphoid follicles.

Code
import numpy as np
import matplotlib.pyplot as plt

# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

grid_cols = int(np.ceil(np.sqrt(n_spots)))
grid_rows = int(np.ceil(n_spots / grid_cols))

def reshape_for_grid(values):
    """Pad spot values to fill the nearest rectangular grid."""
    padded = np.full(grid_rows * grid_cols, np.nan)
    padded[:values.size] = values
    return padded.reshape(grid_rows, grid_cols)

def plot_heatmap(ax, values, title):
    im = ax.imshow(
        reshape_for_grid(values),
        cmap='plasma',
        origin='lower'
    )
    ax.set_xticks([])
    ax.set_yticks([])
    ax.set_title(title)
    ax.grid(alpha=0.3, color='white', linewidth=0.5)
    return im

fig, axes = plt.subplots(3, 2)

for idx in range(3):
    im_true = plot_heatmap(
        axes[idx, 0],
        true_theta[:, idx],
        f'Cell type {idx+1} (true)'
    )
    im_est = plot_heatmap(
        axes[idx, 1],
        estimated_theta[:, idx],
        f'Cell type {idx+1} (estimated)'
    )

fig.colorbar(
    im_true,
    ax=axes[:, 0],
    orientation='horizontal',
    fraction=0.07,
    pad=0.08,
    label='Fraction'
)
fig.colorbar(
    im_est,
    ax=axes[:, 1],
    orientation='horizontal',
    fraction=0.07,
    pad=0.08,
    label='Fraction'
)

plt.tight_layout()
plt.show()
Figure 4.31: Spatial deconvolution recovers latent compositions. (a) Ground-truth fractions of three cell types across synthetic spatial spots arranged on a grid. (b) Estimated fractions from a Negative Binomial mixture fit via non-negative least squares. Even with noise, the algorithm recovers the dominant spatial domains.

4.11.3 Mapping Atlases into Tissue

One flavor of spatial method infers mixtures per spot; the complementary flavor assigns single-cell profiles to spatial positions so that aggregated expression matches the spatial measurement. Both solve an optimal transport-style coupling, now moving cells into physical space rather than mass through time. We seek a coupling matrix P that respects spot capacities and minimizes a cost built from expression similarity: \min_{P \ge 0} \|P^\top X - Y\|_F^2 + \lambda \, \Omega(P), where X \in \mathbb{R}^{n \times g} is the single-cell expression matrix (cells × genes), Y \in \mathbb{R}^{s \times g} is the spatial expression matrix (spots × genes), P \in \mathbb{R}^{n \times s} is the assignment matrix (which cells map to which spots), and \Omega enforces spatial smoothness. The product P^\top X \in \mathbb{R}^{s \times g} reconstructs spatial expression as a weighted combination of cells. Modern software packages this formulation, but the mathematics is the coupling.

Code
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from matplotlib.patches import Patch

np.random.seed(21)

# Generate single-cell embedding
n_cells = 500
cell_types = np.random.choice(['Excitatory', 'Inhibitory', 'Astrocyte'], size=n_cells, p=[0.45, 0.35, 0.20])

centers = {
    'Excitatory': np.array([2.5, 1.0]),
    'Inhibitory': np.array([0.0, -1.5]),
    'Astrocyte': np.array([-2.5, 1.5])
}

embedding = np.vstack([
    centers[ctype] + 0.5 * np.random.randn(2)
    for ctype in cell_types
])

color_map = {
    'Excitatory': QUALITATIVE_COLORS[0],
    'Inhibitory': QUALITATIVE_COLORS[1],
    'Astrocyte': QUALITATIVE_COLORS[2]
}

colors = [color_map[c] for c in cell_types]

# Create spatial grid and assign cell types
grid_side = 20
spatial_types = np.empty((grid_side, grid_side), dtype=object)

for i in range(grid_side):
    for j in range(grid_side):
        if i < grid_side / 3:
            spatial_types[i, j] = 'Astrocyte'
        elif j > grid_side * 0.65:
            spatial_types[i, j] = 'Inhibitory'
        else:
            spatial_types[i, j] = 'Excitatory'

# Simulate marker expression
marker_expression = {
    'Slc17a7': (spatial_types == 'Excitatory').astype(float),
    'Gad1': (spatial_types == 'Inhibitory').astype(float),
    'Gfap': (spatial_types == 'Astrocyte').astype(float)
}

fig, axes = plt.subplots(1, 3)

# Panel A: Embedding
axes[0].scatter(embedding[:, 0], embedding[:, 1], c=colors, s=15, alpha=0.7)
axes[0].set_title('(a) Single-cell embedding')
axes[0].set_xlabel('UMAP 1')
axes[0].set_ylabel('UMAP 2')
axes[0].grid(alpha=0.3)

# Panel B: Spatial assignment
type_order = ['Excitatory', 'Inhibitory', 'Astrocyte']
type_to_idx = {ctype: idx for idx, ctype in enumerate(type_order)}
spatial_indices = np.zeros(spatial_types.shape, dtype=int)
for ctype, idx in type_to_idx.items():
    spatial_indices[spatial_types == ctype] = idx
spatial_cmap = ListedColormap([color_map[ctype] for ctype in type_order])
axes[1].imshow(spatial_indices, origin='lower', cmap=spatial_cmap, vmin=-0.5, vmax=len(type_order) - 0.5)
axes[1].set_title('(b) Inferred spatial map')
axes[1].set_xticks([])
axes[1].set_yticks([])
axes[1].grid(alpha=0.3, color='white', linewidth=0.5)
legend_handles = [Patch(facecolor=color_map[ctype], label=ctype) for ctype in type_order]

# Panel C: Marker validation
marker = marker_expression['Slc17a7']
im = axes[2].imshow(marker, cmap='plasma', origin='lower')
axes[2].set_title('(c) Slc17a7 expression (Excitatory)')
axes[2].set_xticks([])
axes[2].set_yticks([])
axes[2].grid(alpha=0.3, color='white', linewidth=0.5)
fig.colorbar(im, ax=axes[2], fraction=0.046, pad=0.04, label='Normalized expression')

fig.legend(
    handles=legend_handles,
    loc='upper center',
    ncol=3,
    frameon=False,
    bbox_to_anchor=(0.5, 1.08)
)

plt.tight_layout()
plt.show()
Figure 4.32: Conceptual Tangram mapping. (a) Single-cell embedding colored by cell type. (b) Spatial grid colored by inferred dominant cell type after mapping. (c) Marker gene validation showing that mapped locations recover expected expression domains. Tangram aligns an atlas to tissue by solving a regularized optimal transport problem.

4.11.4 Quantifying Spatial Autocorrelation

Once cells are mapped, we can borrow tools from earlier in the chapter: build spatial graphs, run Leiden with spatial weights, and delineate anatomical domains. But we also need a quantitative metric to ask: is this gene expression pattern spatially structured, or is it randomly scattered across the tissue? The answer lies in spatial autocorrelation, which measures whether nearby locations have similar values.

The canonical metric is Moran’s I, which we can derive as a ratio of quadratic forms. Let \mathbf{x} \in \mathbb{R}^n be the mean-centered expression values for a gene across n spatial spots. Let \mathbf{W} be the spatial weight matrix, where w_{ij} = 1 if spots i and j are neighbors (e.g., within a distance threshold) and w_{ij} = 0 otherwise. The total weight is W = \sum_{ij} w_{ij}.

Moran’s I is defined as I = \frac{n}{W} \frac{\mathbf{x}^\top \mathbf{W} \mathbf{x}}{\mathbf{x}^\top \mathbf{x}}. The numerator \mathbf{x}^\top \mathbf{W} \mathbf{x} = \sum_{ij} w_{ij} x_i x_j is the spatial covariance: it sums the products of expression values at neighboring spots. If neighbors have similar expression (both high or both low), this sum is large and positive. If the pattern is random, positive and negative terms cancel. The denominator \mathbf{x}^\top \mathbf{x} normalizes by the total variance, and n/W is a scaling factor.

Notice that this is structurally identical to the Rayleigh quotient for the graph Laplacian we encountered in dimensionality reduction. While the graph Laplacian \mathbf{L} = \mathbf{D} - \mathbf{W} measures signal roughness (penalizing differences between neighbors), Moran’s I measures signal smoothness (rewarding similarity). Under the null hypothesis of no spatial structure, I \approx 0. For strong positive autocorrelation (clustered patterns), I > 0; for negative autocorrelation (checkerboard patterns), I < 0.

Let’s verify this on real data. We’ll load the Visium mouse brain dataset, compute the spatial weight matrix from coordinates, and manually calculate Moran’s I for a spatially variable gene.

Code
import numpy as np
import scanpy as sc
import squidpy as sq
from sklearn.neighbors import kneighbors_graph
from scipy.sparse import issparse

# Load Visium mouse brain
adata_visium = sq.datasets.visium_hne_adata()
adata_visium.var_names_make_unique()
sc.pp.normalize_total(adata_visium, target_sum=1e4)
sc.pp.log1p(adata_visium)

# Extract spatial coordinates and build adjacency matrix W (6 nearest neighbors)
coords = adata_visium.obsm['spatial']
W = kneighbors_graph(coords, n_neighbors=6, mode='connectivity').toarray()
W_sum = np.sum(W)

# Select a spatially variable gene (Plp1 is a myelin marker, strongly patterned)
gene_name = 'Plp1'
if gene_name in adata_visium.var_names:
    X_gene = adata_visium[:, gene_name].X
    x = X_gene.toarray().flatten() if issparse(X_gene) else X_gene.flatten()
    x = x - np.mean(x)  # Center

    # Compute Moran's I via quadratic forms
    numerator = x.T @ W @ x
    denominator = x.T @ x
    n = len(x)
    morans_i = (n / W_sum) * (numerator / denominator)

    print(f"Manual Moran's I for {gene_name}: {morans_i:.3f}")
    print(f"  Interpretation: I > 0 indicates positive spatial autocorrelation")
    print(f"  (neighboring spots have similar expression)")
else:
    print(f"{gene_name} not found in dataset")
Manual Moran's I for Plp1: 0.688
  Interpretation: I > 0 indicates positive spatial autocorrelation
  (neighboring spots have similar expression)

The positive value confirms that Plp1 expression is spatially clustered, as expected for a gene marking myelinated fiber tracts. This single statistic summarizes spatial structure that would otherwise require visual inspection.

Now let’s see these spatial patterns on real tissue. We reload the Visium mouse brain dataset, normalize, and visualize clusters, canonical markers, and neighborhood enrichment.

Code
import scanpy as sc
import squidpy as sq
import warnings

# Load Visium mouse brain and matched image
adata_visium = sq.datasets.visium_hne_adata()
adata_visium.var_names_make_unique()
sc.pp.normalize_total(adata_visium, target_sum=1e4)
sc.pp.log1p(adata_visium)

# Compute spatial neighbors and clusters for visualization
sq.gr.spatial_neighbors(adata_visium, coord_type="grid")
sc.tl.leiden(adata_visium, resolution=0.5)

sq.pl.spatial_scatter(adata_visium, color="cluster")

Visium mouse brain confirms the synthetic intuition. (a) Leiden clusters overlaid on histology reveal cortical layers, hippocampus, and fiber tracts. (b) Marker genes (Plp1, Reln, Gad1) localize to expected regions. (c) Neighborhood enrichment quantifies that adjacent sublayers preferentially contact one another, validating that spatial structure survived preprocessing.
Code
marker_genes = ["Plp1", "Reln", "Gad1"]
present = [gene for gene in marker_genes if gene in adata_visium.var_names]
if present:
    sq.pl.spatial_scatter(adata_visium, color=present, ncols=len(present))
else:
    print("Requested markers absent; adjust list if running interactively.")

Code
import numpy as np
import matplotlib.pyplot as plt

# Spatial neighbors already computed in previous chunk; reuse them here
sq.gr.nhood_enrichment(adata_visium, cluster_key="cluster")

fig, ax = plt.subplots()
sq.pl.nhood_enrichment(
    adata_visium,
    cluster_key="cluster",
    ax=ax,
    show=False
)
ax.set_title("Neighborhood enrichment Z-scores")
plt.show()
(a) Neighborhood enrichment between Visium Leiden clusters. Each cell shows the Z-score for observing adjacent spots from the corresponding pair more often (warm) or less often (cool) than random, confirming that spatial neighborhoods are structured.
(b)
Figure 4.33

The diagonal blocks confirm that spatial neighbors tend to share cluster assignments, while the off-diagonal entries reveal where distinct domains meet. We can now ask not just what cells are present or how they move, but where they reside in the tissue and which neighborhoods they inhabit.

4.12 Synthesis: From Metaphor to Quantitative Model

Waddington’s landscape began as an intuitive metaphor. We have now assembled the mathematical framework to make it concrete. Deterministic ODEs (Chapter 1) define the mean flow, with fixed points marking cell-type attractors. Stochastic dynamics (Chapter 2) formalize rare transitions between valleys through the Chemical Master Equation, showing how noise enables fate switches. Bayesian inference (Chapter 3) turns parameter fitting into a principled statistical problem with quantified uncertainty.

This chapter fused those foundations with high-dimensional data: dimensionality reduction (PCA, UMAP) provides coordinates for states, RNA velocity and optimal transport infer flows, gene regulatory networks define the programs that shape the topography, and spatial transcriptomics supplies the anatomical context. Each layer—deterministic backbone, stochastic fluctuations, statistical inference, spatial grounding—adds rigor to the landscape metaphor until it becomes a testable dynamical systems model.

Code
import numpy as np
import matplotlib.pyplot as plt

# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

x = np.linspace(-3, 3, 200)
y = np.linspace(-1, 3, 200)
X, Y = np.meshgrid(x, y)

potential = (Y**4 - 2 * Y**3 + 0.5 * Y**2) + 0.3 * (X**2) + 0.5 * np.sin(2 * X)

fig, ax = plt.subplots()
contours = ax.contourf(X, Y, potential, levels=40, cmap='plasma', alpha=0.9)
ax.contour(X, Y, potential, levels=15, colors='white', linewidths=0.3, alpha=0.7)

# Trajectories
trajectories = [
    {'color': QUALITATIVE_COLORS[0], 'path': np.array([[-2.5, 2.5], [-2.0, 1.6], [-1.0, 0.9], [-0.5, 0.3]])},
    {'color': QUALITATIVE_COLORS[1], 'path': np.array([[0.0, 2.6], [-0.2, 1.7], [-0.3, 1.0], [-0.4, 0.2]])},
    {'color': QUALITATIVE_COLORS[3], 'path': np.array([[2.5, 2.4], [1.8, 1.5], [1.0, 0.8], [0.2, 0.1]])}
]

for traj in trajectories:
    ax.plot(traj['path'][:, 0], traj['path'][:, 1],
            color=traj['color'], linewidth=3, alpha=0.85)
    ax.scatter(traj['path'][:, 0], traj['path'][:, 1],
               color='white', edgecolor=traj['color'],
               linewidth=1.5, s=40, zorder=3)

ax.set_xlabel('Latent axis 1')
ax.set_ylabel('Latent axis 2')
ax.set_title('Reconstructed developmental landscape')
ax.grid(alpha=0.3, color='white')

plt.colorbar(contours, ax=ax, label='Potential energy')
plt.tight_layout()
plt.show()
Figure 4.34: A modern Waddington landscape. Valleys correspond to expression-defined states, trajectories (pink, blue, gold) represent the RNA velocity and OT flows we inferred, and the markers along each path denote spatial domains where those cells live. The figure ties together the full causal story: states, flows, forces, and their physical context.

The figure visualizes what we have built: a data-driven potential landscape with validated trajectories and spatial grounding, constructed from measurements, tested with interventions, and anchored in tissue architecture.

4.13 Looking Forward

The field continues to advance these ideas. Neural ODEs and normalizing flows learn dynamical systems directly from data. Multi-modal atlases integrate transcriptomics with chromatin accessibility, proteomics, and imaging to build more complete cellular state representations. Causal inference at scale combines Perturb-seq with lineage tracing and spatial context, closing the loop between hypothesis generation and experimental validation in intact tissues.

The mathematical biologist’s task is iterative: discover structure in high-dimensional data, model the dynamics that connect states, infer the regulatory mechanisms that create forces, and validate those mechanisms through perturbations and spatial context. We began with a single gene’s differential equation. We end with the tools to build, test, and localize entire transcriptome-scale dynamical systems.