Algorithm Search⌘K

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.

Time
O(g n log n) worst
Space
O(g n) extra
Where
g = the number of genes; n = the number of cells
Properties
deterministicnot exactofflineiterative
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 v=u−γsv = u - \gamma s 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 nn cells and gg genes, the unspliced counts uigu_{ig} and the spliced counts sigs_{ig}, usually from reads that fall in introns and in exons, normalized for library size. A fraction qq of cells to treat as near steady state at each end.

Output. A ratio γ^g\hat\gamma_g for each gene and a velocity vigv_{ig} for each cell and gene.

Model. For one gene, with transcription rate α\alpha, splicing rate β\beta and degradation rate γ\gamma: du/dt=α−βudu/dt = \alpha - \beta u and ds/dt=βu−γsds/dt = \beta u - \gamma s. The steady-state model takes β\beta to be the same for every gene and measures time in units of it.

The algorithm

  1. RNA-VELOCITY(u, s, q)
  2. 1for each gene g: C ← the ⌈qn⌉ cells with the smallest s_ig and the ⌈qn⌉ with the largest
  3. 2γ_g ← Σ_{i ∈ C} u_ig s_ig / Σ_{i ∈ C} s_ig² ▷ least squares through the origin
  4. 3v_ig ← u_ig - γ_g s_ig for every cell i
  5. 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 u=γsu = \gamma s through them by ordinary least squares with no intercept. Line L3 is the distance of each cell above or below that line, which is ds/dtds/dt when γ\gamma is right. Line L4 moves each cell a short way along its velocity. The real tools then compare s^i\hat s_i with the other cells to draw arrows on a UMAP or other display.

Example

One gene with α=2\alpha = 2, β=1\beta = 1 and γ=0.5\gamma = 0.5. The on steady state is (u,s)=(2,4)(u, s) = (2, 4). 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
uu 0 0.787 1.264 1.729 2.000 1.213 0.736 0.271 0.000 2
ss 0 0.196 0.619 1.598 3.946 3.804 3.381 2.402 0.054 4
vv 0 0.689 0.955 0.930 0.027 -0.689 -0.955 -0.930 -0.027 0

