Algorithm Search⌘K

Algorithmadvanced

Doublet detection

Also called Scrublet, doublet scoring.

Flag barcodes that hold two cells by simulating artificial doublets from pairs of cells and scoring each barcode by its doublet neighbors.

Time
O(n^2 (p + log n) + n d^2 + d^3) worst
Space
O(n^2 + n d + d^2) extra
Where
d = the number of genes; n = the number of cells; p = the number of principal components
Properties
randomizednot exactofflineiterative
Origin
Samuel L. Wolock, Romain Lopez, Allon M. Klein, 2019

Doublet detection finds the barcodes of a single-cell experiment that hold two cells. In droplet methods, cells enter droplets at random, so some droplets get two cells, and their reads share one cell barcode. Such a doublet looks like a cell with a mixed profile, and it can appear as a false intermediate state or a false new type. Scrublet (Wolock, Lopez and Klein 2019) makes artificial doublets by adding the counts of random pairs of observed cells, puts the real and the artificial profiles in one principal component space, and scores each cell by the fraction of artificial doublets among its nearest neighbors. Bayes' rule with the expected doublet rate turns this fraction into a probability. The method is a heuristic. It finds doublets of two different cell types well and doublets of one type poorly, and the tests measure both. It uses a k-nearest-neighbor graph as a classifier: the labels of the neighbors give the score. This is a different use from graph clustering, where the graph is cut into groups.

In plain words

Some barcodes hold two cells, and you cannot see that from one barcode alone. But you can make fake doublets yourself: pick two real cells at random and add their counts. Now put the real cells and the fake doublets together and look at the neighborhood of each real cell. A normal cell lives among other normal cells of its type. A real doublet of two types looks like the fake doublets made from those two types, so many of its neighbors are fake doublets. Count the fake neighbors and turn the count into a probability, using how many doublets you expect. Then pick a cutoff in the valley between the low and the high scores of the fake doublets. A doublet of two cells of the same type looks like a normal cell, and no method of this kind can find it.

The problem

Input. A matrix of raw counts, nn cells by dd genes, usually after the choice of highly variable genes. The ratio rr of simulated doublets to observed cells, the expected doublet rate ρ\rho, the number of neighbors kk and the number of components pp.

Output. A doublet score in (0,1)(0, 1) for each cell, and a call for each cell: doublet or singlet.

Model. A doublet has the sum of the counts of two cells. A cell is a doublet with prior probability ρ\rho. The scores rest on the assumption that the simulated doublets have the same distribution as the real ones. The real doublet rate depends on the number of cells loaded; the single-cell RNA-seq page gives the Poisson calculation.

The algorithm

  1. SCRUBLET(X, r, ρ, k, p) ▷ X: n cells by d genes, raw counts
  2. 1for i ← 1 to r n do pick cells a, b at random; y_i ← x_a + x_b
  3. 2scale each observed and simulated profile to the mean total of the observed cells
  4. 3standardize each gene with the mean and standard deviation of the observed cells
  5. 4fit p principal components on the observed cells; project all profiles on them
  6. 5k_adj ← round(k (1 + r))
  7. 6for each profile, find its k_adj nearest neighbors among all (1 + r) n profiles
  8. 7q ← (the number of simulated neighbors + 1) / (k_adj + 2)
  9. 8score ← q ρ / r / (1 - ρ - q (1 - ρ - ρ/r))
  10. 9t ← the valley of the histogram of the scores of the simulated doublets
  11. 10return the scores, and call each observed cell with score > t a doublet

Line L1 picks the two cells uniformly and independently, so a pair can repeat a cell, as in Scrublet. The simulated doublets use the raw counts, and line L2 removes the larger total of a doublet, so only its mixed composition stays. Lines L3 and L4 use statistics of the observed cells only and apply them to the simulated ones, which puts both sets in the same space. Line L5 grows kk so that each profile still has about kk observed neighbors. Line L7 is the fraction of simulated neighbors with one pseudo count on each side. Line L8 is Bayes' rule with the prior ρ\rho, as the correctness section shows. Line L9 uses the simulated doublets because they have two modes: doublets of two types score high, and doublets of one type score near the prior.

Scrublet defaults to r=2r = 2, ρ=0.1\rho = 0.1, k=round⁡(0.5n)k = \operatorname{round}(0.5\sqrt n) and 30 components, and it selects variable genes and fits the components with a fast solver. The code here takes the genes as given, uses a brute-force neighbor search and a full eigendecomposition, and defaults to 10 components for small test data.

