Algorithm Search⌘K

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.

Time
O(n^2 d + n^3) worst
Space
O(n^2) extra
Where
d = the number of dimensions; n = the number of cells
Properties
deterministicnot exactofflineiterative
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 x1,…,xnx_1, \dots, x_n in Rd\mathbb{R}^d, usually the first principal components of the log expression values, a kernel width σ>0\sigma > 0 and a root cell rr.

Output. A pseudotime τi≥0\tau_i \ge 0 for each cell, with τr=0\tau_r = 0.

The algorithm

  1. DPT(x_1..x_n, σ, r)
  2. 1K_ij ← exp(-‖x_i - x_j‖² / (2σ²)) for i ≠ j; K_ii ← 0
  3. 2q_i ← Σ_j K_ij; K_ij ← K_ij / (q_i q_j) ▷ remove the effect of density
  4. 3z_i ← Σ_j K_ij; T_s ← Z^(-1/2) K Z^(-1/2) ▷ symmetric form of the walk
  5. 4ψ_0 ← √z / ‖√z‖ ▷ top eigenvector, eigenvalue 1
  6. 5M ← (I - T_s + ψ_0 ψ_0ᵀ)^(-1) - I ▷ = Σ_{t ≥ 1} (T_s^t - ψ_0 ψ_0ᵀ)
  7. 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 α=1\alpha = 1. Line L3 gives a symmetric matrix that has the same eigenvalues as the walk T=Z−1KT = Z^{-1}K 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 TT; this page uses the symmetric form, which gives the exact eigen formula below.

Example