With q=0.1q = 0.1, line L1 picks the off cell and the on cell, and line L2 gives γ^=0.5\hat\gamma = 0.5 exactly. The velocities are positive while the gene goes up and negative while it goes down, and the two phases mirror each other. With q=0.2q = 0.2 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 β=γ\beta = \gamma, and shows that every solution tends to a steady state on the line u=(γ/β)su = (\gamma/\beta)s. 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 Δ2\Delta^2. 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 γ^\hat\gamma is 0.11 at q=0.1q = 0.1, 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 u=(γ/β)su = (\gamma/\beta)s (Lemma 2). With the true ratio, the velocity u−(γ/β)su - (\gamma/\beta)s is 1βdsdt\frac{1}{\beta}\frac{ds}{dt}, 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 Δ2\Delta^2 (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 uu and spliced count ss, and rates α≥0\alpha \ge 0 (transcription), β>0\beta > 0 (splicing) and γ>0\gamma > 0 (degradation):

dudt=α−βu,dsdt=βu−γs.\frac{du}{dt} = \alpha - \beta u, \qquad \frac{ds}{dt} = \beta u - \gamma s.

The steady-state model takes β\beta to be the same for all genes and measures time in units of 1/β1/\beta, so its ratio is γ′=γ/β\gamma' = \gamma/\beta. Line L1 chooses the cells whose ss is among the m=⌈qn⌉m = \lceil qn\rceil smallest or the mm largest. Line L2 sets γ^=∑uisi/∑si2\hat\gamma = \sum u_is_i/\sum s_i^2 over the chosen cells. Line L3 sets vi=ui−γ^siv_i = u_i - \hat\gamma s_i, and line L4 sets s^i=si+Δvi\hat s_i = s_i + \Delta v_i.

Theorem 1 (solution). With a constant α\alpha and start (u0,s0)(u_0, s_0), u(t)=u0e−βt+αβ(1−e−βt)u(t) = u_0e^{-\beta t} + \frac{\alpha}{\beta}(1 - e^{-\beta t}) and, for β≠γ\beta \ne \gamma,

s(t)=s0e−γt+αγ(1−e−γt)+α−βu0γ−β(e−γt−e−βt),s(t) = s_0e^{-\gamma t} + \frac{\alpha}{\gamma}(1 - e^{-\gamma t}) + \frac{\alpha - \beta u_0}{\gamma - \beta}\left(e^{-\gamma t} - e^{-\beta t}\right),

and for β=γ\beta = \gamma, s(t)=s0e−γt+αγ(1−e−γt)+(βu0−α)te−γts(t) = s_0e^{-\gamma t} + \frac{\alpha}{\gamma}(1 - e^{-\gamma t}) + (\beta u_0 - \alpha)te^{-\gamma t}.

Proof. Both formulas give u(0)=u0u(0) = u_0 and s(0)=s0s(0) = s_0. For uu: u′=−βu0e−βt+αe−βt=α−βuu' = -\beta u_0e^{-\beta t} + \alpha e^{-\beta t} = \alpha - \beta u. For ss write u=αβ+(u0−αβ)e−βtu = \frac{\alpha}{\beta} + (u_0 - \frac{\alpha}{\beta})e^{-\beta t}, so that s′+γs=α+(βu0−α)e−βts' + \gamma s = \alpha + (\beta u_0 - \alpha)e^{-\beta t}. The terms s0e−γts_0e^{-\gamma t} and αγ(1−e−γt)\frac{\alpha}{\gamma}(1 - e^{-\gamma t}) contribute 00 and α\alpha to s′+γss' + \gamma s. When β≠γ\beta \ne \gamma, ddt(e−γt−e−βt)+γ(e−γt−e−βt)=(β−γ)e−βt\frac{d}{dt}(e^{-\gamma t} - e^{-\beta t}) + \gamma(e^{-\gamma t} - e^{-\beta t}) = (\beta - \gamma)e^{-\beta t}, so the last term, with c=α−βu0γ−βc = \frac{\alpha - \beta u_0}{\gamma - \beta}, contributes c(β−γ)e−βt=(βu0−α)e−βtc(\beta - \gamma)e^{-\beta t} = (\beta u_0 - \alpha)e^{-\beta t}, as needed. When β=γ\beta = \gamma, ddt(te−γt)+γte−γt=e−γt\frac{d}{dt}(te^{-\gamma t}) + \gamma te^{-\gamma t} = e^{-\gamma t}, so the last term contributes (βu0−α)e−βt(\beta u_0 - \alpha)e^{-\beta t}. A linear equation with a given start has only one solution. □\square

Lemma 2 (steady state). The only fixed point is (α/β,α/γ)(\alpha/\beta, \alpha/\gamma), which lies on the line u=(γ/β)su = (\gamma/\beta)s, and every solution tends to it.

Proof. Setting both derivatives to 0 gives u=α/βu = \alpha/\beta and s=βu/γ=α/γs = \beta u/\gamma = \alpha/\gamma. All exponentials in Theorem 1 tend to 0, and so does te−γtte^{-\gamma t}. □\square

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 w=βu−γs=dsdtw = \beta u - \gamma s = \frac{ds}{dt}. If the gene starts at (0,0)(0, 0) with α>0\alpha > 0, then w(t)>0w(t) > 0 for all t>0t > 0. If it starts at the on state (α1/β,α1/γ)(\alpha_1/\beta, \alpha_1/\gamma) with α1>0\alpha_1 > 0 and is switched off (α=0\alpha = 0), then w(t)<0w(t) < 0 for all t>0t > 0. The velocity of line L3 with γ^=γ/β\hat\gamma = \gamma/\beta is w/βw/\beta, with the same sign.

Proof. In both cases w(0)=0w(0) = 0, and w′=βu′−γs′=β(α−βu)−γww' = \beta u' - \gamma s' = \beta(\alpha - \beta u) - \gamma w, so w(t)=∫0te−γ(t−x)β(α−βu(x)) dxw(t) = \int_0^te^{-\gamma(t - x)}\beta(\alpha - \beta u(x))\,dx. In the first case u(x)<α/βu(x) < \alpha/\beta for every xx by Theorem 1, so the integrand is positive. In the second case α=0\alpha = 0 and u(x)>0u(x) > 0, so the integrand is negative. Finally u−γβs=w/βu - \frac{\gamma}{\beta}s = w/\beta. □\square

Lemma 4 (mirror). With β,γ\beta, \gamma fixed, the path switched off from the on state of α1\alpha_1 is the on state minus the path switched on from (0,0)(0, 0) with α1\alpha_1, at the same times. So their velocities are opposite.

Proof. Let (u,s)(u, s) solve the on path. Then (α1/β−u,α1/γ−s)(\alpha_1/\beta - u, \alpha_1/\gamma - s) starts at the on state, and its derivatives are −(α1−βu)=0−β(α1/β−u)-(\alpha_1 - \beta u) = 0 - \beta(\alpha_1/\beta - u) and −(βu−γs)=β(α1/β−u)−γ(α1/γ−s)-(\beta u - \gamma s) = \beta(\alpha_1/\beta - u) - \gamma(\alpha_1/\gamma - s), which is the off model with α=0\alpha = 0. Its ww is β(α1/β−u)−γ(α1/γ−s)=−(βu−γs)=−w\beta(\alpha_1/\beta - u) - \gamma(\alpha_1/\gamma - s) = -(\beta u - \gamma s) = -w. □\square

Theorem 5 (fit). γ^\hat\gamma of line L2 minimizes ∑(ui−c si)2\sum(u_i - c\,s_i)^2 over cc, for the chosen cells. If every chosen cell lies on the line u=γ′su = \gamma' s and not every chosen sis_i is 0, then γ^=γ′\hat\gamma = \gamma'.

Proof. The sum is a quadratic in cc with second derivative 2∑si2>02\sum s_i^2 > 0 and derivative −2∑si(ui−csi)-2\sum s_i(u_i - cs_i), which is 0 only at c=∑uisi/∑si2c = \sum u_is_i/\sum s_i^2. If ui=γ′siu_i = \gamma's_i for all chosen cells, the sum is 0 at c=γ′c = \gamma', so that is the minimum. □\square

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 si2s_i^2. In the page example the fit over all cells gives 0.413 for a true 0.5.

Lemma 6 (extrapolation). If γ^=γ′\hat\gamma = \gamma' and β=1\beta = 1, then s(t+Δ)−(s(t)+Δv(t))=Δ22s′′(ξ)s(t + \Delta) - (s(t) + \Delta v(t)) = \frac{\Delta^2}{2}s''(\xi) for some ξ\xi between tt and t+Δt + \Delta.

Proof. v=s′v = s' by Theorem 3, and this is Taylor's theorem with the Lagrange remainder; ss is smooth by Theorem 1. □\square

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 β\beta. 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 nn cells and gg genes, line L1 sorts each gene in O(nlog⁡n)O(n\log n) time and lines L2 to L4 take O(n)O(n) per gene, so the total time is O(gnlog⁡n)O(gn\log n) and the space is O(gn)O(gn) 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 β\beta and γ\gamma, Lemma 2, Theorem 3 on random rates, Lemma 4, Theorem 5 with steady cells at the extremes, and the order Δ2\Delta^2 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 γ^\hat\gamma and the share of cells with a clear velocity whose sign is right.

Complexity

Line L1 sorts the cells for each gene in O(nlog⁡n)O(n\log n) time, and lines L2 to L4 take O(n)O(n) per gene, so the time is O(gnlog⁡n)O(gn\log n) and the space O(gn)O(gn). 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 β\beta, so γ^\hat\gamma is a ratio, not a rate.

Variants and improvements

  • Dynamical model. Bergen and co-authors (2020) fit α\alpha, β\beta, γ\gamma 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 s^i\hat s_i 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 uu against ss before you trust the arrows.

Pitfalls

  • No steady states. If a gene never settles, the extreme cells are not on the line and γ^\hat\gamma 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 uu and ss.

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.

rna_velocity.pyI0RawGitHub
# 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

  1. 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
  2. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example