Example

Take ρ=0.1\rho = 0.1, r=2r = 2 and kadj=15k_{adj} = 15. A cell has q=(nd+1)/17q = (n_d + 1)/17.

simulated neighbors ndn_d qq score
0 0.0588 0.00346
4 0.2941 0.0226
10 0.6471 0.0924
15 0.9412 0.4706

The score is qρ/r(qρ/r)+(1−ρ)(1−q)\frac{q\rho/r}{(q\rho/r) + (1 - \rho)(1 - q)}. For nd=10n_d = 10 the numerator is 0.6471⋅0.05=0.032350.6471 \cdot 0.05 = 0.03235 and the second term is 0.9⋅0.3529=0.31760.9 \cdot 0.3529 = 0.3176, so the score is 0.03235/0.3500=0.09240.03235/0.3500 = 0.0924, close to the prior 0.1. This is expected: two thirds of all profiles are simulated, and q=0.6471q = 0.6471 is near 2/32/3, so the neighborhood has the global mix and the score stays near ρ\rho. Only a neighborhood with nearly all simulated neighbors gives a high score, and even with all 15 neighbors simulated the score is 0.47060.4706, because the pseudo counts keep qq below 1. The scores are on a low scale, which is why the threshold comes from the data at line L9 and not from a fixed value such as 0.5.

In a simulation with three cell types, 150 singlets, 15 doublets of two types and 10 doublets of one type, the scores of the heterotypic doublets were above those of the singlets in every pair, and the threshold of line L9 called all 15 of them and no singlet. The 10 homotypic doublets had scores like the singlets and none was called. These numbers are measured, not proved.

Correctness

No method can be shown to find the doublets, so the proof shows what the score means. If the observed neighbors of a point estimate the density of singlets there and the simulated neighbors estimate the density of doublets, then line L8 is exactly the posterior probability of a doublet by Bayes' theorem, with prior ρ\rho. The score is strictly increasing in qq, lies in (0,1)(0, 1), and equals ρ\rho when the neighborhood has the global share r/(1+r)r/(1 + r) of simulated profiles. The choice kadj=k(1+r)k_{adj} = k(1 + r) keeps the expected number of observed neighbors at kk. Last, after normalization a doublet of two cells of one type has the expected profile of a singlet of that type, so homotypic doublets cannot be found from the profile. The approximation in the model is that a fraction ρ\rho of the observed cells are doublets, which lowers the score of true doublets a little.

Proof: The Scrublet score is the Bayes posterior of a doublet under a neighbor density model, and homotypic doublets cannot be told apart by profilefull

Doublet detection has no exact answer, so there is no theorem that the method finds the doublets. We prove what the score means. Theorem 1 shows that line L8 is Bayes' rule with the prior ρ\rho, when the neighbors at a point estimate the density of singlets and of doublets there. Lemma 2 gives its range and shape, and Lemma 3 explains the choice of kadjk_{adj}. Lemma 4 shows a limit that holds for every method of this kind: after the normalization of line L2, a doublet of two cells of one type has the same expected profile as a singlet of that type. That the neighbor counts estimate the densities, and that simulated doublets look like real ones, are assumptions; the tests measure how well the scores separate doublets on simulated data.

Setting. There are nn observed profiles and rnrn simulated doublets (line L1), and each profile has kadjk_{adj} nearest neighbors among all (1+r)n(1 + r)n profiles (line L6). For one profile, ndn_d of its neighbors are simulated. Line L7 sets q=(nd+1)/(kadj+2)q = (n_d + 1)/(k_{adj} + 2) and line L8 sets

S(q)=qρ/r1−ρ−q(1−ρ−ρ/r),0<ρ<1,  r>0.S(q) = \frac{q\rho/r}{1 - \rho - q(1 - \rho - \rho/r)}, \qquad 0 < \rho < 1, \; r > 0.

Density model. Near a point xx of the embedding, let fs(x)f_s(x) be the density of singlets and fd(x)f_d(x) the density of doublets, both normalized to integrate to 1. A real cell is a doublet with prior probability ρ\rho. The model treats the nn observed profiles as singlets, so near xx they occur at a rate proportional to nfs(x)n f_s(x), and the simulated doublets at a rate proportional to rnfd(x)rn f_d(x). The fraction qq then estimates rfd/(rfd+fs)rf_d/(rf_d + f_s), and (nd+1)/(kadj+2)(n_d + 1)/(k_{adj} + 2) is the Laplace estimate of that fraction: the posterior mean of a binomial proportion with a uniform prior.

