Algorithm Search⌘K

Algorithmadvanced

Minimum spanning tree pseudotime

Also called Monocle ordering, TSCAN.

Build a minimum spanning tree over cells or cluster centers in reduced space and order cells by their position along its longest path.

Time
O(n^2 d) worst
Space
O(n) extra
Where
d = the number of dimensions; m = the number of clusters; n = the number of cells
Properties
deterministicnot exactofflineiterative
Origin
Cole Trapnell, Davide Cacchiarelli, John L. Rinn, 2014

Minimum spanning tree pseudotime orders single cells along a process such as differentiation. It joins the cells, or the centers of cell clusters, with a minimum spanning tree in a space of few dimensions. It takes the longest path of the tree as the main line of the process, and it gives each cell a pseudotime: its distance along the tree from a root cell at the start. Trapnell and co-authors (2014) used a tree on the cells in Monocle, and Ji and Ji (2016) used a tree on the cluster centers in TSCAN. It is one answer to the trajectory inference problem. The tree is exact, but the claim that the pseudotime follows the real time of the process is a heuristic.

In plain words

Cells that change slowly from one state to another leave a trail of points, one for each cell. Connect every cell to the cells nearest to it so that all cells are joined with the least total length of line and no loops. The result is a tree that runs along the trail. Its longest path is the main line. Pick the cell where the process starts. The pseudotime of a cell is how far you walk along the tree from that start cell to reach it. Where the tree splits into arms, the process splits into branches. With clusters, do the same with one point for each cluster, and place each cell on the line between its cluster and the next one.

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, and a root cell. The cluster version also takes a cluster label for each cell and a root cluster.

Output. A tree on the cells, its longest path (the backbone), a pseudotime τi≥0\tau_i \ge 0 for each cell, and the cells where the tree branches.

The algorithm

  1. MST-PSEUDOTIME(x_1..x_n, r)
  2. 1grow a tree from cell 1: for each cell v outside it, w ← ‖x_u - x_v‖ to the cell u just added
  3. 2if w < best(v): best(v) ← w; parent(v) ← u; then add the outside cell with the smallest best(v)
  4. 3a ← the cell farthest from cell 1 along the tree; backbone ← the tree path from a to the cell farthest from a
  5. 4if no root r is given: r ← the first end of the backbone
  6. 5τ_i ← the length of the tree path from r to i, for every cell i
  7. 6branch points ← the cells of degree 3 or more in the tree
  8. CLUSTER-PSEUDOTIME(x_1..x_n, labels, root cluster)
  9. 7c_j ← the mean of the cells of cluster j; build the tree on the centers c_j as in L1 and L2; take the tree path from the root cluster to the farthest cluster
  10. 8project each cell of a cluster on the path onto the nearest path edge at its cluster, clipped to the edge, and set τ ← the offset of the edge + the position on it

Lines L1 and L2 are Prim's algorithm on the complete graph with Euclidean weights. It needs no distance matrix, so it takes O(n)O(n) extra space. Line L3 finds a longest path of the tree with two farthest-vertex searches, the usual way to find a tree diameter. Line L5 is one depth-first search from the root. Line L4 is only a default: the data do not tell which end of the process is the start, so a user should give the root from known biology, for example a stem cell marker. Lines L7 and L8 are the TSCAN version. Cells of clusters that are not on the main path get no pseudotime from line L8.

Example

Eight cells in two dimensions: three on a stem and two arms of the shape Y.

cell 0 1 2 3 4 5 6 7
xx (0,0)(0, 0) (1,0)(1, 0) (2,0)(2, 0) (3,1)(3, 1) (4,2)(4, 2) (3,−1)(3, -1) (4,−2)(4, -2) (5,−3)(5, -3)

The tree has the edges 00-11 and 11-22 of length 1, and 22-33, 33-44, 22-55, 55-66, 66-77 of length 2\sqrt 2. Cell 2 has degree 3, so it is the branch point. The longest path is 7,6,5,2,3,47, 6, 5, 2, 3, 4, of length 52≈7.075\sqrt 2 \approx 7.07. It runs from the tip of one arm to the tip of the other, and it does not contain the stem. So the default root is cell 7, a tip, and not cell 0, where the process starts. With the root r=0r = 0 the pseudotimes are:

cell 0 1 2 3 4 5 6 7
τ\tau 0 1 2 3.414 4.828 3.414 4.828 6.243

The two arms get the same pseudotimes at the same depth, as they should.

Correctness

The proof shows four things. Lines L1 and L2 give a minimum spanning tree, by the cut property. The two searches of line L3 give a longest path of a tree with nonnegative weights, by the four-point property of tree distances. If the distance between two cells grows strictly with the gap between their true times, the tree is the path of consecutive cells, so the pseudotime from the first cell gives the true order (a theorem). In the cluster version every cell gets a pseudotime between 0 and the length of the path of centers. For noisy cells the order is a measurement: in the tests, 200 cells near a line in five dimensions with noise of standard deviation 0.05 per coordinate give a rank correlation of 0.993 with the true time, and the cluster version on five clusters along a line gives 0.998.

Proof: The tree is a minimum spanning tree, the backbone is a longest path, and cells on a monotone curve are ordered exactlyfull

We prove what the steps compute. Lines L1 and L2 build a minimum spanning tree of the complete graph on the cells (Theorem 1). Line L3 finds a longest path of that tree (Theorem 2). When the cells lie on a curve along which the distance grows with the gap in time, the tree is the path of consecutive cells and the pseudotime gives the true order (Theorem 3). The cluster version places each cell between the two ends of the path of centers (Lemma 4). That the pseudotime of real cells follows the real process is a heuristic, and the tests measure it.

Setting. Cells x1,…,xnx_1, \dots, x_n in Rd\mathbb{R}^d, n≥2n \ge 2, and the complete graph KnK_n with weight w(i,j)=∥xi−xj∥w(i, j) = \|x_i - x_j\|. For a tree TT on the cells, dT(i,j)d_T(i, j) is the sum of the weights on the unique path from ii to jj in TT. Line L5 returns τi=dT(r,i)\tau_i = d_T(r, i) for the root rr.

Theorem 1 (Prim). Lines L1 and L2 return a minimum spanning tree of KnK_n.

Proof. Let SS be the set of cells taken so far. The loop keeps, for each cell v∉Sv \notin S, the value best(v)=min⁡u∈Sw(u,v)\mathrm{best}(v) = \min_{u \in S}w(u, v) and a cell uu that reaches it: line L1 computes the weight to the new cell and line L2 lowers the value when it is smaller. So the next cell uu and its edge to parent(u)\mathrm{parent}(u) form a lightest edge across the cut (S,V∖S)(S, V \setminus S). By induction, the edges taken so far are part of some minimum spanning tree T∗T^*. If the new edge ee is not in T∗T^*, adding ee to T∗T^* makes a cycle, which crosses the cut at another edge ff with w(f)≥w(e)w(f) \ge w(e). Then T∗+e−fT^* + e - f is a spanning tree of weight at most w(T∗)w(T^*) that contains all the edges taken so far and ee. After nn rounds the n−1n - 1 edges form a spanning tree that is part of a minimum spanning tree, so it is one. □\square

Theorem 2 (two searches). Let TT be a tree with nonnegative weights, ss any vertex, aa a vertex farthest from ss, and bb a vertex farthest from aa. Then the path from aa to bb is a longest path of TT.

We use one fact about tree distances first.

Lemma 2a (four points). For any four vertices x,y,z,wx, y, z, w of a tree with nonnegative weights, dT(x,y)+dT(z,w)≤max⁡(dT(x,z)+dT(y,w), dT(x,w)+dT(y,z))d_T(x, y) + d_T(z, w) \le \max\big(d_T(x, z) + d_T(y, w),\ d_T(x, w) + d_T(y, z)\big).