Five cells on a line at 0,1,2,3,40, 1, 2, 3, 4, with σ=1\sigma = 1 and root cell 0. Line L3 gives a walk where cell 0 sends most of its weight to cell 1 (TsT_s 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
τ\tau 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 λl\lambda_l lie strictly between −1-1 and 1 when n≥3n \ge 3. So the matrix of line L5 exists and equals ∑t≥1(Tst−ψ0ψ0⊤)\sum_{t \ge 1}(T_s^t - \psi_0\psi_0^\top), and the pseudotime has the exact formula τ(x,y)2=∑l≥1(λl/(1−λl))2(ψl(x)−ψl(y))2\tau(x, y)^2 = \sum_{l \ge 1}(\lambda_l/(1 - \lambda_l))^2(\psi_l(x) - \psi_l(y))^2. 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 σ=0.2\sigma = 0.2. For 80 cells on an arc of 1.7π1.7\pi, 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 TsT_s that is similar to a random walk on the cells, with top eigenvector ψ0\psi_0 (Lemma 1). The eigenvalue 1 is simple and all other eigenvalues lie strictly between −1-1 and 1 (Lemma 2). So the matrix of line L5 exists and is the sum of the walk over all times t≥1t \ge 1 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 x1,…,xn∈Rdx_1, \dots, x_n \in \mathbb{R}^d with n≥3n \ge 3 and a width σ>0\sigma > 0. Line L1 sets Kij=e−∥xi−xj∥2/(2σ2)K_{ij} = e^{-\|x_i - x_j\|^2/(2\sigma^2)} for i≠ji \ne j and Kii=0K_{ii} = 0. Line L2 sets qi=∑jKijq_i = \sum_jK_{ij} and K~ij=Kij/(qiqj)\tilde K_{ij} = K_{ij}/(q_iq_j). Line L3 sets zi=∑jK~ijz_i = \sum_j\tilde K_{ij}, Z=diag(z)Z = \mathrm{diag}(z) and Ts=Z−1/2K~Z−1/2T_s = Z^{-1/2}\tilde KZ^{-1/2}. Line L4 sets ψ0=z/∥z∥\psi_0 = \sqrt z/\|\sqrt z\| and Π=ψ0ψ0⊤\Pi = \psi_0\psi_0^\top. Line L5 sets M=(I−Ts+Π)−1−IM = (I - T_s + \Pi)^{-1} - I, and line L6 returns τi=∥Mr⋅−Mi⋅∥\tau_i = \|M_{r\cdot} - M_{i\cdot}\| for the root rr. We assume every qi>0q_i > 0; the code raises an error otherwise.

Lemma 1 (the walk). T=Z−1K~T = Z^{-1}\tilde K has nonnegative entries and rows that sum to 1, so it is the transition matrix of a random walk on the cells. Ts=Z1/2TZ−1/2T_s = Z^{1/2}TZ^{-1/2} is symmetric, has the same eigenvalues as TT, and Tsψ0=ψ0T_s\psi_0 = \psi_0.

Proof. K~\tilde K is symmetric with nonnegative entries, and row ii of Z−1K~Z^{-1}\tilde K sums to zi/zi=1z_i/z_i = 1. Z1/2TZ−1/2=Z−1/2K~Z−1/2Z^{1/2}TZ^{-1/2} = Z^{-1/2}\tilde KZ^{-1/2}, which is symmetric because K~\tilde K is, and similar matrices have the same eigenvalues. Finally Tsz=Z−1/2K~1=Z−1/2z=zT_s\sqrt z = Z^{-1/2}\tilde K\mathbf 1 = Z^{-1/2}z = \sqrt z. □\square

Lemma 2 (the spectrum). Let 1=λ0≥λ1≥⋯≥λn−11 = \lambda_0 \ge \lambda_1 \ge \dots \ge \lambda_{n-1} be the eigenvalues of TsT_s with orthonormal eigenvectors ψ0,…,ψn−1\psi_0, \dots, \psi_{n-1}. Then −1<λl<1-1 < \lambda_l < 1 for every l≥1l \ge 1.

Proof. Let Tu=λuTu = \lambda u with u≠0u \ne 0 real, and let ii be an index with ∣ui∣|u_i| largest. Then ∣λ∣∣ui∣=∣∑jTijuj∣≤∑jTij∣uj∣≤∣ui∣|\lambda||u_i| = |\sum_jT_{ij}u_j| \le \sum_jT_{ij}|u_j| \le |u_i|, so ∣λ∣≤1|\lambda| \le 1. Every TijT_{ij} with j≠ij \ne i is positive, because Kij>0K_{ij} > 0. If λ=1\lambda = 1, equality holds in both steps, so uj=uiu_j = u_i for every j≠ij \ne i and uu is constant: the eigenspace of 1 for TT has dimension 1, and so has that of TsT_s, which is Z1/2Z^{1/2} times it. Because TsT_s is symmetric, the eigenvalue 1 is then simple. If λ=−1\lambda = -1, equality gives uj=−uiu_j = -u_i for every j≠ij \ne i. Then every ∣uj∣|u_j| is the largest, and the same argument at an index j≠ij \ne i gives ul=−uj=uiu_l = -u_j = u_i for every l≠jl \ne j. Since n≥3n \ge 3 there is an ll different from ii and jj, with ul=−uiu_l = -u_i and ul=uiu_l = u_i, so ui=0u_i = 0 and u=0u = 0, a contradiction. □\square

Theorem 3 (accumulated matrix). A=I−Ts+ΠA = I - T_s + \Pi is symmetric positive definite, with eigenvalue 1 on ψ0\psi_0 and 1−λl>01 - \lambda_l > 0 on ψl\psi_l for l≥1l \ge 1. Its inverse exists and

M=A−1−I=∑l≥1λl1−λlψlψl⊤=∑t≥1(Tst−Π).M = A^{-1} - I = \sum_{l \ge 1}\frac{\lambda_l}{1 - \lambda_l}\psi_l\psi_l^\top = \sum_{t \ge 1}\left(T_s^t - \Pi\right).

Proof. Write Ts=∑lλlψlψl⊤T_s = \sum_l\lambda_l\psi_l\psi_l^\top and I=∑lψlψl⊤I = \sum_l\psi_l\psi_l^\top. Then A=ψ0ψ0⊤+∑l≥1(1−λl)ψlψl⊤A = \psi_0\psi_0^\top + \sum_{l \ge 1}(1 - \lambda_l)\psi_l\psi_l^\top, whose eigenvalues are positive by Lemma 2. So A−1−I=∑l≥1(11−λl−1)ψlψl⊤A^{-1} - I = \sum_{l \ge 1}\left(\frac{1}{1 - \lambda_l} - 1\right)\psi_l\psi_l^\top, which is the middle expression. Also Tst−Π=∑l≥1λltψlψl⊤T_s^t - \Pi = \sum_{l \ge 1}\lambda_l^t\psi_l\psi_l^\top, and since ∣λl∣<1|\lambda_l| < 1, ∑t≥1λlt=λl/(1−λl)\sum_{t \ge 1}\lambda_l^t = \lambda_l/(1 - \lambda_l), a convergent geometric series. □\square

So MM adds up the walk of tt steps for all t≥1t \ge 1, each with the stationary part Π\Pi removed. There is no time parameter left to choose.

Theorem 4 (eigen formula). For all cells xx and yy,

τ(x,y)2=∥Mx⋅−My⋅∥2=∑l≥1(λl1−λl)2(ψl(x)−ψl(y))2.\tau(x, y)^2 = \|M_{x\cdot} - M_{y\cdot}\|^2 = \sum_{l \ge 1}\left(\frac{\lambda_l}{1 - \lambda_l}\right)^2\big(\psi_l(x) - \psi_l(y)\big)^2.

So τ\tau 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 xx of MM is ∑l≥1λl1−λlψl(x)ψl⊤\sum_{l \ge 1}\frac{\lambda_l}{1 - \lambda_l}\psi_l(x)\psi_l^\top. The difference of two rows is ∑l≥1λl1−λl(ψl(x)−ψl(y))ψl⊤\sum_{l \ge 1}\frac{\lambda_l}{1 - \lambda_l}(\psi_l(x) - \psi_l(y))\psi_l^\top, and its squared norm is the sum of the squared coefficients because the ψl\psi_l are orthonormal. A Euclidean distance between rows of a matrix is a pseudometric. □\square

This is the difference from a diffusion map. A diffusion map at a time tt gives cell xx the coordinates λltψl(x)\lambda_l^t\psi_l(x) for a few ll, and its distance depends on tt. Diffusion pseudotime uses the weights ∑t≥1λlt=λl/(1−λl)\sum_{t \ge 1}\lambda_l^t = \lambda_l/(1 - \lambda_l) for all ll, so it adds the steps of all lengths. The weight grows without bound as λl→1\lambda_l \to 1, 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 A11=e1⊤Ae1>0A_{11} = e_1^\top Ae_1 > 0. After one step, the remaining block is the Schur complement A22−A21A11−1A12A_{22} - A_{21}A_{11}^{-1}A_{12}, which is symmetric positive definite: for v≠0v \ne 0 put w=(−A11−1A12v,v)w = (-A_{11}^{-1}A_{12}v, v), then v⊤(A22−A21A11−1A12)v=w⊤Aw>0v^\top(A_{22} - A_{21}A_{11}^{-1}A_{12})v = w^\top Aw > 0. By induction every pivot is positive. □\square

Invariance. KK depends only on the distances between cells, so moving, rotating or renumbering the cells changes τ\tau 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 α=1\alpha = 1: 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 O(n2d)O(n^2d) time. The normalizations take O(n2)O(n^2). The elimination of line L5 takes O(n3)O(n^3) time. Line L6 takes O(n2)O(n^2). The space is O(n2)O(n^2) 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 MM 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 O(n2d)O(n^2d) time and the inverse O(n3)O(n^3), with O(n2)O(n^2) 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 tt 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 σ\sigma. In the tests, σ=0.1\sigma = 0.1 gives 0.982 on the line and 0.961 on the arc, against 0.998 at σ=0.2\sigma = 0.2.

Variants and improvements

  • Diffusion maps. Use the eigenvectors λltψl\lambda_l^t\psi_l for a fixed tt as coordinates for display (Haghverdi, Buettner and Theis 2015). DPT is not a set of coordinates but a distance that adds all tt.
  • 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 σ\sigma.
  • 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 σ\sigma splits the walk into parts that almost do not touch, and the eigenvalues come near 1.
  • Too large σ\sigma 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.

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

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

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
  • a scene preset for the example