Theorem 1 (the score is a posterior). Suppose q=rfd/(rfd+fs)q = rf_d/(rf_d + f_s) with fs>0f_s > 0. Then

S(q)=ρfdρfd+(1−ρ)fs,S(q) = \frac{\rho f_d}{\rho f_d + (1 - \rho)f_s},

which is the probability, by Bayes' theorem, that a real cell at xx is a doublet.

Proof. From q(rfd+fs)=rfdq(rf_d + f_s) = rf_d we get fd/fs=q/(r(1−q))f_d/f_s = q/(r(1 - q)), and q<1q < 1 since fs>0f_s > 0. Divide the numerator and the denominator of the right side by fsf_s:

ρfdρfd+(1−ρ)fs=ρq/(r(1−q))ρq/(r(1−q))+1−ρ=ρq/rρq/r+(1−ρ)(1−q).\frac{\rho f_d}{\rho f_d + (1 - \rho)f_s} = \frac{\rho q/(r(1 - q))}{\rho q/(r(1 - q)) + 1 - \rho} = \frac{\rho q/r}{\rho q/r + (1 - \rho)(1 - q)}.

The denominator is ρq/r+1−ρ−q+ρq=1−ρ−q(1−ρ−ρ/r)\rho q/r + 1 - \rho - q + \rho q = 1 - \rho - q(1 - \rho - \rho/r), which is the denominator of S(q)S(q). □\square

The model is an approximation in one place: a fraction ρ\rho of the observed profiles are doublets, so the observed profiles occur at a rate proportional to (1−ρ)fs+ρfd(1 - \rho)f_s + \rho f_d, not fsf_s. Where fd>fsf_d > f_s, which is where the doublets are, this rate is above fsf_s, so qq is smaller and the score is lower than the exact posterior. Where fd<fsf_d < f_s the score is a little higher.

Lemma 2 (range and shape). For q∈(0,1)q \in (0, 1), S(q)∈(0,1)S(q) \in (0, 1) and SS is strictly increasing. At q=r/(1+r)q = r/(1 + r), the fraction of simulated profiles among all profiles, S(q)=ρS(q) = \rho.

Proof. Write S(q)=A/(A+B)S(q) = A/(A + B) with A=ρq/r>0A = \rho q/r > 0 and B=(1−ρ)(1−q)>0B = (1 - \rho)(1 - q) > 0, from the proof of Theorem 1. So 0<S<10 < S < 1. As qq grows, AA grows and BB falls, so A/(A+B)=1/(1+B/A)A/(A + B) = 1/(1 + B/A) grows strictly. At q=r/(1+r)q = r/(1 + r), A=ρ/(1+r)A = \rho/(1 + r) and B=(1−ρ)/(1+r)B = (1 - \rho)/(1 + r), so S=ρS = \rho. □\square

So a cell whose neighborhood has the same mix as the whole data gets the prior, and the score moves away from the prior only when the neighborhood holds more or fewer simulated doublets than the global share. Because qq is never 0 or 1, the score is never 0 or 1.

Lemma 3 (the adjusted neighbor count). If the neighbors of a profile have the global mix, the expected number of observed neighbors among the kadj=k(1+r)k_{adj} = k(1 + r) is kk.

Proof. The global share of observed profiles is n/((1+r)n)=1/(1+r)n/((1 + r)n) = 1/(1 + r), and k(1+r)⋅1/(1+r)=kk(1 + r) \cdot 1/(1 + r) = k. □\square

Line L5 rounds k(1+r)k(1 + r) to an integer, so the statement holds up to rounding. The aim is that the resolution of the neighborhood among the real cells does not depend on how many doublets are simulated.

Lemma 4 (homotypic doublets). Let cells aa and bb have expected counts E[xa]=saμE[x_a] = s_a\mu and E[xb]=sbμE[x_b] = s_b\mu with the same profile μ\mu and any sizes sa,sb>0s_a, s_b > 0. Then the expected doublet E[xa+xb]=(sa+sb)μE[x_a + x_b] = (s_a + s_b)\mu is a multiple of μ\mu, and after scaling to a fixed total at line L2 it equals the scaled expected singlet of the type.