Proof. The union of the tree paths between the four vertices is a subtree with at most four leaves. For some way of splitting the four vertices into two pairs, say {x,z}\{x, z\} and {y,w}\{y, w\} (the other splits are the same up to names), it is a path from a vertex pp to a vertex qq, possibly with p=qp = q, together with paths from pp to xx and to zz and from qq to yy and to ww, where these paths share no edges. Then dT(x,y)+dT(z,w)d_T(x, y) + d_T(z, w) and dT(x,w)+dT(y,z)d_T(x, w) + d_T(y, z) both equal dT(x,p)+dT(z,p)+dT(y,q)+dT(w,q)+2dT(p,q)d_T(x, p) + d_T(z, p) + d_T(y, q) + d_T(w, q) + 2d_T(p, q), and dT(x,z)+dT(y,w)d_T(x, z) + d_T(y, w) is the same sum without 2dT(p,q)2d_T(p, q). So the two largest of the three sums are equal, and each sum is at most the larger of the other two. □\square

Proof of Theorem 2. Let uu-vv be a longest path, of length DD. By Lemma 2a with x=sx = s, y=ay = a, z=uz = u, w=vw = v, either dT(s,a)+D≤dT(s,u)+dT(a,v)d_T(s, a) + D \le d_T(s, u) + d_T(a, v) or dT(s,a)+D≤dT(s,v)+dT(a,u)d_T(s, a) + D \le d_T(s, v) + d_T(a, u). Because aa is farthest from ss, dT(s,u)≤dT(s,a)d_T(s, u) \le d_T(s, a) and dT(s,v)≤dT(s,a)d_T(s, v) \le d_T(s, a). So dT(a,v)≥Dd_T(a, v) \ge D in the first case and dT(a,u)≥Dd_T(a, u) \ge D in the second. The farthest vertex bb from aa is at least that far, and no path is longer than DD, so the path from aa to bb has length DD. □\square

Theorem 3 (monotone curve). Let t1<t2<⋯<tnt_1 < t_2 < \dots < t_n and suppose ∥xi−xj∥\|x_i - x_j\| is a strictly increasing function of ∣ti−tj∣|t_i - t_j|: ∣ti−tj∣<∣tk−tl∣|t_i - t_j| < |t_k - t_l| implies ∥xi−xj∥<∥xk−xl∥\|x_i - x_j\| < \|x_k - x_l\|. Then the minimum spanning tree is unique and is the path 1,2,…,n1, 2, \dots, n, and with root 1 the pseudotime τi=∑l<i∥xl+1−xl∥\tau_i = \sum_{l < i}\|x_{l+1} - x_l\| is strictly increasing in ii.

Proof. Take an edge (i,j)(i, j) with j>i+1j > i + 1. On the cycle i,i+1,…,j,ii, i + 1, \dots, j, i every edge (l,l+1)(l, l + 1) with i≤l<ji \le l < j has tl+1−tl<tj−tit_{l+1} - t_l < t_j - t_i, so it is strictly lighter than (i,j)(i, j). So (i,j)(i, j) is the unique heaviest edge of a cycle. If some minimum spanning tree TT contained it, removing it would split TT into two parts, and some edge (l,l+1)(l, l + 1) of the cycle joins the two parts; replacing (i,j)(i, j) by it gives a lighter spanning tree, a contradiction. So every minimum spanning tree uses only the edges (l,l+1)(l, l + 1), and the only spanning tree made of them is the path. The tree distance from 1 to ii is the sum of the path edges before ii, and every edge has positive weight because ∥xl+1−xl∥>∥xl−xl∥=0\|x_{l+1} - x_l\| > \|x_l - x_l\| = 0. □\square

Points on a line, and points on a helix piece (cos⁡t,sin⁡t,ct)(\cos t, \sin t, ct) with tt in an interval shorter than π\pi, satisfy the condition: the squared chord 2−2cos⁡Δ+c2Δ22 - 2\cos\Delta + c^2\Delta^2 is strictly increasing in Δ\Delta on [0,π][0, \pi]. Noise breaks it, which is why the order of noisy cells is only measured.

