Algorithmadvanced
Diffusion pseudotime
Also called DPT.
Order cells by a distance between their random-walk transition vectors in a diffusion map, measured from a chosen root cell.
- Solves
- Trajectory inference
- Time
- O(n^2 d + n^3) worst
- Space
- O(n^2) extra
- Where
- d = the number of dimensions; n = the number of cells
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Laleh Haghverdi, Maren Büttner, F. Alexander Wolf, Florian Buettner, Fabian J. Theis, 2016
Diffusion pseudotime (DPT) orders single cells along a process such as differentiation. It builds a random walk on the cells, where a step goes mostly to near cells, and it adds up the walks of all lengths into one matrix. The pseudotime of a cell is the distance between its row of that matrix and the row of a root cell. Haghverdi and co-authors (2016) defined it. It answers the trajectory inference problem with no tree to build and no time scale to choose. The distance is defined exactly and has a formula in the eigenvectors of the walk; the claim that it follows the real order of the process is a heuristic.
In plain words
Think of the cells as stepping stones. A walker on one stone jumps to a near stone more often than to a far one. Start a walker at every stone and record where it is likely to be after one jump, two jumps, and so on, and add all of these up. Two stones whose records look alike are close along the path that the stones make, even if a straight line between them would go across empty space. The pseudotime of a cell is how different its record is from the record of the start cell.
The problem
Input. Cells in , usually the first principal components of the log expression values, a kernel width and a root cell .
Output. A pseudotime for each cell, with .
The algorithm
DPT(x_1..x_n, σ, r)- 1
K_ij ← exp(-‖x_i - x_j‖² / (2σ²)) for i ≠ j; K_ii ← 0 - 2
q_i ← Σ_j K_ij; K_ij ← K_ij / (q_i q_j) ▷ remove the effect of density - 3
z_i ← Σ_j K_ij; T_s ← Z^(-1/2) K Z^(-1/2) ▷ symmetric form of the walk - 4
ψ_0 ← √z / ‖√z‖ ▷ top eigenvector, eigenvalue 1 - 5
M ← (I - T_s + ψ_0 ψ_0ᵀ)^(-1) - I ▷ = Σ_{t ≥ 1} (T_s^t - ψ_0 ψ_0ᵀ) - 6
τ_i ← ‖M(r, ·) - M(i, ·)‖ for every cell i
Line L1 is a Gaussian kernel. Line L2 divides by the density at both cells, which is the normalization of Coifman and Lafon (2006) with . Line L3 gives a symmetric matrix that has the same eigenvalues as the walk whose rows sum to 1. Line L4 is the eigenvector of the eigenvalue 1. Line L5 adds the walk over all numbers of steps, with the part that does not depend on the start removed; the inverse is computed by Gauss-Jordan elimination. Line L6 is the distance from the root. The paper writes the sum with the walk ; this page uses the symmetric form, which gives the exact eigen formula below.
Example
Five cells on a line at , with and root cell 0. Line L3 gives a walk where cell 0 sends most of its weight to cell 1 ( entry 0.7038) and cell 1 sends weight to both sides (0.7038 to cell 0, 0.3312 to cell 2). Lines L5 and L6 give:
| cell | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| 0 | 0.5877 | 1.0140 | 1.9329 | 1.9833 |
The order is correct. The steps are not even: the last two cells are close in pseudotime, because the walk treats the two ends of the line alike.
Correctness
The proof shows that the walk has a simple eigenvalue 1 and that all its other eigenvalues lie strictly between and 1 when . So the matrix of line L5 exists and equals , and the pseudotime has the exact formula . It is a pseudometric, and it does not change when the cells are moved, rotated or renumbered. The order of noisy cells is a measurement: in the tests, 80 cells near a line in five dimensions give a rank correlation of 0.998 with the true time at . For 80 cells on an arc of , whose two ends are close in space, the pseudotime gives 0.998 and the straight distance from the root gives only 0.618.
Proof: The accumulated transition matrix is the sum of the walk over all times, and diffusion pseudotime has an exact eigen formulafull
We prove what the steps compute. Lines L1 to L4 give a symmetric matrix that is similar to a random walk on the cells, with top eigenvector (Lemma 1). The eigenvalue 1 is simple and all other eigenvalues lie strictly between and 1 (Lemma 2). So the matrix of line L5 exists and is the sum of the walk over all times with its limit removed (Theorem 3), and the pseudotime has an exact formula in the eigenvectors (Theorem 4). The elimination of the code needs no pivoting (Lemma 5). That the pseudotime follows the order of a real process is a heuristic, and the tests measure it.
Setting. Cells with and a width . Line L1 sets for and . Line L2 sets and . Line L3 sets , and . Line L4 sets and . Line L5 sets , and line L6 returns for the root . We assume every ; the code raises an error otherwise.
Lemma 1 (the walk). has nonnegative entries and rows that sum to 1, so it is the transition matrix of a random walk on the cells. is symmetric, has the same eigenvalues as , and .
Proof. is symmetric with nonnegative entries, and row of sums to . , which is symmetric because is, and similar matrices have the same eigenvalues. Finally .
Lemma 2 (the spectrum). Let be the eigenvalues of with orthonormal eigenvectors . Then for every .
Proof. Let with real, and let be an index with largest. Then , so . Every with is positive, because . If , equality holds in both steps, so for every and is constant: the eigenspace of 1 for has dimension 1, and so has that of , which is times it. Because is symmetric, the eigenvalue 1 is then simple. If , equality gives for every . Then every is the largest, and the same argument at an index gives for every . Since there is an different from and , with and , so and , a contradiction.
Theorem 3 (accumulated matrix). is symmetric positive definite, with eigenvalue 1 on and on for . Its inverse exists and
Proof. Write and . Then , whose eigenvalues are positive by Lemma 2. So , which is the middle expression. Also , and since , , a convergent geometric series.
So adds up the walk of steps for all , each with the stationary part removed. There is no time parameter left to choose.
Theorem 4 (eigen formula). For all cells and ,
So is a pseudometric on the cells: it is symmetric, it is 0 from a cell to itself, and it obeys the triangle inequality.
Proof. By Theorem 3, row of is . The difference of two rows is , and its squared norm is the sum of the squared coefficients because the are orthonormal. A Euclidean distance between rows of a matrix is a pseudometric.
This is the difference from a diffusion map. A diffusion map at a time gives cell the coordinates for a few , and its distance depends on . Diffusion pseudotime uses the weights for all , so it adds the steps of all lengths. The weight grows without bound as , so the slowest directions of the walk, which run along the trajectory, count most.
Lemma 5 (elimination). Gauss-Jordan elimination on a symmetric positive definite matrix without row exchanges meets only positive pivots, so it computes the inverse.
Proof. The first pivot is . After one step, the remaining block is the Schur complement , which is symmetric positive definite: for put , then . By induction every pivot is positive.
Invariance. depends only on the distances between cells, so moving, rotating or renumbering the cells changes only by the same renumbering.
What the lines compute. Line L1 is the kernel. Line L2 is the density normalization of Coifman and Lafon (2006) with : in their analysis, as the cells become dense on a smooth curve or surface, the walk then no longer depends on how densely the cells are sampled. Line L3 is Lemma 1, line L4 the top eigenvector of Lemma 1, line L5 Theorem 3 by the elimination of Lemma 5, and line L6 Theorem 4 from the root.
Complexity. The kernel takes time. The normalizations take . The elimination of line L5 takes time. Line L6 takes . The space is for the dense matrices.
What the tests check. The test file checks the page example, Lemma 1 and Lemma 2 on random cells, the matrix against the partial sums of the series of Theorem 3, the eigen formula of Theorem 4 against the eigenvectors from the Jacobi method, the pseudometric and the invariance, and the elimination of Lemma 5 against a general inverse. Two simulations are measurements, not theorems: the rank correlation of the pseudotime with the true time for noisy cells near a line, and for cells on an arc whose two ends are close in space.
Complexity
The kernel takes time and the inverse , with space for the dense matrices. Real tools use a sparse nearest neighbor graph as the kernel and compute only a few eigenvectors, which makes the formula of the proof cheap for many cells.
Properties
- No time scale. The sum over all steps removes the number of steps that a diffusion map needs.
- Follows the shape. The distance runs along the cells, not across empty space.
- Exact formula. The pseudotime is a weighted distance in the eigenvectors of the walk.
- Needs a root. The data do not say where the process starts.
- Depends on . In the tests, gives 0.982 on the line and 0.961 on the arc, against 0.998 at .
Variants and improvements
- Diffusion maps. Use the eigenvectors for a fixed as coordinates for display (Haghverdi, Buettner and Theis 2015). DPT is not a set of coordinates but a distance that adds all .
- Branches. The paper also finds branches by comparing the pseudotimes from several end cells; this page leaves that out.
- Width per cell. A kernel width that changes with the local density of cells, in place of one .
- Sparse graph. A kernel on a k-nearest-neighbor graph, as in the scanpy package, to scale to many cells.
- Other approaches. Minimum spanning tree pseudotime builds a tree, and RNA velocity gives a direction from spliced and unspliced counts, which can help to choose the root.
When to use it
Use it when the cells form a continuous path or a tree and you can name a start cell. It handles curved paths that a straight distance gets wrong. The benchmark of Saelens and co-authors (2019) found that the best method depends on the shape of the trajectory, so check the result against a second method.
Pitfalls
- Wrong root. A root in the middle of the path gives cells on both sides the same pseudotimes.
- Too small splits the walk into parts that almost do not touch, and the eigenvalues come near 1.
- Too large joins cells across gaps and makes the walk ignore the shape.
- Separate groups. Cells of a different type far from the path get large but meaningless pseudotimes; remove them first.
- Pseudotime is not time. It is a distance in the walk, not hours or days, and its steps need not be even, as the example shows.
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/diffusion-pseudotime/. The authors are listed in prov/0RVW5J.jsonl.
"""Diffusion pseudotime (Haghverdi et al. 2016), dense and small.
The steps:
- A Gaussian kernel with one width sigma on all pairs of distinct cells.
- Density normalization: divide K[i][j] by q[i] q[j], where q is the row sum.
- The symmetric transition matrix Ts = Z^(-1/2) K Z^(-1/2), where Z holds the
row sums of the normalized kernel. Its top eigenvector is psi0 = sqrt(z) / norm.
- The accumulated matrix M = (I - Ts + psi0 psi0^T)^(-1) - I, which is the sum
over all t >= 1 of the walk of t steps with the stationary part removed.
- The pseudotime of cell i is the Euclidean distance between rows r and i of M.
What this version leaves out: the kernel width per cell, the neighbor graph
that real tools use to scale to many cells, and the detection of branches and
of the cells that start no branch.
"""
from __future__ import annotations
import math
from typing import List, Sequence, Tuple
from rq3lin import identity, sqdist
Matrix = List[List[float]]
def transition_matrix(points: Sequence[Sequence[float]], sigma: float) -> Tuple[Matrix, List[float]]:
"""The symmetric transition matrix Ts and its top eigenvector psi0."""
n = len(points)
if n < 3:
raise ValueError("need at least three cells")
if sigma <= 0:
raise ValueError("sigma must be positive")
K = [[0.0 if i == j else math.exp(-sqdist(points[i], points[j]) / (2 * sigma * sigma)) # @line L1
for j in range(n)] for i in range(n)]
q = [sum(row) for row in K]
if min(q) == 0.0:
raise ValueError("a cell has no neighbor at this sigma; use a larger sigma")
K = [[K[i][j] / (q[i] * q[j]) for j in range(n)] for i in range(n)] # @line L2
z = [sum(row) for row in K]
s = [1.0 / math.sqrt(v) for v in z]
Ts = [[s[i] * K[i][j] * s[j] for j in range(n)] for i in range(n)] # @line L3
norm = math.sqrt(sum(z))
psi0 = [math.sqrt(v) / norm for v in z] # @line L4
return Ts, psi0
def spd_inverse(A: Sequence[Sequence[float]]) -> Matrix:
"""The inverse of a symmetric positive definite matrix by Gauss-Jordan elimination, in O(n^3).
No pivoting is needed: every pivot of a positive definite matrix is positive.
"""
n = len(A)
W = [list(map(float, A[i])) + [1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
for c in range(n):
piv = W[c][c]
if piv <= 0.0:
raise ValueError("matrix is not positive definite")
top = [v / piv for v in W[c]]
W[c] = top
for r in range(n):
if r != c:
f = W[r][c]
if f != 0.0:
row = W[r]
for j in range(c, 2 * n):
row[j] -= f * top[j]
return [row[n:] for row in W]
def accumulated_matrix(Ts: Sequence[Sequence[float]], psi0: Sequence[float]) -> Matrix:
"""M = (I - Ts + psi0 psi0^T)^(-1) - I."""
n = len(Ts)
I = identity(n)
A = [[I[i][j] - Ts[i][j] + psi0[i] * psi0[j] for j in range(n)] for i in range(n)]
Ainv = spd_inverse(A)
return [[Ainv[i][j] - I[i][j] for j in range(n)] for i in range(n)] # @line L5
def dpt_distance(M: Sequence[Sequence[float]], a: int, b: int) -> float:
return math.sqrt(sum((x - y) ** 2 for x, y in zip(M[a], M[b])))
def diffusion_pseudotime(points: Sequence[Sequence[float]], root: int, sigma: float) -> List[float]:
"""The diffusion pseudotime of every cell from the root cell."""
if not 0 <= root < len(points):
raise ValueError("root out of range")
Ts, psi0 = transition_matrix(points, sigma)
M = accumulated_matrix(Ts, psi0)
return [dpt_distance(M, root, i) for i in range(len(points))] # @line L6
rq3lin.py 203 lines
# SPDX-License-Identifier: MIT
# Group module of the single-cell pages of https://algorithm.tamnd.com/ (group rq3). The authors are listed in prov/.
"""Small dense linear algebra and neighbor search for the single-cell pages.
The reference copy is in biology/transcriptomics/doublet-detection/impl/python/.
The other rq3 pages hold identical copies. The module holds no algorithm of a
page: no doublet score, no clustering, no batch correction and no pseudotime.
Conventions:
- A vector is a list of floats and a matrix is a list of rows.
- Ties between equal distances are broken by the smaller index, so that every
result is deterministic.
- Random draws use a random.Random object that the caller passes in.
"""
from __future__ import annotations
import math
import random
from typing import List, Optional, Sequence, Tuple
Vector = List[float]
Matrix = List[List[float]]
def dot(a: Sequence[float], b: Sequence[float]) -> float:
return sum(x * y for x, y in zip(a, b))
def sqdist(a: Sequence[float], b: Sequence[float]) -> float:
return sum((x - y) * (x - y) for x, y in zip(a, b))
def transpose(A: Sequence[Sequence[float]]) -> Matrix:
return [list(col) for col in zip(*A)]
def matmul(A: Sequence[Sequence[float]], B: Sequence[Sequence[float]]) -> Matrix:
Bt = transpose(B)
return [[dot(row, col) for col in Bt] for row in A]
def matvec(A: Sequence[Sequence[float]], x: Sequence[float]) -> Vector:
return [dot(row, x) for row in A]
def identity(n: int) -> Matrix:
return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
def column_means(X: Sequence[Sequence[float]]) -> Vector:
n = len(X)
return [sum(col) / n for col in zip(*X)]
def knn(points: Sequence[Sequence[float]], k: int,
queries: Optional[Sequence[Sequence[float]]] = None) -> List[List[int]]:
"""The k nearest points (Euclidean) of each query, by brute force.
With queries=None the queries are the points themselves and each point is
left out of its own list. Each list is sorted by (distance, index).
"""
self_query = queries is None
qs = points if self_query else queries
limit = len(points) - (1 if self_query else 0)
if not 0 <= k <= limit:
raise ValueError("k must be between 0 and the number of candidate points")
out = []
for i, q in enumerate(qs):
cand = [(sqdist(q, p), j) for j, p in enumerate(points) if not (self_query and j == i)]
cand.sort()
out.append([j for _, j in cand[:k]])
return out
def solve(A: Sequence[Sequence[float]], b: Sequence[float]) -> Vector:
"""Solve A x = b by Gaussian elimination with partial pivoting.
Raises ValueError when a pivot is zero, that is when A is singular in
floating point.
"""
n = len(A)
M = [list(map(float, A[i])) + [float(b[i])] for i in range(n)]
for c in range(n):
p = max(range(c, n), key=lambda r: abs(M[r][c]))
if M[p][c] == 0.0:
raise ValueError("singular matrix")
M[c], M[p] = M[p], M[c]
piv = M[c][c]
for r in range(c + 1, n):
f = M[r][c] / piv
if f != 0.0:
row, top = M[r], M[c]
for j in range(c, n + 1):
row[j] -= f * top[j]
x = [0.0] * n
for i in range(n - 1, -1, -1):
s = M[i][n] - sum(M[i][j] * x[j] for j in range(i + 1, n))
x[i] = s / M[i][i]
return x
def inverse(A: Sequence[Sequence[float]]) -> Matrix:
"""The inverse of A, one column at a time with solve."""
n = len(A)
cols = [solve(A, [1.0 if i == j else 0.0 for i in range(n)]) for j in range(n)]
return transpose(cols)
def jacobi_eigh(S: Sequence[Sequence[float]], tol: float = 1e-12,
max_sweeps: int = 100) -> Tuple[Vector, Matrix]:
"""All eigenvalues and eigenvectors of a symmetric matrix by the cyclic Jacobi method.
Returns (values, vectors): values in decreasing order, and vectors[i] the
unit eigenvector of values[i]. Each eigenvector is given the sign that
makes its entry of largest absolute value positive.
"""
n = len(S)
A = [list(map(float, row)) for row in S]
V = identity(n)
for _ in range(max_sweeps):
off = sum(A[i][j] * A[i][j] for i in range(n) for j in range(n) if i != j)
scale = sum(A[i][i] * A[i][i] for i in range(n)) + off
if off <= tol * tol * max(scale, 1e-300):
break
for p in range(n - 1):
for q in range(p + 1, n):
apq = A[p][q]
if apq == 0.0:
continue
theta = (A[q][q] - A[p][p]) / (2.0 * apq)
t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
c = 1.0 / math.sqrt(t * t + 1.0)
s = t * c
for k in range(n):
akp, akq = A[k][p], A[k][q]
A[k][p] = c * akp - s * akq
A[k][q] = s * akp + c * akq
for k in range(n):
apk, aqk = A[p][k], A[q][k]
A[p][k] = c * apk - s * aqk
A[q][k] = s * apk + c * aqk
for k in range(n):
vkp, vkq = V[k][p], V[k][q]
V[k][p] = c * vkp - s * vkq
V[k][q] = s * vkp + c * vkq
order = sorted(range(n), key=lambda i: -A[i][i])
values = [A[i][i] for i in order]
vectors = []
for i in order:
v = [V[k][i] for k in range(n)]
big = max(range(n), key=lambda k: abs(v[k]))
if v[big] < 0:
v = [-x for x in v]
vectors.append(v)
return values, vectors
def pca_fit(X: Sequence[Sequence[float]], r: int) -> Tuple[Vector, Matrix, Vector]:
"""Principal axes of the rows of X: (means, axes, variances), r axes of unit length.
The covariance uses the divisor n - 1. The axes come from jacobi_eigh, so they
are deterministic up to the sign rule of that function.
"""
n, d = len(X), len(X[0])
if not 1 <= r <= d:
raise ValueError("r must be between 1 and the number of columns")
mu = column_means(X)
C = [[0.0] * d for _ in range(d)]
for row in X:
z = [x - m for x, m in zip(row, mu)]
for a in range(d):
za = z[a]
if za != 0.0:
Ca = C[a]
for b in range(a, d):
Ca[b] += za * z[b]
for a in range(d):
for b in range(a, d):
C[a][b] /= max(n - 1, 1)
C[b][a] = C[a][b]
values, vectors = jacobi_eigh(C)
return mu, vectors[:r], values[:r]
def pca_project(X: Sequence[Sequence[float]], mu: Sequence[float], axes: Sequence[Sequence[float]]) -> Matrix:
"""The coordinates of the rows of X on the axes, after subtracting mu."""
return [[dot([x - m for x, m in zip(row, mu)], a) for a in axes] for row in X]
def poisson_knuth(rng: random.Random, lam: float) -> int:
"""A Poisson draw by multiplying uniforms (Knuth); for test data with lam up to about 50.
Draw order: rng.random() until the product falls below exp(-lam).
"""
if lam < 0:
raise ValueError("lam must be non-negative")
limit, k, p = math.exp(-lam), 0, 1.0
while True:
p *= rng.random()
if p <= limit:
return k
k += 1
test_diffusion_pseudotime.py 158 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/diffusion-pseudotime/. The authors are listed in prov/0RVW5J.jsonl.
import math
import random
import pytest
from diffusion_pseudotime import (
accumulated_matrix,
diffusion_pseudotime,
dpt_distance,
spd_inverse,
transition_matrix,
)
from rq3lin import inverse, jacobi_eigh, matmul
def spearman(a, b):
def ranks(v):
order = sorted(range(len(v)), key=lambda i: v[i])
r = [0] * len(v)
for k, i in enumerate(order):
r[i] = k
return r
ra, rb = ranks(a), ranks(b)
n = len(a)
return 1 - 6 * sum((x - y) ** 2 for x, y in zip(ra, rb)) / (n * (n * n - 1))
def random_cells(rng, n, d=2):
return [[rng.random() for _ in range(d)] for _ in range(n)]
def test_page_example():
pts = [(0,), (1,), (2,), (3,), (4,)]
Ts, psi0 = transition_matrix(pts, 1.0)
assert math.isclose(Ts[0][1], 0.7038, abs_tol=5e-5)
assert math.isclose(Ts[1][2], 0.3312, abs_tol=5e-5)
tau = diffusion_pseudotime(pts, 0, 1.0)
want = [0.0, 0.5877, 1.0140, 1.9329, 1.9833]
assert all(math.isclose(a, b, abs_tol=5e-5) for a, b in zip(tau, want))
assert tau == sorted(tau)
def test_transition_matrix_facts():
rng = random.Random(1)
for _ in range(10):
pts = random_cells(rng, rng.randint(3, 15))
n = len(pts)
Ts, psi0 = transition_matrix(pts, 0.3)
assert all(math.isclose(Ts[i][j], Ts[j][i]) for i in range(n) for j in range(n))
# psi0 is a unit eigenvector of eigenvalue 1.
assert math.isclose(sum(v * v for v in psi0), 1.0)
Tp = [sum(Ts[i][j] * psi0[j] for j in range(n)) for i in range(n)]
assert all(math.isclose(a, b, abs_tol=1e-12) for a, b in zip(Tp, psi0))
# The walk T = Z^(-1/2) Ts Z^(1/2) has rows that sum to 1; psi0 is proportional to sqrt(z).
T = [[Ts[i][j] * psi0[j] / psi0[i] for j in range(n)] for i in range(n)]
assert all(math.isclose(sum(row), 1.0) for row in T)
assert all(v >= 0 for row in T for v in row)
# Every other eigenvalue lies strictly inside (-1, 1).
vals, _ = jacobi_eigh(Ts)
assert math.isclose(vals[0], 1.0, abs_tol=1e-10)
assert all(-1 < v < 1 - 1e-9 for v in vals[1:])
def test_accumulated_matrix_is_the_series():
rng = random.Random(2)
for _ in range(5):
pts = random_cells(rng, 6)
Ts, psi0 = transition_matrix(pts, 0.5)
n = len(pts)
P = [[psi0[i] * psi0[j] for j in range(n)] for i in range(n)]
B = [[Ts[i][j] - P[i][j] for j in range(n)] for i in range(n)]
total = [[0.0] * n for _ in range(n)]
power = [row[:] for row in B]
for _ in range(3000):
total = [[a + b for a, b in zip(r1, r2)] for r1, r2 in zip(total, power)]
power = matmul(power, B)
if max(abs(v) for row in power for v in row) < 1e-15:
break
M = accumulated_matrix(Ts, psi0)
assert all(math.isclose(M[i][j], total[i][j], abs_tol=1e-9) for i in range(n) for j in range(n))
def test_eigen_formula():
rng = random.Random(3)
for _ in range(5):
pts = random_cells(rng, 10, 3)
Ts, psi0 = transition_matrix(pts, 0.4)
M = accumulated_matrix(Ts, psi0)
vals, vecs = jacobi_eigh(Ts)
for a in range(10):
for b in range(10):
s = sum((lam / (1 - lam)) ** 2 * (v[a] - v[b]) ** 2 for lam, v in zip(vals[1:], vecs[1:]))
assert math.isclose(dpt_distance(M, a, b), math.sqrt(s), rel_tol=1e-7, abs_tol=1e-9)
def test_pseudometric_and_invariance():
rng = random.Random(4)
pts = random_cells(rng, 12)
M = accumulated_matrix(*transition_matrix(pts, 0.3))
D = [[dpt_distance(M, a, b) for b in range(12)] for a in range(12)]
for a in range(12):
assert D[a][a] == 0.0
for b in range(12):
assert math.isclose(D[a][b], D[b][a])
for c in range(12):
assert D[a][c] <= D[a][b] + D[b][c] + 1e-12
# The same cells in another order, rotated and moved, give the same pseudotimes.
perm = list(range(12))
rng.shuffle(perm)
c, s = math.cos(0.7), math.sin(0.7)
moved = [[c * pts[i][0] - s * pts[i][1] + 5, s * pts[i][0] + c * pts[i][1] - 2] for i in perm]
tau = diffusion_pseudotime(pts, 0, 0.3)
tau2 = diffusion_pseudotime(moved, perm.index(0), 0.3)
assert all(math.isclose(tau2[j], tau[perm[j]], rel_tol=1e-8, abs_tol=1e-10) for j in range(12))
def test_spd_inverse_matches_general_inverse():
rng = random.Random(5)
pts = random_cells(rng, 9)
Ts, psi0 = transition_matrix(pts, 0.3)
A = [[(1.0 if i == j else 0.0) - Ts[i][j] + psi0[i] * psi0[j] for j in range(9)] for i in range(9)]
X, Y = spd_inverse(A), inverse(A)
assert all(math.isclose(X[i][j], Y[i][j], abs_tol=1e-10) for i in range(9) for j in range(9))
def test_noisy_line_measured():
"""A measurement: 80 cells near a line in 5 dimensions, noise 0.05 per coordinate, sigma 0.2."""
rng = random.Random(4)
t = [rng.random() for _ in range(80)]
pts = [[s * 3 + rng.gauss(0, 0.05), s * 2 + rng.gauss(0, 0.05)] + [rng.gauss(0, 0.05) for _ in range(3)] for s in t]
root = min(range(80), key=lambda i: t[i])
assert spearman(diffusion_pseudotime(pts, root, 0.2), t) > 0.99
def test_horseshoe_measured():
"""A measurement: cells on an arc of 1.7 pi, so the two ends are close in space but far along the arc."""
rng = random.Random(7)
t = [rng.random() for _ in range(80)]
pts = [[math.cos(1.7 * math.pi * s) + rng.gauss(0, 0.02), math.sin(1.7 * math.pi * s) + rng.gauss(0, 0.02)] for s in t]
root = min(range(80), key=lambda i: t[i])
euclid = [math.dist(pts[root], p) for p in pts]
assert spearman(diffusion_pseudotime(pts, root, 0.2), t) > 0.99
assert spearman(euclid, t) < 0.7
def test_errors():
with pytest.raises(ValueError):
transition_matrix([(0,), (1,)], 1.0)
with pytest.raises(ValueError):
transition_matrix([(0,), (1,), (2,)], 0.0)
with pytest.raises(ValueError):
transition_matrix([(0,), (1,), (1000,)], 0.01)
with pytest.raises(ValueError):
diffusion_pseudotime([(0,), (1,), (2,)], 3, 1.0)
History
Coifman and Lafon (2006) introduced diffusion maps and the normalization of the kernel by density. Haghverdi, Buettner and Theis (2015) applied diffusion maps to single-cell differentiation data. Haghverdi and co-authors (2016) defined diffusion pseudotime and used it to find branch points. The benchmark of Saelens and co-authors (2019) compared it with many other trajectory inference methods.
References
- Laleh Haghverdi, Maren Büttner, F. Alexander Wolf, Florian Buettner and Fabian J. Theis, Diffusion pseudotime robustly reconstructs lineage branching, Nature Methods 13(10), 845 to 848 (2016), the definition of the accumulated transition matrix and of the diffusion pseudotime distance from a root cell
- Laleh Haghverdi, Florian Buettner and Fabian J. Theis, Diffusion maps for high-dimensional single-cell analysis of differentiation data, Bioinformatics 31(18), 2989 to 2998 (2015), the diffusion map of single cells with a Gaussian kernel and its eigenvectors as coordinates
- Ronald R. Coifman and Stéphane Lafon, Diffusion maps, Applied and Computational Harmonic Analysis 21(1), 5 to 30 (2006), the normalization of the kernel by the density with the parameter alpha, and the diffusion distance
- Wouter Saelens, Robrecht Cannoodt, Helena Todorov and Yvan Saeys, A comparison of single-cell trajectory inference methods, Nature Biotechnology 37(5), 547 to 554 (2019), the benchmark of trajectory inference methods on real and synthetic data
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 0RVW5J Edit this page History Report an error Markdown