Proof. E[xa+xb]=E[xa]+E[xb]=(sa+sb)μE[x_a + x_b] = E[x_a] + E[x_b] = (s_a + s_b)\mu. Scaling to the total TT maps any positive multiple cμc\mu to Tμ/∑gμgT\mu/\sum_g\mu_g, the same vector for every c>0c > 0. □\square

So the normalized profile of a homotypic doublet differs from a singlet of its type only by noise. The doublet has about twice the counts, so its noise is smaller, but its position in the embedding is the same in expectation. Scrublet, and every method that works on normalized profiles, finds mainly heterotypic doublets, of two different types, whose expected profile saμa+sbμbs_a\mu_a + s_b\mu_b lies between two types where few singlets are.

What the lines compute. Line L1 draws the pairs with replacement, as Scrublet does. Lines L2 to L4 apply the same scaling, the same gene means and standard deviations, and the same principal axes to the observed and the simulated profiles, so that both are in one space; the axes are fitted on the observed cells only. Lines L5 to L8 compute kadjk_{adj}, ndn_d, qq and S(q)S(q). Line L9 takes the valley of the smoothed histogram of the simulated scores, which have one mode near the prior (homotypic simulated doublets) and one high mode (heterotypic ones). Line L10 compares each observed score with it.

Complexity. With dd genes, pp components and a fixed rr, lines L1 to L3 take O(nd)O(nd) time, the covariance at line L4 takes O(nd2)O(nd^2), the eigendecomposition O(d3)O(d^3) per Jacobi sweep, and the projection O(ndp)O(ndp). The brute-force neighbor search at line L6 takes O(n2(p+log⁡n))O(n^2(p + \log n)), which is the largest term for many cells; Scrublet uses an approximate search there.

What the tests check. The test file checks Theorem 1 against Bayes' rule written with the two densities, for many values of ρ\rho, rr, kadjk_{adj} and ndn_d, and Lemma 2 for the monotone shape, the range and the value ρ\rho at the global mix. It checks the adjusted kk, the doublet sums and their draw order, the scaling, the threshold on a bimodal sample, and that a seed gives the same scores. For the group module it checks the neighbor search against sorting, the linear solver, the Jacobi eigenvectors and the Poisson draws. One simulation with three cell types measures how well heterotypic doublets are found and that homotypic doublets are not; this is a measurement, not a theorem.

Complexity

On a real RAM with rr fixed, lines L1 to L3 take O(nd)O(nd) time. Line L4 takes O(nd2)O(nd^2) for the covariance, O(d3)O(d^3) per sweep of the eigendecomposition, and O(ndp)O(ndp) for the projection. The brute-force search at line L6 takes O(n2(p+log⁡n))O(n^2(p + \log n)), which is the largest term for many cells. Scrublet uses an approximate nearest neighbor search there, which makes the method fast for 10510^5 cells. The extra space is O(n2)O(n^2) for the brute-force distances and O(nd+d2)O(nd + d^2) for the data and the covariance.

Properties

  • Randomized. The pairs of line L1 are random, so the scores change a little with the seed.
  • Bayesian score. The score is a posterior probability under a stated density model, with the doublet rate as the prior.
  • Unsupervised. It needs no labels, only the counts and an expected rate.
  • Blind to homotypic doublets. Two cells of one type make a profile like one cell of that type.
  • Depends on the embedding. The genes, the scaling and the number of components change the neighbors and so the scores.

Variants and improvements

  • DoubletFinder (McGinnis, Murrow and Gartner 2019) uses the proportion of artificial neighbors directly, chooses its neighborhood size by a sweep, and thresholds by the expected number of doublets.
  • Classifier methods train a classifier, for example gradient boosted trees, to separate real cells from simulated doublets.
  • Experimental methods use cell hashing with tagged antibodies, or genetic variants when cells of several donors are pooled. They also find homotypic doublets when the two cells come from different samples.
  • Cluster-aware simulation draws the pairs from different clusters only, to model heterotypic doublets.

When to use it

Use it on each sample of a droplet experiment before clustering, and remove the called doublets or mark them. It matters most when many cells were loaded, because the doublet rate grows with the load. Set ρ\rho from the load and the platform. When samples were pooled with hashtags or from several donors, use the experimental labels first and the score for the rest. Do not run it on data that already merges several samples, because the simulation would add counts of cells that could never share a droplet.