Lemma 4 (projection). In the cluster version, let the path of centers be c0,c1,…,cmc_0, c_1, \dots, c_m with offsets o0=0o_0 = 0 and oj+1=oj+∥cj+1−cj∥o_{j+1} = o_j + \|c_{j+1} - c_j\|. A cell of the cluster at position ii gets τ∈[omax⁡(i−1,0),omin⁡(i+1,m)]\tau \in [o_{\max(i-1, 0)}, o_{\min(i+1, m)}], and the foot it uses is the nearest point to the cell on the segment it is projected on.

Proof. For a segment from aa to bb of length L>0L > 0 the code sets s=(p−a)⋅(b−a)/Ls = (p - a) \cdot (b - a)/L and clips it to [0,L][0, L]. The function s↦∥p−a−s(b−a)/L∥2s \mapsto \|p - a - s(b - a)/L\|^2 is a convex quadratic with its minimum at the unclipped ss, so the clipped value is its minimum on [0,L][0, L], which is the nearest point of the segment. The cell then gets oj+so_j + s with s∈[0,L]=[0,oj+1−oj]s \in [0, L] = [0, o_{j+1} - o_j] for the edge j∈{i−1,i}j \in \{i - 1, i\} with the nearer foot. □\square

So the pseudotime of the cluster version is never below 0 or above the length of the path, and the cells of a cluster lie next to the cells of the clusters before and after it on the path. If two centers are the same point, L=0L = 0 and the code would divide by zero; this needs two clusters with the same mean, which the input must avoid.

What the lines compute. Lines L1 and L2 are Theorem 1. Line L3 is Theorem 2. Line L4 takes the first end of the backbone as the root when no root is given; which end is the start of the process is not known from the data alone. Line L5 is the tree distance from the root, computed by a depth-first search, and Theorem 3 is the case where it gives the true order. Line L6 marks the cells of degree 3 or more, where the tree branches. Line L7 computes the centers, and line L8 is Lemma 4.

Complexity. Prim's algorithm takes nn rounds, each of which finds the minimum of at most nn values and computes at most nn distances in O(d)O(d) time, so lines L1 and L2 take O(n2d)O(n^2d) time and O(n)O(n) extra space, with no distance matrix stored. The two searches of line L3 and the search of line L5 take O(n)O(n) time each on a tree. The cluster version with mm clusters takes O(nd)O(nd) for the centers, O(m2d)O(m^2d) for the tree and O(nd)O(nd) for the projections, after O(nm)O(nm) for grouping the cells by label in this code.

What the tests check. The test file checks the page example, Prim's tree against Kruskal's algorithm on random points and against all labeled trees from Pruefer sequences for n≤6n \le 6, the backbone length against the longest distance over all pairs, Theorem 3 on random points of a helix piece given in shuffled order, Lemma 4 on clusters along a line, the cell of an off-path cluster, and the errors. Two simulations are measurements, not theorems: the rank correlation of the pseudotime with the true time for noisy cells near a line, and a Y shape in which one branch point lies near the junction, together with many small branches caused by noise.

Complexity

Prim's algorithm on the complete graph takes O(n2d)O(n^2d) time and O(n)O(n) extra space. The searches of lines L3 and L5 take O(n)O(n) time. The cluster version with mm clusters takes O(nd)O(nd) time for the centers and projections and O(m2d)O(m^2d) for the tree, which is much less than O(n2d)O(n^2d) when mm is small. For many cells, the cluster version is the usual way to keep the tree small.

Properties

  • Deterministic. Ties are broken by the smaller index.
  • Exact tree. The tree is a minimum spanning tree of the cells; only its meaning as a trajectory is a heuristic.
  • Shows branches. The cells of degree 3 or more mark where the tree splits.
  • Needs a root. The pseudotime depends on the root, which the data do not fix.
  • Sensitive to noise. One cell more or less can change the tree and its longest path.

