Single-Cell Biology and Virtual Cells¶
Every human body contains roughly 37 trillion cells that share the same DNA blueprint yet play wildly different roles across brain, blood, heart, and tumour microenvironments. This file explores how single-cell RNA sequencing, geometric cell manifolds, RNA velocity, spatial transcriptomics, Perturb-seq, and cellular foundation models turn living tissues into computable landscapes and bring an AI Virtual Cell within reach.
-
Walk into a bustling orchestra hall and place a single microphone outside the closed doors. You will hear one muddy chord blending violins, percussion, and brass into a single loudness curve, completely missing a lone piccolo playing a warning motif in the back row. For decades, genomics faced the exact same limitation because bulk RNA sequencing ground up millions of cells together and measured only their average gene expression.
-
Single-cell RNA sequencing (scRNA-seq) changes the game by barcoding and measuring every individual cell on its own. Biologists love the smoothie versus fruit-salad analogy. Bulk sequencing blends a bowl of strawberries, blueberries, and one tiny, bitter peppercorn into a uniform smoothie where the peppercorn disappears into the average. Single-cell sequencing inspects every piece of fruit separately, immediately spotting the rare drug-resistant tumour clone or infiltrating immune cell hiding inside an otherwise healthy organ.
The Single-Cell Count Matrix and Cellular Manifolds¶
-
Picture a colossal spreadsheet where each row is an individual cell (\(N\) often ranges from \(10{,}000\) to millions) and each column is one of the roughly \(G \approx 20{,}000\) protein-coding genes in the human genome. Entry \(X_{ig}\) records how many messenger RNA (mRNA) transcripts of gene \(g\) were captured inside cell \(i\).
-
Working directly with raw count matrices is tricky for two physical reasons. First, the matrix suffers from extreme sparsity and technical dropout, meaning over \(90\%\) of entries are zero because tiny droplets fail to capture every RNA molecule present inside a microscopic cell. Second, different cells yield different total RNA capture depths (called library sizes \(L_i = \sum_{g=1}^{G} X_{ig}\)), so a cell with twice as many captured molecules would falsely look twice as active unless we rescale it.
-
Standard preprocessing transforms noisy raw counts into a clean geometric space through four disciplined steps.
- Library-size normalisation divides each cell's counts by its total captured transcripts \(L_i\) and multiplies by a common scale factor \(S\) (typically \(10{,}000\)), placing every cell on equal footing.
- Variance stabilisation applies a shifted logarithm so a handful of super-abundant housekeeping genes do not drown out subtle signalling genes.
- Highly Variable Gene (HVG) selection keeps the roughly \(2{,}000\) genes whose variance across cells exceeds the technical noise expected for their mean expression, trimming out static background noise.
- Dimensionality reduction and graph clustering first apply Principal Component Analysis (PCA) via Singular Value Decomposition from Chapter 02 to project cells onto the top \(30\) to \(50\) principal axes. Next, we build a \(k\)-nearest-neighbour (kNN) cell similarity graph (connecting directly to Chapter 15), partition it into biological cell types using Leiden community detection (maximising graph modularity without creating disconnected communities), and embed the graph into two dimensions with UMAP for human visualisation.
Cellular Dynamics, Pseudotime, and RNA Velocity¶
-
A classic single-cell experiment is destructive, because bursting a cell open to read its RNA kills it on the spot. At first glance, that sounds like trying to understand a football match from one frozen photograph. How can a static snapshot reveal how a stem cell differentiates into a neuron or how a healthy lung cell transforms into a metastatic tumour?
-
Because an asynchronous tissue contains thousands of cells caught at slightly different moments along the same biological journey, we can arrange those snapshots into a movie using two complementary ideas.
-
Trajectory inference and pseudotime treat the cell manifold like a winding hiking trail photographed from above. Starting from a known stem or progenitor cell, algorithms compute shortest geodesic paths or diffusion distances along the kNN graph to assign each cell a continuous progress coordinate called pseudotime \(\tau \in [0, 1]\), capturing both linear maturation and branching lineage splits.
-
Yet pseudotime alone cannot tell whether cells are walking forwards or backwards along a branch unless you supply a starting root. RNA velocity (La Manno et al., 2018; Bergen et al., 2020) solves that directionality puzzle by noticing a tiny built-in biological clock inside every sequencing read. When a gene switches on, RNA polymerase first transcribes raw unspliced pre-mRNA (\(u\)) containing non-coding introns, which the cell subsequently edits into mature spliced mRNA (\(s\)) before it eventually degrades.
- Think of filling a bathtub while the plug is slightly loose. Unspliced pre-mRNA \(u\) is the stream pouring from the tap at transcription rate \(\alpha(t)\), splicing moves water into the mature spliced pool \(s\) at rate \(\beta\), and mature mRNA drains away at degradation rate \(\gamma\). This gives a pair of coupled ordinary differential equations from Chapter 03.
- At steady state (\(\frac{ds}{dt} = 0\)), unspliced and spliced counts sit neatly along a straight diagonal line \(u = \frac{\gamma}{\beta} s\). If a cell sits above that diagonal (\(u > \frac{\gamma}{\beta} s\)), fresh unspliced transcripts are flooding in faster than mature ones are disappearing, giving positive velocity (\(\frac{ds}{dt} > 0\)) that predicts gene expression is rising. If a cell sits below the diagonal (\(u < \frac{\gamma}{\beta} s\)), transcription has switched off and mature mRNA is decaying (\(\frac{ds}{dt} < 0\)). Aggregating these velocities across all dynamic genes places directional arrows directly onto the UMAP manifold, revealing where each cell is heading over the next few hours.
Spatial Transcriptomics and Tissue Architecture¶
-
Dissociating a biopsy into a suspension of single cells solves the smoothie problem, yet it introduces a new blind spot. Imagine demolishing a medieval cathedral into a neat pile of numbered bricks. Even if you catalogue every single brick perfectly, you no longer know which stones formed the flying buttresses and which framed the stained-glass window.
-
Cells behave according to their neighbours. A killer T-cell parked inside the core of a solid tumour behaves completely differently from an identical T-cell trapped outside a fibrous barrier two millimetres away. Spatial transcriptomics preserves the physical \((x, y)\) or \((x, y, z)\) coordinates of gene expression right inside intact tissue slices, either by capturing mRNA onto spatially barcoded microarrays (such as Visium or Slide-seq) or by imaging fluorescent RNA probes directly under high-resolution microscopes (such as MERFISH and Xenium).
-
Computationally, spatial transcriptomics turns tissue into a spatial cellular graph where each node carries a gene expression vector and each edge connects physically adjacent cells. Applying Graph Neural Networks from Chapter 15 to these tissue graphs lets models learn ligand-receptor cell-to-cell signalling, map tumour-immune boundaries, and predict how local neighbourhoods drive tissue development and disease progression.
Perturbation Biology and Causal Response Prediction¶
-
Observing cells in their natural state teaches us correlation, just like watching traffic from a helicopter tells you which roads get busy together. To discover true biological cause and effect, scientists must intervene directly, knocking out a gene or adding a candidate drug and watching how the cell responds.
-
Perturb-seq pairs pooled CRISPR genetic edits with single-cell RNA sequencing. Thousands of cells each receive a tiny molecular barcode identifying which gene was knocked out alongside a full transcriptomic readout of how all \(20{,}000\) genes reacted. High-throughput chemical screens do the same for small-molecule drugs across dozens of cell types and dosages.
-
Even with robotic labs, testing every possible combination of \(20{,}000\) human genes, millions of drug-like compounds, hundreds of cell types, and pair-wise drug synergies is astronomically impossible. Machine learning tackles this combinatorial wall by treating a perturbation as a geometric transport map inside a learned low-dimensional latent space \(\mathbf{z} \in \mathbb{R}^d\).
-
In latent arithmetic approaches (such as scGen and CPA), an autoencoder compresses untreated and treated cells into a smooth latent space where applying perturbation \(p\) shifts a cell's representation by a learnable vector \(\boldsymbol{\delta}_p\). To predict how an unseen cell type \(B\) will respond to drug \(p\), we simply add the shift learned from cell type \(A\) to the untreated latent state of cell type \(B\) and decode back into gene space.
- Because different cells within a population can react heterogeneously rather than shifting rigidly in lockstep, Optimal Transport (OT) methods (such as CellOT and Monge-map neural networks) go a step further. Instead of matching single averages, they learn a minimal-cost coupling \(T_p\) that transports the entire probability distribution of untreated control cells onto the distribution of perturbed cells, capturing subtle shifts in variance, rare subpopulations, and branching drug resistance.
Foundation Models of the Cell and the AI Virtual Cell¶
-
Every gene inside a cell does not act in isolation. Genes talk to one another through intricate regulatory circuits, much like words acquire meaning from the grammar and context of a sentence. That observation sparked a wave of single-cell foundation models built on the Transformer architectures of Chapter 07.
-
Geneformer (Theodoris et al., 2023) converts each cell into a sequence of gene tokens ranked from highest to lowest normalised expression, pretraining a masked Transformer on roughly \(30\) million human single-cell profiles to predict masked genes from their regulatory context. scGPT (Cui et al., 2024) jointly embeds both gene identities and binned expression values using specialised generative attention over tens of millions of cells, enabling downstream cell-type annotation, multi-omic integration, and genetic perturbation prediction.
-
These models point toward one of the grandest ambitions in BioAI, the AI Virtual Cell (Bunne et al., 2024). Picture a flight simulator for living biology. Before a biologist ever picks up a pipette or spends months running wet-lab assays, they load a patient's single-cell and spatial profile into a universal multi-scale model that links molecules, gene regulatory networks, organelles, and tissue architecture.
-
Inside that simulator, researchers can test ten thousand CRISPR edits or drug combinations in silico in an afternoon, inspect predicted efficacy and off-target toxicity across healthy organs, and send only the top handful of candidates to real wet-lab validation. Each wet-lab result then flows back into the simulator in a tight active-learning loop, steadily turning cellular biology from trial-and-error alchemy into predictive engineering.
Take-Home¶
- Single-cell sequencing replaces a blended tissue smoothie with an inspectable fruit salad, preserving rare immune and drug-resistant tumour cells that bulk averaging silently erases.
- Careful preprocessing unlocks clean biological manifolds, combining library-size normalisation, \(\log(1+x)\) variance stabilisation, highly variable gene selection, PCA, Leiden graph clustering, and UMAP visualisation.
- RNA velocity adds time's arrow to static snapshots by contrasting fresh unspliced pre-mRNA against mature spliced mRNA via \(\frac{ds}{dt} = \beta u - \gamma s\), predicting each cell's near-future differentiation trajectory.
- Spatial transcriptomics and Perturb-seq add geometry and causality, mapping how cells communicate inside intact tissues and how CRISPR edits or drugs shift cellular states across latent space.
- Cellular foundation models such as Geneformer and scGPT lay the groundwork for an AI Virtual Cell capable of simulating unseen perturbations in silico before costly wet-lab experiments begin.
Coding Tasks (use CoLab or notebook)¶
-
Simulate a sparse scRNA-seq count matrix containing two abundant cell types plus a rare \(5\%\) tumour subpopulation across \(G=60\) genes with varying sequencing depths. Compare the bulk RNA-seq mean against single-cell library-size normalisation, \(\log(1+x)\) transformation, and SVD/PCA (Chapter 02), verifying that bulk averaging hides the tumour signature while single-cell PCA separates all three populations cleanly.
import jax import jax.numpy as jnp import matplotlib.pyplot as plt key = jax.random.PRNGKey(7) k1, k2, k3, k4 = jax.random.split(key, 4) # 3 cell populations: 190 Epithelial, 190 Immune, 20 Rare Tumour (5% of tissue) n_epi, n_imm, n_tum, G = 190, 190, 20, 60 N = n_epi + n_imm + n_tum # True baseline gene-rate profiles (distinct marker gene blocks + shared housekeeping) base = jnp.full((G,), 0.4) epi_rate = base + jnp.where((jnp.arange(G) >= 0) & (jnp.arange(G) < 15), 5.0, 0.0) imm_rate = base + jnp.where((jnp.arange(G) >= 15) & (jnp.arange(G) < 30), 5.0, 0.0) tum_rate = base + jnp.where((jnp.arange(G) >= 30) & (jnp.arange(G) < 42), 7.5, 0.0) rates = jnp.concatenate([ jnp.tile(epi_rate, (n_epi, 1)), jnp.tile(imm_rate, (n_imm, 1)), jnp.tile(tum_rate, (n_tum, 1)), ], axis=0) labels = jnp.concatenate([jnp.zeros(n_epi), jnp.ones(n_imm), jnp.full(n_tum, 2.0)]) # Variable sequencing library depth (0.4x to 2.5x) + technical dropout (~75% zeros) depths = jax.random.uniform(k1, (N, 1), minval=0.4, maxval=2.5) noisy_expr = jnp.maximum(0.0, rates * depths + 0.8 * jax.random.normal(k2, (N, G))) dropout_mask = (jax.random.uniform(k3, (N, G)) > 0.72).astype(jnp.float32) counts = jnp.round(noisy_expr * dropout_mask) # Bulk RNA-seq smoothie: average across all cells bulk_mean = jnp.mean(counts, axis=0) tumour_markers_in_bulk = float(jnp.mean(bulk_mean[30:42])) tumour_markers_in_clone = float(jnp.mean(counts[n_epi + n_imm:, 30:42])) print(f"Sparsity (fraction zero): {float(jnp.mean(counts == 0)):.1%}") print(f"Tumour marker mean -> Bulk average: {tumour_markers_in_bulk:.2f} vs True rare clone: {tumour_markers_in_clone:.2f}") # Single-cell pipeline: library-size normalisation -> log(1 + x) -> SVD/PCA lib_size = jnp.sum(counts, axis=1, keepdims=True) + 1e-6 X_norm = jnp.log1p(100.0 * counts / lib_size) X_centred = X_norm - jnp.mean(X_norm, axis=0, keepdims=True) U, S, Vt = jnp.linalg.svd(X_centred, full_matrices=False) pcs = X_centred @ Vt[:2].T fig, axes = plt.subplots(1, 2, figsize=(10.5, 4)) axes[0].bar(range(G), bulk_mean, color="#95a5a6", alpha=0.85, label="Bulk average") axes[0].axvspan(30, 41, color="#e74c3c", alpha=0.18, label="Tumour markers (30-41)") axes[0].set_xlabel("Gene Index"); axes[0].set_ylabel("Mean Raw Count") axes[0].set_title("Bulk RNA-seq Hides the Rare 5% Tumour Clone"); axes[0].legend(); axes[0].grid(alpha=0.3) colours = ["#3498db", "#27ae60", "#e74c3c"] names = ["Epithelial (47.5%)", "Immune (47.5%)", "Rare Tumour (5%)"] for c, col, name in zip([0, 1, 2], colours, names): m = labels == c axes[1].scatter(pcs[m, 0], pcs[m, 1], s=26, alpha=0.8, color=col, label=name) axes[1].set_xlabel("PC 1"); axes[1].set_ylabel("PC 2") axes[1].set_title("scRNA-seq Normalised PCA Manifold"); axes[1].legend(); axes[1].grid(alpha=0.3) plt.tight_layout(); plt.show() -
Simulate RNA velocity splicing kinetics (\(\frac{du}{dt} = \alpha(t) - \beta u\) and \(\frac{ds}{dt} = \beta u - \gamma s\)) over an induction-then-repression cycle, estimate the steady-state ratio \(\hat{\gamma} = \gamma / \beta\) from extreme quantiles of the noisy cells, and visualise both the classic unspliced-versus-spliced phase portrait and predicted velocity arrows.
import jax import jax.numpy as jnp import matplotlib.pyplot as plt key = jax.random.PRNGKey(12) k1, k2 = jax.random.split(key) # Simulate exact Euler trajectory: induction (t < 6) then repression (t >= 6) beta, gamma, dt, steps = 0.9, 0.55, 0.05, 260 u_val, s_val = 0.0, 0.0 u_list, s_list, t_list, phase_list = [], [], [], [] for step in range(steps): t = step * dt alpha = 4.0 if t < 6.0 else 0.0 du = alpha - beta * u_val ds = beta * u_val - gamma * s_val u_val = max(0.0, u_val + dt * du) s_val = max(0.0, s_val + dt * ds) u_list.append(u_val); s_list.append(s_val); t_list.append(t) phase_list.append(1.0 if t < 6.0 else 0.0) u_true, s_true = jnp.array(u_list), jnp.array(s_list) t_arr, phase = jnp.array(t_list), jnp.array(phase_list) # Add single-cell measurement noise u_obs = jnp.maximum(0.0, u_true + 0.18 * jax.random.normal(k1, (steps,))) s_obs = jnp.maximum(0.0, s_true + 0.18 * jax.random.normal(k2, (steps,))) # Estimate steady-state slope gamma_hat = gamma / beta from top 10% highest-expression cells q90 = jnp.quantile(s_obs, 0.90) top_mask = s_obs >= q90 gamma_hat = jnp.sum(u_obs * s_obs * top_mask) / (jnp.sum((s_obs ** 2) * top_mask) + 1e-6) v_est = u_obs - gamma_hat * s_obs # Proportional to ds/dt (velocity in spliced space) true_v = beta * u_true - gamma * s_true corr = jnp.corrcoef(v_est, true_v)[0, 1] print(f"True ratio gamma/beta: {gamma/beta:.3f} | Estimated steady-state slope: {float(gamma_hat):.3f}") print(f"Correlation between estimated and true RNA velocity: {float(corr):.4f}") fig, axes = plt.subplots(1, 2, figsize=(10.5, 4)) sc = axes[0].scatter(s_obs, u_obs, c=v_est, cmap="coolwarm", s=22, alpha=0.85, vmin=-2.5, vmax=2.5) s_grid = jnp.linspace(0.0, float(jnp.max(s_obs)), 50) axes[0].plot(s_grid, gamma_hat * s_grid, "k--", lw=1.8, label=f"Steady state u = {float(gamma_hat):.2f} s") # Quiver arrows along sampled snapshots showing predicted direction of spliced mRNA idx = jnp.arange(8, steps, 22) axes[0].quiver(s_obs[idx], u_obs[idx], v_est[idx], jnp.zeros_like(idx), color="#333", scale=18, width=0.006) plt.colorbar(sc, ax=axes[0], label="Estimated Velocity v") axes[0].set_xlabel("Spliced mRNA (s)"); axes[0].set_ylabel("Unspliced pre-mRNA (u)") axes[0].set_title("RNA Velocity Phase Portrait"); axes[0].legend(); axes[0].grid(alpha=0.3) axes[1].plot(t_arr, s_true, color="#3498db", lw=2.2, label="True spliced s(t)") axes[1].plot(t_arr, u_true, color="#27ae60", lw=2.2, linestyle="--", label="True unspliced u(t)") axes[1].plot(t_arr, v_est, color="#e74c3c", lw=1.6, alpha=0.8, label="Estimated velocity v(t)") axes[1].axvline(6.0, color="#666", linestyle=":", label="Transcription off") axes[1].set_xlabel("Biological Time t"); axes[1].set_ylabel("Level / Velocity") axes[1].set_title("Unspliced Peaks Ahead of Spliced mRNA"); axes[1].legend(); axes[1].grid(alpha=0.3) plt.tight_layout(); plt.show() -
Build a virtual-cell latent perturbation model (inspired by scGen) in JAX. Train a nonlinear autoencoder on Cell Type A (untreated and drug-treated) plus Cell Type B (untreated only), compute the latent drug shift vector \(\boldsymbol{\delta}_{\text{drug}}\), and perform zero-shot prediction of how Cell Type B responds to the unseen drug.
import jax import jax.numpy as jnp import matplotlib.pyplot as plt key = jax.random.PRNGKey(99) k1, k2, k3, k4, k5 = jax.random.split(key, 5) N_grp, G, D_lat, H = 80, 24, 4, 16 def softplus(x): return jnp.log1p(jnp.exp(jnp.clip(x, -20.0, 20.0))) # Ground-truth nonlinear gene manifold: latent cell identity + distinct drug response W_true = jax.random.normal(k1, (D_lat, G)) * 0.8 drug_shift_true = jnp.array([2.4, -2.1, 1.8, -1.4]) def make_cells(subkey, centre): z = centre + 0.30 * jax.random.normal(subkey, (N_grp, D_lat)) return softplus(z @ W_true + 1.0) z_A_ctrl = jnp.array([-1.2, 0.7, -0.5, 0.3]) z_B_ctrl = jnp.array([1.1, -0.6, 0.7, -0.4]) X_A_ctrl = make_cells(k2, z_A_ctrl) X_A_drug = make_cells(k3, z_A_ctrl + drug_shift_true) X_B_ctrl = make_cells(k4, z_B_ctrl) X_B_drug_true = make_cells(k5, z_B_ctrl + drug_shift_true) # Held out completely! # Training set NEVER sees Cell Type B + drug X_train = jnp.concatenate([X_A_ctrl, X_A_drug, X_B_ctrl], axis=0) N_tr = X_train.shape[0] # Compact nonlinear autoencoder trained with analytical backprop (Pyodide-fast & JAX-exact) kp = jax.random.split(jax.random.PRNGKey(5), 4) We1, be1 = jax.random.normal(kp[0], (G, H)) * 0.15, jnp.zeros(H) We2, be2 = jax.random.normal(kp[1], (H, D_lat)) * 0.15, jnp.zeros(D_lat) Wd1, bd1 = jax.random.normal(kp[2], (D_lat, H)) * 0.15, jnp.zeros(H) Wd2, bd2 = jax.random.normal(kp[3], (H, G)) * 0.15, jnp.zeros(G) def encode(x): return jnp.tanh(x @ We1 + be1) @ We2 + be2 def decode(z): return softplus(z @ Wd1 @ Wd2 + bd2) lr = 0.12 for _ in range(700): he = jnp.tanh(X_train @ We1 + be1) z = he @ We2 + be2 hd = z @ Wd1 pre_out = hd @ Wd2 + bd2 x_hat = softplus(pre_out) d_out = (2.0 / (N_tr * G)) * (x_hat - X_train) * jax.nn.sigmoid(pre_out) dWd2, dbd2 = hd.T @ d_out, jnp.sum(d_out, axis=0) d_hd = d_out @ Wd2.T dWd1 = z.T @ d_hd d_z = d_hd @ Wd1.T dWe2, dbe2 = he.T @ d_z, jnp.sum(d_z, axis=0) d_he = (d_z @ We2.T) * (1.0 - he ** 2) dWe1, dbe1 = X_train.T @ d_he, jnp.sum(d_he, axis=0) We1, be1 = We1 - lr * dWe1, be1 - lr * dbe1 We2, be2 = We2 - lr * dWe2, be2 - lr * dbe2 Wd1 = Wd1 - lr * dWd1 Wd2, bd2 = Wd2 - lr * dWd2, bd2 - lr * dbd2 # Latent arithmetic: transfer drug shift from Cell A onto unseen Cell B delta_drug = jnp.mean(encode(X_A_drug), axis=0) - jnp.mean(encode(X_A_ctrl), axis=0) X_B_drug_pred = decode(encode(X_B_ctrl) + delta_drug) # Compare predicted vs true mean gene expression on the held-out combination true_mean = jnp.mean(X_B_drug_true, axis=0) pred_mean = jnp.mean(X_B_drug_pred, axis=0) ctrl_mean = jnp.mean(X_B_ctrl, axis=0) r2_pred = float(jnp.corrcoef(true_mean, pred_mean)[0, 1] ** 2) r2_ctrl = float(jnp.corrcoef(true_mean, ctrl_mean)[0, 1] ** 2) print(f"Unseen Cell B + Drug gene correlation R^2 -> Baseline (untreated): {r2_ctrl:.3f} | Virtual Cell: {r2_pred:.3f}") fig, axes = plt.subplots(1, 2, figsize=(10.5, 4)) axes[0].scatter(true_mean, pred_mean, color="#27ae60", s=50, alpha=0.85, label=f"Virtual Cell (R^2={r2_pred:.2f})") axes[0].scatter(true_mean, ctrl_mean, color="#e74c3c", marker="x", s=45, alpha=0.7, label=f"Untreated baseline (R^2={r2_ctrl:.2f})") lim = [0.0, float(jnp.max(true_mean)) + 0.5] axes[0].plot(lim, lim, "k--", lw=1.2) axes[0].set_xlabel("True Held-Out Gene Mean (Cell B + Drug)"); axes[0].set_ylabel("Predicted Gene Mean") axes[0].set_title("Zero-Shot Perturbation Prediction"); axes[0].legend(); axes[0].grid(alpha=0.3) # Latent space view (first 2 latent dims) for data, col, lbl in [(X_A_ctrl, "#3498db", "Cell A ctrl"), (X_A_drug, "#27ae60", "Cell A + drug"), (X_B_ctrl, "#9b59b6", "Cell B ctrl"), (X_B_drug_true, "#f39c12", "Cell B + drug (true)"), (X_B_drug_pred, "#e74c3c", "Cell B + drug (pred)")]: z_vis = encode(data) axes[1].scatter(z_vis[:, 0], z_vis[:, 1], s=20, alpha=0.7, color=col, label=lbl) axes[1].set_xlabel("Latent Dim 1"); axes[1].set_ylabel("Latent Dim 2") axes[1].set_title("Latent Arithmetic Across Cell Types"); axes[1].legend(fontsize=8); axes[1].grid(alpha=0.3) plt.tight_layout(); plt.show()