Pitfalls

  • The threshold. The valley of line L9 does not always exist. When the histogram of the simulated scores has no clear second mode, the threshold has to be set by hand, and the calls depend on it.
  • Homotypic doublets are not found. The fraction of doublets that Scrublet can see is smaller than ρ\rho when one cell type dominates.
  • Real intermediate states, such as cells in transition between two types, look like doublets of the two types and can get high scores.
  • Too few cells of a type give the simulated doublets little support, and the scores near that type are noisy.
  • Merged samples. Run it per sample, before integration or batch correction.

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.

doublet_detection.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/doublet-detection/. The authors are listed in prov/WZKYKW.jsonl.
"""Doublet scores in the manner of Scrublet (Wolock, Lopez and Klein 2019).

Steps: simulate doublets by adding the raw counts of two random observed cells,
normalize every profile to the same total, standardize each gene with the mean
and standard deviation of the observed cells, fit principal components on the
observed cells and project all profiles, find the k_adj nearest neighbors of
every profile among observed and simulated profiles, and turn the fraction of
simulated neighbors into a doublet probability with Bayes' rule.

What this small version leaves out, compared with the Scrublet package: the
selection of highly variable genes (the caller passes the genes to use), the
approximate neighbor search (the search here is brute force), the randomized
and sparse PCA solvers (here a full Jacobi eigendecomposition of the gene
covariance), the score of the simulated doublets of each observed cell, and
the error bars and z-scores of the scores. The defaults follow the package:
sim_ratio 2, expected doublet rate 0.1, k = round(0.5 sqrt(n)).
"""

from __future__ import annotations

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

from rq3lin import knn, pca_fit, pca_project

Matrix = List[List[float]]


def simulate_doublets(counts: Sequence[Sequence[float]], n_sim: int,
                      rng: random.Random) -> Tuple[Matrix, List[Tuple[int, int]]]:
    """n_sim profiles, each the sum of the raw counts of two observed cells.

    Draw order: for each doublet, rng.randrange(n) twice. As in Scrublet, the two
    cells are drawn with replacement, so a pair can repeat one cell.
    """
    n = len(counts)
    pairs, sims = [], []
    for _ in range(n_sim):
        a, b = rng.randrange(n), rng.randrange(n)
        pairs.append((a, b))
        sims.append([x + y for x, y in zip(counts[a], counts[b])])  # @line L1
    return sims, pairs


def normalize_total(X: Sequence[Sequence[float]], target: float) -> Matrix:
    """Scale each row to sum to target; a row of zeros stays zero."""
    out = []
    for row in X:
        t = sum(row)
        out.append([x * target / t for x in row] if t > 0 else [0.0] * len(row))
    return out


def standardize(obs: Matrix, sim: Matrix) -> Tuple[Matrix, Matrix]:
    """Z-scores of each gene, with the mean and standard deviation of the observed cells."""
    n, d = len(obs), len(obs[0])
    mu = [sum(r[g] for r in obs) / n for g in range(d)]
    sd = []
    for g in range(d):
        v = sum((r[g] - mu[g]) ** 2 for r in obs) / max(n - 1, 1)
        sd.append(math.sqrt(v) if v > 0 else 1.0)

    def z(X):
        return [[(r[g] - mu[g]) / sd[g] for g in range(d)] for r in X]

    return z(obs), z(sim)


def adjusted_k(k: int, n_obs: int, n_sim: int) -> int:
    """The neighbor count that keeps about k observed neighbors: round(k (1 + n_sim / n_obs))."""
    return int(round(k * (1.0 + n_sim / n_obs)))


def bayes_score(n_doublet_neighbors: int, k_adj: int, rho: float, r: float) -> float:
    """The doublet probability of Scrublet from the number of simulated neighbors.

    q = (nd + 1) / (k_adj + 2) and score = q rho / r / (1 - rho - q (1 - rho - rho / r)).
    """
    q = (n_doublet_neighbors + 1.0) / (k_adj + 2.0)  # @line L7
    return q * rho / r / (1.0 - rho - q * (1.0 - rho - rho / r))  # @line L8