Variants and improvements

  • Monocle 1. Trapnell and co-authors (2014) reduce the data with independent component analysis, build the tree on the cells, and order the cells along the longest path with a PQ tree to place the branches.
  • TSCAN. Ji and Ji (2016) cluster the cells in a space of principal components with a Gaussian mixture model, build the tree on the cluster centers, and project the cells onto its edges. A tree on a few centers is much less sensitive to noise than a tree on all cells.
  • Slingshot builds the tree on the clusters and then fits a smooth principal curve along each lineage.
  • Graph methods. Diffusion pseudotime uses random walks on a neighbor graph instead of a tree, and RNA velocity gives a direction to the process from unspliced and spliced counts.

When to use it

Use it for a first look at a process with a simple shape, a line or a tree with few branches, when you can name the start cell or the start cluster. Use the cluster version when the data are noisy or large. The benchmark of Saelens and co-authors (2019) found that no method was best for all shapes of trajectory, so compare it with a graph method such as diffusion pseudotime.

Pitfalls

  • Spurious branches. In the tests, a Y of 180 cells with noise of standard deviation 0.02 gives 39 cells of degree 3 or more, although only one branch point lies near the junction. Count only branches with long arms, or use the cluster version.
  • The wrong root. The default end of the longest path can be a tip, as in the example. Give the root from biology.
  • Cycles and gaps. A tree cannot show a cycle, such as the cell cycle, and it joins separate groups of cells with long edges that are not a real process.
  • The space matters. The tree depends on the reduced space and the number of components; a different space can give a different order.
  • Pseudotime is not time. It is a distance in expression space, not hours or days.

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.

mst_pseudotime.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mst-pseudotime/. The authors are listed in prov/MJ06W1.jsonl.
"""Pseudotime from a minimum spanning tree of cells or of cluster centers.

Two versions:

- On cells, the idea of Monocle 1 (Trapnell et al. 2014): a minimum spanning
  tree over the cells in a reduced space, its longest path as the backbone of
  the process, and for each cell the distance along the tree from a root cell
  at one end of the backbone. Monocle 1 then orders the cells with a PQ tree
  and an independent component analysis space; this version uses the tree
  distance and any coordinates it is given.
- On clusters, the idea of TSCAN (Ji and Ji 2016): a minimum spanning tree
  over the cluster centers, the path of clusters from a root cluster to the
  farthest cluster, and each cell of a cluster on the path projected onto the
  nearest path edge at its cluster. Cells of clusters off the path get None.

The tree is found by Prim's algorithm on the complete graph with Euclidean
weights, in O(n^2) time. Ties are broken by the smaller index.
"""

from __future__ import annotations

import math
from typing import Dict, List, Optional, Sequence, Tuple

Edge = Tuple[int, int, float]


def dist(a: Sequence[float], b: Sequence[float]) -> float:
    return math.sqrt(sum((x - y) ** 2 for x, y in zip(a, b)))


def prim_mst(points: Sequence[Sequence[float]]) -> List[Edge]:
    """The edges (parent, child, weight) of a minimum spanning tree of the complete Euclidean graph."""
    n = len(points)
    if n == 0:
        return []
    inside = [False] * n
    best = [math.inf] * n
    parent = [-1] * n
    best[0] = 0.0
    edges = []
    for _ in range(n):
        u = min((v for v in range(n) if not inside[v]), key=lambda v: (best[v], v))
        inside[u] = True
        if parent[u] >= 0:
            edges.append((parent[u], u, best[u]))
        for v in range(n):
            if not inside[v]:
                w = dist(points[u], points[v])  # @line L1
                if w < best[v]:
                    best[v], parent[v] = w, u  # @line L2
    return edges


def adjacency(n: int, edges: Sequence[Edge]) -> List[List[Tuple[int, float]]]:
    adj: List[List[Tuple[int, float]]] = [[] for _ in range(n)]
    for a, b, w in edges:
        adj[a].append((b, w))
        adj[b].append((a, w))
    return adj


