Algorithmresearch
RNA velocity
Also called scVelo dynamical model.
Estimate the time derivative of expression of each gene from unspliced and spliced counts with a model of splicing and degradation.
- Solves
- Trajectory inference
- Time
- O(g n log n) worst
- Space
- O(g n) extra
- Where
- g = the number of genes; n = the number of cells
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Gioele La Manno, Ruslan Soldatov, Sten Linnarsson, Peter V. Kharchenko, 2018
RNA velocity estimates, for each cell and each gene, how fast the amount of mature RNA is changing. A cell holds both newly made RNA that still has introns (unspliced) and mature RNA (spliced). If a gene was switched on recently, a cell has more unspliced RNA than its spliced RNA would need at balance, and if it was switched off, less. La Manno and co-authors (2018) turned this into a model with three rates and a velocity for each gene. The velocities of all genes point from the current state of the cell toward its state in the near future, which gives a direction to the trajectory inference problem. This page covers the steady-state model and states what it leaves out. The algebra of the model is proved; the claim that the fitted velocities follow the real process is a heuristic.
In plain words
A cell makes copies of a gene's message as rough drafts. The drafts are cleaned into final copies, and the final copies wear out. When a gene has just turned on, there are many drafts and few final copies. When it has just turned off, there are few drafts but many old final copies. When nothing has changed for a long time, the two stay in a fixed proportion. Learn that proportion from the cells that seem settled. Then, for every cell, the gap between its drafts and the drafts that its final copies would need tells you whether the gene is going up or down, and how fast.
The problem
Input. For cells and genes, the unspliced counts and the spliced counts , usually from reads that fall in introns and in exons, normalized for library size. A fraction of cells to treat as near steady state at each end.
Output. A ratio for each gene and a velocity for each cell and gene.
Model. For one gene, with transcription rate , splicing rate and degradation rate : and . The steady-state model takes to be the same for every gene and measures time in units of it.
The algorithm
RNA-VELOCITY(u, s, q)- 1
for each gene g: C ← the ⌈qn⌉ cells with the smallest s_ig and the ⌈qn⌉ with the largest - 2
γ_g ← Σ_{i ∈ C} u_ig s_ig / Σ_{i ∈ C} s_ig² ▷ least squares through the origin - 3
v_ig ← u_ig - γ_g s_ig for every cell i - 4
ŝ_i ← s_i + Δ v_i ▷ the predicted state after a short time Δ
Line L1 takes the cells at the two ends of the spliced counts as the cells closest to the off and the on steady states. Line L2 fits the line through them by ordinary least squares with no intercept. Line L3 is the distance of each cell above or below that line, which is when is right. Line L4 moves each cell a short way along its velocity. The real tools then compare with the other cells to draw arrows on a UMAP or other display.
Example
One gene with , and . The on steady state is . Ten cells: one off, four at times 0.5, 1, 2 and 10 after the gene is switched on, four at the same times after it is switched off from the on state, and one on.
| cell | off | on 0.5 | on 1 | on 2 | on 10 | off 0.5 | off 1 | off 2 | off 10 | on |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 0.787 | 1.264 | 1.729 | 2.000 | 1.213 | 0.736 | 0.271 | 0.000 | 2 | |
| 0 | 0.196 | 0.619 | 1.598 | 3.946 | 3.804 | 3.381 | 2.402 | 0.054 | 4 | |
| 0 | 0.689 | 0.955 | 0.930 | 0.027 | -0.689 | -0.955 | -0.930 | -0.027 | 0 |
With , line L1 picks the off cell and the on cell, and line L2 gives exactly. The velocities are positive while the gene goes up and negative while it goes down, and the two phases mirror each other. With the fit also uses the cells at times 10, and gives 0.503. With all cells it gives 0.413, because the cells that are still changing pull the line.
Correctness
The proof gives the exact solution of the model, also for , and shows that every solution tends to a steady state on the line . It shows that with the true ratio, the velocity is positive at all times after a gene is switched on from zero and negative at all times after it is switched off from its on state, and that the two phases mirror each other. The fit of line L2 is exact when the chosen cells lie on the line. The step of line L4 has an error of order . On noisy data the quality is a measurement: in the tests, with 20 genes, 300 cells over an on and an off phase and Gaussian noise of 10 percent, the median relative error of is 0.11 at , and 94 percent of the cells with a clear velocity get the right sign.
Proof: The splicing model has an exact solution, steady states lie on a line, and the steady-state velocity has the right signfull
We prove what the steady-state model computes, for one gene. The splicing model has a closed-form solution (Theorem 1). Its steady states lie on the line (Lemma 2). With the true ratio, the velocity is , it is positive while the gene is switched on from zero and negative while it is switched off from its on state (Theorem 3). The fit of lines L1 and L2 is exact when the chosen cells lie on the steady-state line (Theorem 5), and the step of line L4 has an error of order (Lemma 6). Real cells are not all at steady state at the extremes, counts are noisy, and genes do not all follow one switch; so the quality of the estimate on data is measured, not proved.
Setting. One gene in one cell, with unspliced count and spliced count , and rates (transcription), (splicing) and (degradation):
The steady-state model takes to be the same for all genes and measures time in units of , so its ratio is . Line L1 chooses the cells whose is among the smallest or the largest. Line L2 sets over the chosen cells. Line L3 sets , and line L4 sets .
Theorem 1 (solution). With a constant and start , and, for ,
and for , .
Proof. Both formulas give and . For : . For write , so that . The terms and contribute and to . When , , so the last term, with , contributes , as needed. When , , so the last term contributes . A linear equation with a given start has only one solution.
Lemma 2 (steady state). The only fixed point is , which lies on the line , and every solution tends to it.
Proof. Setting both derivatives to 0 gives and . All exponentials in Theorem 1 tend to 0, and so does .
So a cell whose gene has been on for a long time sits at the upper end of the line, and a cell whose gene has been off for a long time sits near the origin, which is also on the line.
Theorem 3 (sign). Let . If the gene starts at with , then for all . If it starts at the on state with and is switched off (), then for all . The velocity of line L3 with is , with the same sign.
Proof. In both cases , and , so . In the first case for every by Theorem 1, so the integrand is positive. In the second case and , so the integrand is negative. Finally .
Lemma 4 (mirror). With fixed, the path switched off from the on state of is the on state minus the path switched on from with , at the same times. So their velocities are opposite.
Proof. Let solve the on path. Then starts at the on state, and its derivatives are and , which is the off model with . Its is .
Theorem 5 (fit). of line L2 minimizes over , for the chosen cells. If every chosen cell lies on the line and not every chosen is 0, then .
Proof. The sum is a quadratic in with second derivative and derivative , which is 0 only at . If for all chosen cells, the sum is 0 at , so that is the minimum.
When some chosen cells are still on their way to a steady state, the fit is biased. Cells being switched on lie above the line and cells being switched off lie below it (Theorem 3), and the fit weights each cell by . In the page example the fit over all cells gives 0.413 for a true 0.5.
Lemma 6 (extrapolation). If and , then for some between and .
Proof. by Theorem 3, and this is Taylor's theorem with the Lagrange remainder; is smooth by Theorem 1.
What the lines compute. Line L1 picks the cells taken to be near the off and on steady states. Line L2 is Theorem 5. Line L3 is the velocity of Theorem 3, in units of . Line L4 is Lemma 6. This page does not pool counts over neighbor cells, fit the rates of each gene by the dynamical model of Bergen and co-authors (2020), or project the velocities onto an embedding; Theorems 1 and 3 are the model that the dynamical fit uses, but the fit itself is not here.
Complexity. For cells and genes, line L1 sorts each gene in time and lines L2 to L4 take per gene, so the total time is and the space is for the velocities.
What the tests check. The test file checks the page example, Theorem 1 against a fourth-order Runge-Kutta solution in both cases of and , Lemma 2, Theorem 3 on random rates, Lemma 4, Theorem 5 with steady cells at the extremes, and the order of Lemma 6. One simulation is a measurement, not a theorem: 20 genes and 300 cells over an on and an off phase with Gaussian noise, where the test checks the median error of and the share of cells with a clear velocity whose sign is right.
Complexity
Line L1 sorts the cells for each gene in time, and lines L2 to L4 take per gene, so the time is and the space . In real tools, the pooling of counts over neighbors and the projection onto a display cost more than this.
Properties
- Per gene. Each gene is fitted on its own; no gene borrows strength from another.
- Gives a direction. Unlike a pseudotime, the velocity says which way a cell is moving, so it can choose the root of a trajectory.
- Short horizon. The velocity describes the near future of a cell, of the order of the lifetime of the mRNA.
- Assumes steady states. The fit needs cells near both steady states of each gene.
- One splicing rate. All genes share one , so is a ratio, not a rate.
Variants and improvements
- Dynamical model. Bergen and co-authors (2020) fit , , and a switching time for each gene, and a time for each cell, by expectation maximization on the solution of the model. This removes the need for cells at steady state and gives a latent time. It is not on this page.
- Stochastic model. Uses the second moments of the counts as well as the means.
- Neighbor pooling. Averages the counts of each cell over its nearest neighbors on a k-nearest-neighbor graph before the fit, to reduce noise; not on this page.
- Velocity on a display. Turns into transition probabilities to the other cells and draws them as arrows; not on this page.
- Pseudotime. Diffusion pseudotime and minimum spanning tree pseudotime give an order but no direction; velocity can choose their root.
When to use it
Use it when the data hold unspliced and spliced counts, the cells change during the time of the sample, and you want to know which way the cells move. Check the fit on a few genes with a plot of against before you trust the arrows.
Pitfalls
- No steady states. If a gene never settles, the extreme cells are not on the line and is biased; the example shows how much the changing cells pull the line.
- Different rates. Genes with two transcription rates in two cell types, or a splicing rate that differs from the others, break the model.
- Noise. Unspliced counts are low; in the tests, cells with a velocity near 0 get the wrong sign often.
- Arrows on a display. The projection of high dimensional velocities onto a two dimensional display can show directions that are not in the data.
- Normalization. The counts must be normalized the same way for and .
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/rna-velocity/. The authors are listed in prov/MT9F81.jsonl.
"""RNA velocity with the steady-state model, small and dense.
The model of one gene in one cell, with time in units of the splicing rate
(beta = 1 unless given):
du/dt = alpha - beta u (unspliced: made at rate alpha, spliced at rate beta)
ds/dt = beta u - gamma s (spliced: made from u, degraded at rate gamma)
At a steady state u = (gamma / beta) s. The steady-state model (La Manno et al.
2018) fits the ratio gamma' = gamma / beta for each gene by least squares
through the origin on the cells with the smallest and the largest spliced
counts, which it takes to be near the two steady states, and sets the velocity
of a cell to v = u - gamma' s, which is ds/dt in units of beta.
What this version leaves out: the pooling of counts over nearest neighbors
(the moments), the dynamical model of scVelo (Bergen et al. 2020) fitted by
expectation maximization, the stochastic model, the transition probabilities
between cells, and the projection of the velocities onto an embedding.
"""
from __future__ import annotations
import math
from typing import List, Sequence, Tuple
def solution(alpha: float, beta: float, gamma: float, u0: float, s0: float, t: float) -> Tuple[float, float]:
"""The exact (u, s) after time t from (u0, s0) with a constant alpha."""
if beta <= 0 or gamma <= 0:
raise ValueError("beta and gamma must be positive")
eb, eg = math.exp(-beta * t), math.exp(-gamma * t)
u = u0 * eb + alpha / beta * (1 - eb)
if math.isclose(beta, gamma, rel_tol=1e-12, abs_tol=0.0):
s = s0 * eg + alpha / gamma * (1 - eg) + (beta * u0 - alpha) * t * eg
else:
s = s0 * eg + alpha / gamma * (1 - eg) + (alpha - beta * u0) / (gamma - beta) * (eg - eb)
return u, s
def fit_gamma(u: Sequence[float], s: Sequence[float], q: float = 0.05) -> float:
"""gamma' by least squares through the origin on the cells in the lowest and highest q fraction of s."""
n = len(s)
if n != len(u) or n == 0:
raise ValueError("u and s must have the same nonzero length")
if not 0 < q <= 0.5:
raise ValueError("q must be in (0, 0.5]")
m = max(1, math.ceil(q * n))
order = sorted(range(n), key=lambda i: (s[i], i))
chosen = sorted(set(order[:m]) | set(order[n - m:])) # @line L1
ss = sum(s[i] * s[i] for i in chosen)
if ss == 0.0:
raise ValueError("the chosen cells have no spliced counts")
return sum(u[i] * s[i] for i in chosen) / ss # @line L2
def velocity(U: Sequence[Sequence[float]], S: Sequence[Sequence[float]], q: float = 0.05) -> Tuple[List[float], List[List[float]]]:
"""Per-gene gamma' and the cells by genes matrix of velocities. U and S are cells by genes."""
n, g = len(S), len(S[0])
gammas = [fit_gamma([U[i][j] for i in range(n)], [S[i][j] for i in range(n)], q) for j in range(g)]
V = [[U[i][j] - gammas[j] * S[i][j] for j in range(g)] for i in range(n)] # @line L3
return gammas, V
def extrapolate(S: Sequence[Sequence[float]], V: Sequence[Sequence[float]], dt: float) -> List[List[float]]:
"""The predicted spliced state after a short time dt: s + dt v."""
return [[s + dt * v for s, v in zip(rs, rv)] for rs, rv in zip(S, V)] # @line L4
test_rna_velocity.py 151 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/rna-velocity/. The authors are listed in prov/MT9F81.jsonl.
import math
import random
import pytest
from rna_velocity import extrapolate, fit_gamma, solution, velocity
ALPHA, BETA, GAMMA = 2.0, 1.0, 0.5
def rk4(alpha, beta, gamma, u, s, t, steps=2000):
h = t / steps
def f(u, s):
return alpha - beta * u, beta * u - gamma * s
for _ in range(steps):
k1 = f(u, s)
k2 = f(u + h / 2 * k1[0], s + h / 2 * k1[1])
k3 = f(u + h / 2 * k2[0], s + h / 2 * k2[1])
k4 = f(u + h * k3[0], s + h * k3[1])
u += h / 6 * (k1[0] + 2 * k2[0] + 2 * k3[0] + k4[0])
s += h / 6 * (k1[1] + 2 * k2[1] + 2 * k3[1] + k4[1])
return u, s
def page_cells():
cells = [(0.0, 0.0)]
cells += [solution(ALPHA, BETA, GAMMA, 0, 0, t) for t in (0.5, 1, 2, 10)]
cells += [solution(0, BETA, GAMMA, ALPHA / BETA, ALPHA / GAMMA, t) for t in (0.5, 1, 2, 10)]
cells.append((ALPHA / BETA, ALPHA / GAMMA))
return cells
def test_page_example():
cells = page_cells()
u = [c[0] for c in cells]
s = [c[1] for c in cells]
assert fit_gamma(u, s, 0.1) == pytest.approx(0.5, abs=1e-12)
assert fit_gamma(u, s, 0.2) == pytest.approx(0.5033, abs=5e-5)
assert fit_gamma(u, s, 0.5) == pytest.approx(0.4129, abs=5e-5)
_, V = velocity([[x] for x in u], [[y] for y in s], 0.1)
v = [row[0] for row in V]
want = [0.0, 0.689, 0.955, 0.930, 0.027, -0.689, -0.955, -0.930, -0.027, 0.0]
assert all(math.isclose(a, b, abs_tol=5e-4) for a, b in zip(v, want))
def test_solution_matches_rk4():
rng = random.Random(1)
for _ in range(20):
a, b, g = rng.uniform(0, 5), rng.uniform(0.2, 3), rng.uniform(0.2, 3)
u0, s0, t = rng.uniform(0, 3), rng.uniform(0, 3), rng.uniform(0, 5)
assert solution(a, b, g, u0, s0, t) == pytest.approx(rk4(a, b, g, u0, s0, t), abs=1e-9)
# The case beta = gamma has its own formula.
for g in (0.3, 1.0, 2.5):
assert solution(1.5, g, g, 0.4, 0.9, 3.0) == pytest.approx(rk4(1.5, g, g, 0.4, 0.9, 3.0), abs=1e-9)
def test_steady_state_limit():
u, s = solution(ALPHA, BETA, GAMMA, 0.3, 7.0, 60.0)
assert u == pytest.approx(ALPHA / BETA, abs=1e-9)
assert s == pytest.approx(ALPHA / GAMMA, abs=1e-9)
assert u - GAMMA / BETA * s == pytest.approx(0.0, abs=1e-9)
def test_sign_of_velocity_in_the_two_phases():
rng = random.Random(2)
for _ in range(20):
a, g = rng.uniform(0.5, 5), rng.uniform(0.2, 3)
for t in (0.01, 0.3, 1.0, 4.0, 15.0):
u, s = solution(a, 1.0, g, 0, 0, t)
assert u - g * s > 0
u, s = solution(0, 1.0, g, a, a / g, t)
assert u - g * s < 0
def test_repression_mirrors_induction():
for t in (0.2, 1.0, 3.0):
ui, si = solution(ALPHA, BETA, GAMMA, 0, 0, t)
ur, sr = solution(0, BETA, GAMMA, ALPHA / BETA, ALPHA / GAMMA, t)
assert ur == pytest.approx(ALPHA / BETA - ui)
assert sr == pytest.approx(ALPHA / GAMMA - si)
def test_fit_is_exact_when_extreme_cells_are_at_steady_state():
rng = random.Random(3)
for _ in range(20):
g = rng.uniform(0.1, 3)
hi = rng.uniform(1, 10)
s = [0.0, 0.0, hi, hi] + [rng.uniform(0.1, hi * 0.9) for _ in range(16)]
u = [0.0, 0.0, g * hi, g * hi] + [rng.uniform(0, 5) for _ in range(16)]
assert fit_gamma(u, s, 0.1) == pytest.approx(g, rel=1e-12)
# The fit is the least squares slope through the origin.
chosen = [0, 1, 2, 3]
best = fit_gamma(u, s, 0.1)
for d in (-1e-3, 1e-3):
assert sum((u[i] - (best + d) * s[i]) ** 2 for i in chosen) > sum((u[i] - best * s[i]) ** 2 for i in chosen)
def test_velocity_is_ds_dt_and_extrapolation_is_first_order():
for t in (0.5, 2.0):
u, s = solution(ALPHA, 1.0, GAMMA, 0, 0, t)
v = u - GAMMA * s
errs = []
for dt in (0.1, 0.05, 0.025):
_, s2 = solution(ALPHA, 1.0, GAMMA, 0, 0, t + dt)
pred = extrapolate([[s]], [[v]], dt)[0][0]
errs.append(abs(s2 - pred))
# Halving dt divides the error by about 4.
assert 3.5 < errs[0] / errs[1] < 4.5 and 3.5 < errs[1] / errs[2] < 4.5
def test_simulation_measured():
"""A measurement: 20 genes, 300 cells over an on and an off phase, Gaussian noise of 10 percent."""
rng = random.Random(1)
genes, ncells = 20, 300
times = [rng.uniform(0, 20) for _ in range(ncells)]
U = [[0.0] * genes for _ in range(ncells)]
S = [[0.0] * genes for _ in range(ncells)]
D = [[0.0] * genes for _ in range(ncells)]
true = []
for j in range(genes):
a, g = rng.uniform(1, 5), rng.uniform(0.3, 1.5)
true.append(g)
uon, son = solution(a, 1, g, 0, 0, 10.0)
for i, t in enumerate(times):
uu, ss = solution(a, 1, g, 0, 0, t) if t < 10 else solution(0, 1, g, uon, son, t - 10)
D[i][j] = uu - g * ss
U[i][j] = max(0.0, uu + rng.gauss(0, 0.1 * a))
S[i][j] = max(0.0, ss + rng.gauss(0, 0.1 * a / g))
gammas, V = velocity(U, S, 0.1)
rel = sorted(abs(x - y) / y for x, y in zip(gammas, true))
assert rel[len(rel) // 2] < 0.2
big = [(i, j) for j in range(genes) for i in range(ncells)
if abs(D[i][j]) > 0.2 * max(abs(D[k][j]) for k in range(ncells))]
agree = sum((V[i][j] > 0) == (D[i][j] > 0) for i, j in big) / len(big)
assert agree > 0.9
def test_errors():
with pytest.raises(ValueError):
solution(1, 0, 1, 0, 0, 1)
with pytest.raises(ValueError):
fit_gamma([1, 2], [1], 0.1)
with pytest.raises(ValueError):
fit_gamma([1, 2], [1, 2], 0.0)
with pytest.raises(ValueError):
fit_gamma([0, 0], [0, 0], 0.5)
History
The model of transcription, splicing and degradation of one gene is a pair of linear differential equations. La Manno and co-authors (2018) used it with the steady-state fit to give each single cell a velocity and a predicted future state, in the velocyto software. Bergen and co-authors (2020) fitted the full kinetics of each gene in scVelo and showed that this works also for genes that do not reach a steady state.
References
- Gioele La Manno et al., RNA velocity of single cells, Nature 560(7719), 494 to 498 (2018), the model of transcription, splicing and degradation, the steady-state fit of the degradation ratio for each gene, and the extrapolation of the future state of a cell
- Volker Bergen, Marius Lange, Stefan Peidli, F. Alexander Wolf and Fabian J. Theis, Generalizing RNA velocity to transient cell states through dynamical modeling, Nature Biotechnology 38(12), 1408 to 1414 (2020), the dynamical model fitted by expectation maximization, the latent time, and the comparison with the steady-state model
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag MT9F81 Edit this page History Report an error Markdown