def doublet_scores(counts: Sequence[Sequence[float]], rng: random.Random, sim_ratio: float = 2.0,
                   expected_rate: float = 0.1, k: Optional[int] = None, n_pcs: int = 10,
                   log_transform: bool = False) -> Tuple[List[float], List[float]]:
    """(scores of the observed cells, scores of the simulated doublets).

    counts holds one row of raw counts per cell, over the genes to use.
    """
    n = len(counts)
    if n < 3:
        raise ValueError("need at least 3 cells")
    if not 0.0 < expected_rate < 1.0:
        raise ValueError("expected_rate must be in (0, 1)")
    n_sim = int(round(sim_ratio * n))
    sim, _ = simulate_doublets(counts, n_sim, rng)
    target = sum(sum(r) for r in counts) / n
    obs_n = normalize_total(counts, target)  # @line L2
    sim_n = normalize_total(sim, target)
    if log_transform:
        obs_n = [[math.log1p(x) for x in r] for r in obs_n]
        sim_n = [[math.log1p(x) for x in r] for r in sim_n]
    obs_z, sim_z = standardize(obs_n, sim_n)  # @line L3
    mu, axes, _ = pca_fit(obs_z, min(n_pcs, len(obs_z[0])))  # @line L4
    emb = pca_project(obs_z, mu, axes) + pca_project(sim_z, mu, axes)
    if k is None:
        k = int(round(0.5 * math.sqrt(n)))
    k_adj = adjusted_k(k, n, n_sim)  # @line L5
    k_adj = min(k_adj, n + n_sim - 1)
    neighbors = knn(emb, k_adj)  # @line L6
    r = n_sim / n
    scores = [bayes_score(sum(1 for j in nb if j >= n), k_adj, expected_rate, r) for nb in neighbors]
    return scores[:n], scores[n:]


def threshold_minimum(values: Sequence[float], nbins: int = 50, max_iter: int = 10000) -> float:
    """The threshold at the valley of a bimodal histogram (the method of skimage threshold_minimum).

    Smooth the histogram with a 3-bin mean until it has exactly two local maxima,
    then return the center of the lowest bin between them.
    """
    lo, hi = min(values), max(values)
    if hi == lo:
        raise ValueError("all values are equal")
    width = (hi - lo) / nbins
    h = [0.0] * nbins
    for v in values:
        h[min(int((v - lo) / width), nbins - 1)] += 1.0
    for _ in range(max_iter):
        peaks = local_maxima(h)
        if len(peaks) == 2:
            a, b = peaks
            valley = min(range(a, b + 1), key=lambda i: (h[i], i))
            return lo + (valley + 0.5) * width  # @line L9
        if len(peaks) < 2:
            break
        h = [(h[max(i - 1, 0)] + h[i] + h[min(i + 1, nbins - 1)]) / 3.0 for i in range(nbins)]
    raise ValueError("the histogram does not become bimodal")


def local_maxima(h: Sequence[float]) -> List[int]:
    """The bins where the histogram stops rising and starts falling, as skimage finds them."""
    out, rising = [], True
    for i in range(len(h) - 1):
        if rising and h[i + 1] < h[i]:
            out.append(i)
            rising = False
        elif not rising and h[i + 1] > h[i]:
            rising = True
    return out


def call_doublets(scores: Sequence[float], threshold: float) -> List[bool]:
    """True for each cell whose score is above the threshold."""
    return [s > threshold for s in scores]  # @line L10
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_doublet_detection.py 200 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/doublet-detection/. The authors are listed in prov/WZKYKW.jsonl.

import math
import random

import pytest

from doublet_detection import (
    adjusted_k,
    bayes_score,
    call_doublets,
    doublet_scores,
    local_maxima,
    normalize_total,
    simulate_doublets,
    threshold_minimum,
)
from rq3lin import inverse, jacobi_eigh, knn, matmul, pca_fit, poisson_knuth, solve, sqdist


def cells(rng, n_per, n_types=3, d=30):
    """Cells of n_types types; type t has a mean of 8 on genes g with g mod n_types = t, and 1 elsewhere."""
    prof = [[8.0 if g % n_types == t else 1.0 for g in range(d)] for t in range(n_types)]
    X, lab = [], []
    for t in range(n_types):
        for _ in range(n_per):
            s = rng.uniform(0.6, 1.4)
            X.append([poisson_knuth(rng, s * m) for m in prof[t]])
            lab.append(t)
    return X, lab


def auc(pos, neg):
    w = sum(1.0 if p > q else 0.5 if p == q else 0.0 for p in pos for q in neg)
    return w / (len(pos) * len(neg))


# The group module rq3lin.