def tree_distances(adj, source: int) -> Tuple[List[float], List[int]]:
    """Distances along the tree from source, and the parent of each vertex on its path to source."""
    n = len(adj)
    d = [math.inf] * n
    par = [-1] * n
    d[source] = 0.0
    stack = [source]
    while stack:
        u = stack.pop()
        for v, w in adj[u]:
            if d[v] == math.inf:
                d[v] = d[u] + w
                par[v] = u
                stack.append(v)
    return d, par


def farthest(d: Sequence[float]) -> int:
    return max(range(len(d)), key=lambda v: (d[v], -v))


def diameter_path(adj, start: int = 0) -> List[int]:
    """A longest path of the tree, by two farthest-vertex searches."""
    a = farthest(tree_distances(adj, start)[0])  # @line L3
    d, par = tree_distances(adj, a)
    b = farthest(d)
    path = [b]
    while path[-1] != a:
        path.append(par[path[-1]])
    return path[::-1]


def cell_pseudotime(points: Sequence[Sequence[float]], root: Optional[int] = None) -> Dict[str, object]:
    """Pseudotime of each cell as the tree distance from the root.

    With root=None the root is the first end of the backbone. Returns a dict
    with 'tree', 'backbone', 'root', 'pseudotime' and 'branch_points'.
    """
    n = len(points)
    if n < 2:
        raise ValueError("need at least two cells")
    edges = prim_mst(points)
    adj = adjacency(n, edges)
    backbone = diameter_path(adj)
    if root is None:
        root = backbone[0]  # @line L4
    if not 0 <= root < n:
        raise ValueError("root out of range")
    tau = tree_distances(adj, root)[0]  # @line L5
    branch = [v for v in range(n) if len(adj[v]) >= 3]  # @line L6
    return {"tree": edges, "backbone": backbone, "root": root, "pseudotime": tau, "branch_points": branch}


def cluster_pseudotime(points: Sequence[Sequence[float]], labels: Sequence[int],
                       root_cluster: int) -> Dict[str, object]:
    """TSCAN-style pseudotime: an MST on the cluster centers and projection onto the main path."""
    ids = sorted(set(labels))
    if root_cluster not in ids:
        raise ValueError("unknown root cluster")
    pos = {c: i for i, c in enumerate(ids)}
    dim = len(points[0])
    centers = []
    for c in ids:
        members = [p for p, l in zip(points, labels) if l == c]
        centers.append([sum(p[a] for p in members) / len(members) for a in range(dim)])  # @line L7
    adj = adjacency(len(ids), prim_mst(centers))
    d, par = tree_distances(adj, pos[root_cluster])
    end = farthest(d)
    path = [end]
    while path[-1] != pos[root_cluster]:
        path.append(par[path[-1]])
    path = path[::-1]
    offset = [0.0]
    for a, b in zip(path, path[1:]):
        offset.append(offset[-1] + dist(centers[a], centers[b]))
    where = {c: i for i, c in enumerate(path)}
    tau: List[Optional[float]] = []
    for p, l in zip(points, labels):
        i = where.get(pos[l])
        if i is None:
            tau.append(None)
            continue
        best = None
        for j in (i - 1, i):  # the path edges (j, j + 1) at this cluster
            if 0 <= j < len(path) - 1:
                a, b = centers[path[j]], centers[path[j + 1]]
                L = offset[j + 1] - offset[j]
                s = sum((x - y) * (z - y) for x, y, z in zip(p, a, b)) / L
                s = min(max(s, 0.0), L)
                foot = [y + s / L * (z - y) for y, z in zip(a, b)]
                cand = (dist(p, foot), offset[j] + s)
                if best is None or cand < best:
                    best = cand
        tau.append(best[1] if best is not None else 0.0)  # @line L8
    return {"centers": centers, "path": [ids[i] for i in path], "pseudotime": tau}
test_mst_pseudotime.py 192 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mst-pseudotime/. The authors are listed in prov/MJ06W1.jsonl.

import itertools
import math
import random

import pytest

from mst_pseudotime import (
    adjacency,
    cell_pseudotime,
    cluster_pseudotime,
    diameter_path,
    dist,
    prim_mst,
    tree_distances,
)

R2 = math.sqrt(2)
PAGE = [(0, 0), (1, 0), (2, 0), (3, 1), (4, 2), (3, -1), (4, -2), (5, -3)]


def weight(edges):
    return sum(w for _, _, w in edges)


def kruskal_weight(points):
    n = len(points)
    parent = list(range(n))

    def find(x):
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x

    total = 0.0
    for w, a, b in sorted((dist(points[a], points[b]), a, b) for a in range(n) for b in range(a + 1, n)):
        ra, rb = find(a), find(b)
        if ra != rb:
            parent[ra] = rb
            total += w
    return total


def prufer_trees(n):
    """All labeled trees on n vertices, from Pruefer sequences."""
    for seq in itertools.product(range(n), repeat=n - 2):
        degree = [1] * n
        for x in seq:
            degree[x] += 1
        edges = []
        for x in seq:
            leaf = min(v for v in range(n) if degree[v] == 1)
            edges.append((leaf, x))
            degree[leaf] -= 1
            degree[x] -= 1
        u, v = [v for v in range(n) if degree[v] == 1]
        edges.append((u, v))
        yield edges


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 test_page_example():
    out = cell_pseudotime(PAGE)
    assert sorted((min(a, b), max(a, b)) for a, b, _ in out["tree"]) == [(0, 1), (1, 2), (2, 3), (2, 5), (3, 4), (5, 6), (6, 7)]
    # The longest path runs from tip to tip, not from the start of the process.
    assert out["backbone"] == [7, 6, 5, 2, 3, 4]
    assert out["branch_points"] == [2]
    tau = cell_pseudotime(PAGE, root=0)["pseudotime"]
    want = [0, 1, 2, 2 + R2, 2 + 2 * R2, 2 + R2, 2 + 2 * R2, 2 + 3 * R2]
    assert all(math.isclose(a, b) for a, b in zip(tau, want))


def test_prim_matches_kruskal_and_exhaustive_search():
    rng = random.Random(1)
    for _ in range(30):
        n = rng.randint(2, 25)
        pts = [(rng.random(), rng.random()) for _ in range(n)]
        edges = prim_mst(pts)
        assert len(edges) == n - 1
        assert math.isclose(weight(edges), kruskal_weight(pts))
    for n in range(2, 7):
        pts = [(rng.random(), rng.random(), rng.random()) for _ in range(n)]
        best = min(sum(dist(pts[a], pts[b]) for a, b in t) for t in prufer_trees(n))
        assert math.isclose(weight(prim_mst(pts)), best)


def test_diameter_matches_all_pairs():
    rng = random.Random(2)
    for _ in range(30):
        n = rng.randint(2, 20)
        pts = [(rng.random(), rng.random()) for _ in range(n)]
        adj = adjacency(n, prim_mst(pts))
        path = diameter_path(adj, start=rng.randrange(n))
        length = sum(w for a, b in zip(path, path[1:]) for v, w in adj[a] if v == b)
        longest = max(max(tree_distances(adj, s)[0]) for s in range(n))
        assert math.isclose(length, longest)


def test_points_on_a_monotone_curve_are_ordered_exactly():
    """Distance strictly increasing in the gap of the parameter: the tree is the path of consecutive points."""
    rng = random.Random(3)
    for _ in range(10):
        t = sorted(rng.uniform(0, 2.5) for _ in range(30))
        pts = [(math.cos(s), math.sin(s), 0.3 * s) for s in t]  # a helix piece, chords grow with the gap
        order = list(range(30))
        rng.shuffle(order)
        shuffled = [pts[i] for i in order]
        tt = [t[i] for i in order]
        root = order.index(0)
        tau = cell_pseudotime(shuffled, root=root)["pseudotime"]
        assert sorted(range(30), key=lambda i: tau[i]) == sorted(range(30), key=lambda i: tt[i])
        arc = [0.0]
        for a, b in zip(pts, pts[1:]):
            arc.append(arc[-1] + dist(a, b))
        assert all(math.isclose(tau[j], arc[order[j]], abs_tol=1e-12) for j in range(30))