def test_knn_against_sorting_all_distances():
    rng = random.Random(1)
    pts = [[rng.randint(0, 3) for _ in range(2)] for _ in range(25)]
    for k in (0, 1, 4, 24):
        got = knn(pts, k)
        for i, nb in enumerate(got):
            order = sorted((j for j in range(25) if j != i), key=lambda j: (sqdist(pts[i], pts[j]), j))
            assert nb == order[:k]
    with pytest.raises(ValueError):
        knn(pts, 25)


def test_solve_and_inverse():
    rng = random.Random(2)
    for n in (1, 2, 5, 8):
        A = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(n)]
        x = [rng.uniform(-1, 1) for _ in range(n)]
        b = [sum(A[i][j] * x[j] for j in range(n)) for i in range(n)]
        assert all(math.isclose(u, v, abs_tol=1e-9) for u, v in zip(solve(A, b), x))
        P = matmul(A, inverse(A))
        assert all(abs(P[i][j] - (i == j)) < 1e-9 for i in range(n) for j in range(n))
    with pytest.raises(ValueError):
        solve([[1.0, 2.0], [2.0, 4.0]], [1.0, 2.0])


def test_jacobi_eigh():
    rng = random.Random(3)
    for n in (1, 3, 6, 10):
        B = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(n)]
        S = [[B[i][j] + B[j][i] for j in range(n)] for i in range(n)]
        vals, vecs = jacobi_eigh(S)
        assert vals == sorted(vals, reverse=True)
        for lam, v in zip(vals, vecs):
            Sv = [sum(S[i][j] * v[j] for j in range(n)) for i in range(n)]
            assert all(abs(a - lam * b) < 1e-9 for a, b in zip(Sv, v))
            assert math.isclose(sum(x * x for x in v), 1.0, rel_tol=1e-12)
        assert math.isclose(sum(vals), sum(S[i][i] for i in range(n)), abs_tol=1e-9)


def test_pca_of_points_on_a_line():
    pts = [[t, 2 * t, -t] for t in range(-3, 4)]
    mu, axes, var = pca_fit(pts, 1)
    s = math.sqrt(6)
    assert all(math.isclose(a, b, abs_tol=1e-12) for a, b in zip(axes[0], [1 / s, 2 / s, -1 / s]))
    assert math.isclose(var[0], 6 * sum(t * t for t in range(-3, 4)) / 6, rel_tol=1e-12)


def test_poisson_knuth_mean_and_variance():
    rng = random.Random(4)
    lam, n = 3.5, 4000
    xs = [poisson_knuth(rng, lam) for _ in range(n)]
    m = sum(xs) / n
    v = sum((x - m) ** 2 for x in xs) / (n - 1)
    assert abs(m - lam) <= 4 * math.sqrt(lam / n)
    assert abs(v - lam) <= 4 * math.sqrt(2 * lam * lam / n + lam / n)


# The doublet scores.

def test_simulated_doublets_are_sums_of_two_cells():
    rng = random.Random(5)
    X = [[rng.randint(0, 9) for _ in range(4)] for _ in range(6)]
    sims, pairs = simulate_doublets(X, 20, random.Random(6))
    again = random.Random(6)
    for s, (a, b) in zip(sims, pairs):
        assert (a, b) == (again.randrange(6), again.randrange(6))
        assert s == [x + y for x, y in zip(X[a], X[b])]


def test_normalize_total():
    out = normalize_total([[1, 3], [0, 0], [2, 2]], 8.0)
    assert out == [[2.0, 6.0], [0.0, 0.0], [4.0, 4.0]]


def test_adjusted_k():
    assert adjusted_k(5, 100, 200) == 15
    assert adjusted_k(6, 400, 800) == 18
    assert adjusted_k(7, 10, 5) == 10


def test_score_is_bayes_rule_with_neighbor_densities():
    """Treat the observed neighbors as singlets with density fs and the simulated ones as doublets."""
    for rho in (0.05, 0.1, 0.3):
        for r in (0.5, 1.0, 2.0):
            for k_adj in (3, 10, 31):
                for nd in range(k_adj + 1):
                    q = (nd + 1) / (k_adj + 2)
                    fd, fs = q / r, 1 - q          # sim density r fd, obs density fs
                    post = rho * fd / (rho * fd + (1 - rho) * fs)
                    assert math.isclose(bayes_score(nd, k_adj, rho, r), post, rel_tol=1e-12)


def test_score_is_increasing_in_simulated_neighbors_and_in_zero_one():
    for rho in (0.02, 0.1, 0.5):
        for r in (0.5, 2.0):
            k_adj = 20
            s = [bayes_score(nd, k_adj, rho, r) for nd in range(k_adj + 1)]
            assert all(a < b for a, b in zip(s, s[1:]))
            assert 0.0 < s[0] and s[-1] < 1.0


def test_score_is_rho_when_the_neighborhood_has_the_global_mix():
    # q = r / (1 + r) means f_d = f_s, so the posterior is the prior.
    for r, k_adj, nd in ((2.0, 13, 9), (1.0, 8, 4), (3.0, 6, 5)):
        assert math.isclose((nd + 1) / (k_adj + 2), r / (1 + r))
        for rho in (0.05, 0.2):
            assert math.isclose(bayes_score(nd, k_adj, rho, r), rho, rel_tol=1e-12)


def test_local_maxima_and_threshold():
    assert local_maxima([0, 2, 5, 3, 1, 4, 6, 2]) == [2, 6]
    assert local_maxima([1, 2, 3]) == []
    rng = random.Random(7)
    vals = [rng.gauss(0.1, 0.03) for _ in range(300)] + [rng.gauss(0.7, 0.05) for _ in range(150)]
    t = threshold_minimum(vals)
    assert 0.1 + 3 * 0.03 < t < 0.7 - 3 * 0.05   # inside the gap between the two modes
    with pytest.raises(ValueError):
        threshold_minimum([1.0, 1.0])
    assert call_doublets([0.1, 0.5, 0.3], 0.3) == [False, True, False]


def test_same_seed_same_scores():
    X, _ = cells(random.Random(8), 12)
    a = doublet_scores(X, random.Random(9))
    b = doublet_scores(X, random.Random(9))
    assert a == b


def test_errors():
    with pytest.raises(ValueError):
        doublet_scores([[1, 2], [3, 4]], random.Random(1))
    with pytest.raises(ValueError):
        doublet_scores([[1, 2]] * 5, random.Random(1), expected_rate=0.0)


def test_heterotypic_doublets_found_homotypic_missed_measured():
    """A measurement, not a theorem: 150 singlets of 3 types, 15 doublets of two types, 10 of one type."""
    rng = random.Random(1)
    X, lab = cells(rng, 50)
    n = len(X)
    het, homo = [], []
    for _ in range(15):
        a, b = rng.randrange(n), rng.randrange(n)
        while lab[b] == lab[a]:
            b = rng.randrange(n)
        het.append([x + y for x, y in zip(X[a], X[b])])
    for _ in range(10):
        a, b = rng.randrange(n), rng.randrange(n)
        while lab[b] != lab[a] or b == a:
            b = rng.randrange(n)
        homo.append([x + y for x, y in zip(X[a], X[b])])
    obs, sim = doublet_scores(X + het + homo, random.Random(101))
    single, s_het, s_homo = obs[:n], obs[n:n + 15], obs[n + 15:]
    assert auc(s_het, single) > 0.95
    assert auc(s_homo, single) < 0.8
    t = threshold_minimum(sim)
    calls = call_doublets(obs, t)
    assert sum(calls[n:n + 15]) >= 12
    assert sum(calls[:n]) <= 5
    assert sum(calls[n + 15:]) <= 3

History

Macosko et al. (2015) measured the rate of barcodes with two cells by mixing human and mouse cells, which gives reads of both species in a doublet. Experimental methods with tagged antibodies and with genetic variants followed. Wolock, Lopez and Klein (2019) published Scrublet, and McGinnis, Murrow and Gartner (2019) published DoubletFinder in the same issue of Cell Systems. Both score cells against simulated doublets in a reduced space.

References

  1. Samuel L. Wolock, Romain Lopez and Allon M. Klein, Scrublet, computational identification of cell doublets in single-cell transcriptomic data, Cell Systems 8(4) (2019), 281-291, the simulation of doublets, the k-nearest-neighbor classifier with the adjusted k, and the doublet score with the expected doublet rate
  2. Christopher S. McGinnis, Lyndsay M. Murrow and Zev J. Gartner, DoubletFinder, doublet detection in single-cell RNA sequencing data using artificial nearest neighbors, Cell Systems 8(4) (2019), 329-337, the proportion of artificial nearest neighbors as a doublet score
  3. Evan Z. Macosko et al., Highly parallel genome-wide expression profiling of individual cells using nanoliter droplets, Cell 161(5) (2015), 1202-1214, the mixed species experiment that measures the rate of barcodes with two cells

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