def test_noisy_line_measured():
    """A measurement: 200 cells near a line in 5 dimensions, noise 0.05 per coordinate."""
    rng = random.Random(4)
    t = [rng.random() for _ in range(200)]
    pts = [[s * 3, s * 2] + [rng.gauss(0, 0.05) for _ in range(3)] for s in t]
    pts = [[p[0] + rng.gauss(0, 0.05), p[1] + rng.gauss(0, 0.05)] + p[2:] for p in pts]
    root = min(range(200), key=lambda i: t[i])
    tau = cell_pseudotime(pts, root=root)["pseudotime"]
    assert spearman(tau, t) > 0.97


def test_cluster_version_on_a_line():
    rng = random.Random(5)
    pts, labels, t = [], [], []
    for c in range(5):
        for _ in range(20):
            s = c + rng.uniform(-0.4, 0.4)
            pts.append((s, rng.gauss(0, 0.1)))
            labels.append(c)
            t.append(s)
    out = cluster_pseudotime(pts, labels, root_cluster=0)
    assert out["path"] == [0, 1, 2, 3, 4]
    tau = out["pseudotime"]
    assert all(v is not None for v in tau)
    assert spearman(tau, t) > 0.97
    # A cell is placed between 0 and the length of the path of centers.
    c = out["centers"]
    length = sum(dist(c[i], c[i + 1]) for i in range(4))
    assert all(0 <= v <= length + 1e-12 for v in tau)


def test_cluster_version_off_path_cluster_gets_none():
    pts = [(0, 0), (0.1, 0), (1, 0), (1.1, 0), (2, 0), (2.1, 0), (1, 5), (1.1, 5)]
    labels = [0, 0, 1, 1, 2, 2, 3, 3]
    out = cluster_pseudotime(pts, labels, root_cluster=0)
    assert out["path"] == [0, 1, 3]
    assert out["pseudotime"][4] is None
    with pytest.raises(ValueError):
        cluster_pseudotime(pts, labels, root_cluster=9)


def test_branching_measured():
    """A measurement: a Y with three arms of 60 cells; one branch point lies near the junction."""
    rng = random.Random(6)
    pts = []
    for ang in (math.pi, math.pi / 4, -math.pi / 4):
        for _ in range(60):
            r = rng.uniform(0.05, 1.0)
            pts.append((r * math.cos(ang) + rng.gauss(0, 0.02), r * math.sin(ang) + rng.gauss(0, 0.02)))
    out = cell_pseudotime(pts)
    hubs = [v for v in out["branch_points"] if math.hypot(*pts[v]) < 0.3]
    assert hubs
    assert len(out["branch_points"]) > 3  # noise adds small side branches too


def test_errors():
    with pytest.raises(ValueError):
        cell_pseudotime([(0, 0)])
    with pytest.raises(ValueError):
        cell_pseudotime([(0, 0), (1, 1)], root=5)

History

Trapnell and co-authors (2014) introduced pseudotemporal ordering of single cells with Monocle, which built a minimum spanning tree on the cells. The tree on cells was sensitive to noise, so Ji and Ji (2016) built it on cluster centers in TSCAN. Later methods such as Slingshot kept the cluster tree and fitted curves along it. The benchmark of Saelens and co-authors (2019) compared many trajectory inference methods, including several built on spanning trees.

References

  1. Cole Trapnell et al., The dynamics and regulators of cell fate decisions are revealed by pseudotemporal ordering of single cells, Nature Biotechnology 32(4), 381 to 386 (2014), the Monocle method, with independent component analysis, the minimum spanning tree on the cells and the longest path through it
  2. Zhicheng Ji and Hongkai Ji, TSCAN: Pseudo-time reconstruction and evaluation in single-cell RNA-seq analysis, Nucleic Acids Research 44(13), e117 (2016), the method section, with the clusters, the minimum spanning tree on the cluster centers and the projection of the cells onto its edges
  3. 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, which includes methods built on minimum spanning trees

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