Algorithm Search⌘K

Algorithmadvanced

Pooled size factor deconvolution

Also called scran pooling normalization.

Sum counts over pools of cells, compute size factors for the pools, and solve a linear system for the size factor of each cell.

Time
O(q n m (w + log m) + q n w^2 + n^3) worst
Space
O(n^2 + m n) extra
Where
m = the number of genes; n = the number of cells; q = the number of pool sizes; w = the largest pool size
Properties
deterministicnot exactofflineiterative
Origin
Aaron T. L. Lun, Karsten Bach, John C. Marioni, 2016

Pooled size factor deconvolution finds a size factor for each cell of a single-cell RNA-seq experiment, the number by which its counts are divided to make cells comparable. Bulk methods such as median of ratios fail on single cells, because most counts of a cell are 0 and the median of its ratios is often 0. Lun, Bach and Marioni (2016) sum the cells into pools, where counts are large, and compute a median-of-ratios factor for each pool against an average cell. The factor of a pool is the sum of the unknown factors of its cells, so many overlapping pools give a linear system, and its least squares solution gives the factor of each cell. It solves the library size normalization problem for single cells. It differs from scaling by the library size, the total count of the cell, in that it does not assume that all genes keep their share of the total.

In plain words

You want to know how much each cell was sampled, but each cell has too few reads: most genes show zero, so the usual trick of comparing gene by gene gives nothing. So add cells together. A group of twenty cells has enough reads, and comparing the group with an average cell, gene by gene, gives a good number for the group. That number is the sum of the numbers of its cells. Make many groups that overlap: line the cells up in a ring and slide windows of several widths along it. Each window gives one sum. With enough sums you can solve for each cell, as in a puzzle where you know the sums of many rows of a grid. Cells of similar size go into the same windows, so the sums are not dominated by a few large cells.

The problem

Input. A matrix of counts Ygj≥0Y_{gj} \ge 0 for mm genes and nn cells, a set WW of pool sizes (20, 40, 60, 80 and 100 in the paper), and optionally a clustering of the cells.

Output. Size factors θ^1,…,θ^n>0\hat\theta_1, \dots, \hat\theta_n > 0, scaled to mean 1.

Model. E[Ygj]=θjλgjE[Y_{gj}] = \theta_j\lambda_{gj}, and λgj=λg\lambda_{gj} = \lambda_g for more than half of the genes: most genes do not change between cells, the same assumption as for bulk data. Within a cluster this needs to hold only inside the cluster.

The algorithm

  1. POOLED-SIZE-FACTORS(Y, W) ▷ Y: m genes by n cells; W: pool sizes
  2. 1t_j ← Σ_g Y[g][j]; Z[g][j] ← Y[g][j] / t_j
  3. 2U[g] ← (1/n) Σ_j Z[g][j] ▷ the average cell
  4. 3sort the cells by t; put odd ranks up one side of a ring and even ranks down the other
  5. 4for each w in W and each start s on the ring do S ← the w cells from s on
  6. 5f_S ← median over g with U[g] > 0 of (Σ_{j∈S} Z[g][j]) / U[g]
  7. 6add the equation Σ_{j∈S} x_j = f_S for each pool S, with weight 1
  8. 7add the equation x_j = median over g of Z[g][j] / U[g] for each cell j, with weight 10^-6
  9. 8x ← the weighted least squares solution of all equations
  10. 9θ_j ← x_j t_j
  11. 10with clusters, run L1 to L9 in each cluster, then scale each cluster by a median ratio to a reference
  12. 11return θ divided by its mean

Line L1 divides each cell by its library size. The unknown is then xj=θj/tjx_j = \theta_j/t_j, which corrects the library size for genes that take a larger or smaller share in that cell; line L9 multiplies the library size back. Line L2 is the reference: an average cell, so every pool is compared with the same profile. Line L5 is the median-of-ratios factor of the pool against this reference. Line L3 makes the pools: the ring alternates the ranks, so that a window of consecutive cells holds cells of similar library size. With all window sizes, each cell is in 20+40+60+80+100=30020 + 40 + 60 + 80 + 100 = 300 pools. Lines L6 to L8 solve the system by least squares; the code forms the normal equations and solves them by Gaussian elimination. Line L7 adds one weak equation per cell, the single-cell median of ratios, with a tiny weight. It changes the answer very little when the pool equations determine it, and it fixes the answer when they do not.

With clusters, each cluster is normalized on its own, so the genes need to be stable only inside a cluster. The clusters are then put on one scale by the median ratio of their average normalized profiles to that of a reference cluster. The code takes the largest cluster as the reference.

Example

Four cells and three genes. The true factors are 1,2,1,41, 2, 1, 4, and gene 3 is six times higher in cell 4.

gene cell 1 cell 2 cell 3 cell 4
1 10 20 10 40
2 6 12 6 24
3 4 8 4 96
tjt_j 20 40 20 160

The library sizes say that cell 4 is 8 times cell 1, but the truth is 4. Dividing by tjt_j gives Z=(0.5,0.3,0.2)Z = (0.5, 0.3, 0.2) for cells 1 to 3 and (0.25,0.15,0.6)(0.25, 0.15, 0.6) for cell 4, so U=(0.4375,0.2625,0.3)U = (0.4375, 0.2625, 0.3). Sorted by size the cells are 1, 3, 2, 4, and the ring is 1, 2, 4, 3. With pool sizes 2 and 3 there are 8 pools. For the pool {2,4}\{2, 4\}, V=(0.75,0.45,0.8)V = (0.75, 0.45, 0.8) and V/U=(1.714,1.714,2.667)V/U = (1.714, 1.714, 2.667), so f=1.714=12/7f = 1.714 = 12/7. All the pool factors, in sevenths:

pool {1, 2} {2, 4} {4, 3} {3, 1} {1, 2, 4} {2, 4, 3} {4, 3, 1} {3, 1, 2}
7fS7f_S 16 12 12 16 20 20 20 24

The solution is x=(8,8,8,4)/7x = (8, 8, 8, 4)/7, and θ=x t=(160,320,160,640)/7\theta = x\,t = (160, 320, 160, 640)/7, which is (0.5,1,0.5,2)(0.5, 1, 0.5, 2) after scaling to mean 1. This is the truth: cell 4 is 4 times cell 1. The pools of size 2 alone would not be enough. On a ring of 4 they give the equations x1+x2x_1 + x_2, x2+x4x_2 + x_4, x4+x3x_4 + x_3 and x3+x1x_3 + x_1, and adding (1,−1,1,−1)(1, -1, 1, -1) in ring order changes none of these sums.

Correctness

The proof shows that the method is exact when the counts of more than half of the genes are proportional to the true factors. Each such gene gives the pool ratio ∑j∈Sxj/xˉ\sum_{j \in S}x_j/\bar x, so the median takes that value, every equation holds exactly, and the solution returns the true factors up to one constant. It also shows that the pool equations alone can fail to determine the factors. The pool matrices are circulant, and they share a null vector exactly when the number of cells nn divides kwkw for every pool size ww and some 0<k<n0 < k < n. With the sizes of the paper this happens for every even nn and every multiple of 5. The weak equations of line L7 make the system positive definite, so the solution is always unique. With clusters, the method is exact when the condition holds inside each cluster and between each cluster and the reference. With real counts the factors carry noise, and the size of that error is measured, not proved.

Proof: Pooled size factors are exact when more than half of the genes do not change, and the weak equations make the linear system uniquely solvablefull

We prove that pooling and deconvolution recover the true size factors, up to one common constant, in exact arithmetic when the counts of more than half of the genes are proportional to the size factors (Theorem 2). We show when the pool equations alone have more than one solution (Lemma 3), and that the weak equations of line L7 always make the solution unique (Lemma 4). With clusters, the same holds when the condition holds inside each cluster and between each cluster and the reference (Theorem 5). That real counts satisfy these conditions is a modelling assumption, and with Poisson noise the factors have an error that the tests measure but the proof does not bound.

Setting. Counts Ygj≥0Y_{gj} \ge 0 for genes g=1,…,Gg = 1, \dots, G and cells j=1,…,nj = 1, \dots, n, with library sizes tj=∑gYgj>0t_j = \sum_g Y_{gj} > 0. Line L1 sets Zgj=Ygj/tjZ_{gj} = Y_{gj}/t_j and line L2 sets Ug=1n∑jZgjU_g = \frac1n\sum_j Z_{gj}. For a pool SS, line L5 sets fS=median⁡{Vg/Ug:Ug>0}f_S = \operatorname{median}\{V_g/U_g : U_g > 0\} with Vg=∑j∈SZgjV_g = \sum_{j \in S} Z_{gj}. Lines L6 to L8 minimize

F(x)=∑S(∑j∈Sxj−fS)2+ε∑j(xj−ej)2,F(x) = \sum_S \Big(\sum_{j \in S} x_j - f_S\Big)^2 + \varepsilon\sum_j (x_j - e_j)^2,

where ej=median⁡{Zgj/Ug:Ug>0}e_j = \operatorname{median}\{Z_{gj}/U_g : U_g > 0\} is the single-cell estimate and ε=10−6\varepsilon = 10^{-6}. Line L9 returns θ^j=xjtj\hat\theta_j = x_j t_j, and line L11 divides by the mean.

Model. There are true factors θj>0\theta_j > 0 and a set NN of genes, the non-DE genes, with Ygj=θjλgY_{gj} = \theta_j\lambda_g for g∈Ng \in N, λg>0\lambda_g > 0. The other genes may have any counts. Let P={g:Ug>0}P = \{g : U_g > 0\}, so N⊆PN \subseteq P, and assume ∣N∣>∣P∣/2|N| > |P|/2.

Lemma 1 (ratios of the non-DE genes). Let xj=θj/tjx_j = \theta_j/t_j and xˉ=1n∑jxj\bar x = \frac1n\sum_j x_j. For g∈Ng \in N and every pool SS, Vg/Ug=∑j∈Sxj/xˉV_g/U_g = \sum_{j \in S}x_j/\bar x, and Zgj/Ug=xj/xˉZ_{gj}/U_g = x_j/\bar x.

Proof. For g∈Ng \in N, Zgj=θjλg/tj=xjλgZ_{gj} = \theta_j\lambda_g/t_j = x_j\lambda_g, so Ug=λgxˉU_g = \lambda_g\bar x and Vg=λg∑j∈SxjV_g = \lambda_g\sum_{j \in S}x_j. Divide. □\square

The ratios do not depend on gg. This is why the method divides by the library size before pooling: the library size of a cell is not proportional to θj\theta_j when other genes change, but xjx_j absorbs it, and line L9 multiplies it back.

Theorem 2 (exact recovery). Under the model, the minimizer of FF is xj∗=xj/xˉx^\ast_j = x_j/\bar x, and the returned factors are θj/θˉ\theta_j/\bar\theta, with θˉ\bar\theta the mean of the true factors.

Proof. By Lemma 1, more than half of the values in each median of line L5 equal ∑j∈Sxj/xˉ\sum_{j \in S}x_j/\bar x. When more than half of a list of values equal cc, the median is cc; the proof of this fact is in the proof of median-of-ratios normalization. So fS=∑j∈Sxj∗f_S = \sum_{j \in S}x^\ast_j for every pool, and in the same way ej=xj∗e_j = x^\ast_j. Then F(x∗)=0F(x^\ast) = 0, and F≥0F \ge 0, so x∗x^\ast is a minimizer. It is the only one by Lemma 4. Line L9 gives θ^j=xj∗tj=θj/xˉ\hat\theta_j = x^\ast_j t_j = \theta_j/\bar x, and dividing by the mean gives θj/θˉ\theta_j/\bar\theta. □\square

Lemma 3 (the pool equations alone). Let the pools be all windows of ww consecutive positions on a ring of nn cells, for each ww in a set WW, and let AA be the matrix of these equations. Then AA has a nonzero null vector if and only if there is an integer kk, 0<k<n0 < k < n, such that nn divides kwkw for every w∈Ww \in W. Then vp=cos⁡(2πkp/n)v_p = \cos(2\pi kp/n), on ring positions pp, is such a vector.

Proof. For one ww, the pool matrix CwC_w has a row for each start ss with ones at positions s,…,s+w−1s, \dots, s + w - 1 modulo nn. It is a circulant matrix, so the vectors ϕk(p)=ωkp\phi_k(p) = \omega^{kp} with ω=e2πi/n\omega = e^{2\pi i/n} are its eigenvectors, with eigenvalues μw(k)=∑i=0w−1ωki\mu_w(k) = \sum_{i=0}^{w-1}\omega^{ki}. For k=0k = 0, μw(0)=w>0\mu_w(0) = w > 0. For 0<k<n0 < k < n, ωk≠1\omega^k \ne 1 and μw(k)=(ωkw−1)/(ωk−1)\mu_w(k) = (\omega^{kw} - 1)/(\omega^k - 1), which is 0 if and only if ωkw=1\omega^{kw} = 1, that is, nn divides kwkw. Now A∗A=∑w∈WCw∗CwA^\ast A = \sum_{w \in W} C_w^\ast C_w has the same eigenvectors with eigenvalues ∑w∣μw(k)∣2\sum_w|\mu_w(k)|^2. This sum is 0 if and only if every μw(k)=0\mu_w(k) = 0, and AA has a nonzero null vector if and only if A∗AA^\ast A has the eigenvalue 0. When μw(k)=0\mu_w(k) = 0 for all ww, Cwϕk=0C_w\phi_k = 0, and since CwC_w is real, the real part vv of ϕk\phi_k also satisfies Cwv=0C_wv = 0. □\square

The sizes 20,40,60,80,10020, 40, 60, 80, 100 of the paper are all multiples of 20, and 20 is one of them, so the condition is that nn divides 20k20k for some 0<k<n0 < k < n. This holds if and only if gcd⁡(n,20)>1\gcd(n, 20) > 1, with k=n/gcd⁡(n,20)k = n/\gcd(n, 20): for every even nn and every multiple of 5. For n=100n = 100, k=5k = 5. For n=101n = 101 no kk works. On such a null vector the pool equations cannot tell the factors apart: adding c vc\,v to xx changes no pool sum.

Lemma 4 (uniqueness). For every ε>0\varepsilon > 0, FF has exactly one minimizer, the solution of (A⊤A+εI)x=A⊤f+εe(A^\top A + \varepsilon I)x = A^\top f + \varepsilon e.

Proof. FF is a quadratic with Hessian 2(A⊤A+εI)2(A^\top A + \varepsilon I). For y≠0y \ne 0, y⊤(A⊤A+εI)y=∥Ay∥2+ε∥y∥2>0y^\top(A^\top A + \varepsilon I)y = \|Ay\|^2 + \varepsilon\|y\|^2 > 0, so the Hessian is positive definite, FF is strictly convex, and its only stationary point, the solution of the normal equations, is its minimizer. □\square

When AA has full column rank, the weak equations move the solution by O(ε)O(\varepsilon) in general, and not at all in the setting of Theorem 2. When AA has a null space, the weak equations fix the component of xx in it to that of the single-cell estimates. In floating point the normal matrix then has a condition number of order ∥A∥2/ε\|A\|^2/\varepsilon, so rounding errors grow by that factor; the tests use a tolerance of 10−510^{-5} for this reason.

Theorem 5 (clusters). Suppose the cells are split into clusters, the model holds inside each cluster with its own non-DE set, and line L10 scales cluster cc by τc=median⁡gPcg/Prg\tau_c = \operatorname{median}_g P_{cg}/P_{rg} over genes positive in both, where PcgP_{cg} is the mean of Ygj/θ^jY_{gj}/\hat\theta_j over the cells of cc and rr is the reference cluster. If more than half of these genes have Ygj=θjλgY_{gj} = \theta_j\lambda_g in both clusters, then the final factors are θj/θˉ\theta_j/\bar\theta for all cells.

Proof. By Theorem 2 applied to cluster cc alone, θ^j=θj/κc\hat\theta_j = \theta_j/\kappa_c for j∈cj \in c, with a constant κc>0\kappa_c > 0. For a gene with Ygj=θjλgY_{gj} = \theta_j\lambda_g in both clusters, Ygj/θ^j=κcλgY_{gj}/\hat\theta_j = \kappa_c\lambda_g, so Pcg=κcλgP_{cg} = \kappa_c\lambda_g and Pcg/Prg=κc/κrP_{cg}/P_{rg} = \kappa_c/\kappa_r. More than half of the ratios equal this, so τc=κc/κr\tau_c = \kappa_c/\kappa_r, and τcθ^j=θj/κr\tau_c\hat\theta_j = \theta_j/\kappa_r for every cell of every cluster. Line L11 divides by the mean, which gives θj/θˉ\theta_j/\bar\theta. □\square

So with clusters the non-DE condition is needed inside each cluster and between each cluster and the reference, not over all cells at once.

What the lines compute. Lines L1 and L2 compute ZZ and UU. Line L3 builds the ring, and line L4 the windows; each cell is in ww windows of size ww, so in ∑w∈Ww\sum_{w \in W}w pools. Line L5 computes fSf_S, skipping genes with Ug=0U_g = 0. Lines L6 to L8 build A⊤A+εIA^\top A + \varepsilon I and A⊤f+εeA^\top f + \varepsilon e directly and solve by Gaussian elimination with partial pivoting. Line L9 multiplies by tjt_j, line L10 is Theorem 5, and line L11 scales to mean 1. Theorem 2 does not use the ring order: it holds for any set of pools. The ring order matters only for noise, because it puts cells of similar size in one pool.

Complexity. With q=∣W∣q = |W| pool sizes and wmaxw_{max} the largest, line L5 takes O(Gw)O(Gw) per pool plus a median, so O(qn(Gwmax+Glog⁡G))O(qn(Gw_{max} + G\log G)) in all. Building the normal matrix takes O(qnwmax2)O(qnw_{max}^2), and solving it O(n3)O(n^3). scran solves the sparse system instead, which is much faster for many cells.

What the tests check. The test file checks Theorem 2 with 0, 20 and 45 percent of changed genes, that the library size is wrong on such data, Theorem 5 with two clusters, and the page example with its singular pools of size 2. It compares the floating point solution with an exact rational solution of the same normal equations. It checks Lemma 3 with the null vector for n=100n = 100 and the divisibility condition for n=100n = 100 and n=101n = 101, and that each cell is in 300 pools with the default sizes. A simulation with Poisson counts, more than half of them 0, measures that the pooled factors have a smaller error and a smaller composition bias than the library size, and that most single-cell medians are 0. These are measurements, not theorems.

Complexity

On a real RAM, line L1 reads the matrix once in O(mn)O(mn) time. There are qnqn pools for qq pool sizes. Each takes O(mw)O(mw) time for the sums and O(mlog⁡m)O(m\log m) for the median, which gives O(qnm(w+log⁡m))O(qnm(w + \log m)) in all. Building the normal equations takes O(qnw2)O(qnw^2) time and solving them by elimination takes O(n3)O(n^3), with O(n2)O(n^2) space. scran solves the sparse system directly, which scales to many thousands of cells; the dense solve here is meant for small nn.

Properties

  • Robust to a minority of changed genes, like median of ratios, but usable when most counts are 0.
  • Exact in the noiseless model, for any choice of pools, as long as the weak equations are there.
  • Deterministic. The ring and the pools depend only on the library sizes.
  • Scale free. The factors are relative and have mean 1.
  • Local in the ring. Each pool holds cells of similar library size, which keeps the noise of the pool sums balanced.

Variants and improvements

  • Clustering first. scran runs a quick clustering and normalizes each cluster on its own, which weakens the assumption to "most genes do not change inside a cluster".
  • Positive solutions. Least squares can give negative factors for cells with very few counts. The paper discusses constrained solvers that keep the factors positive; removing such cells is the simple fix.
  • Pool sizes. Larger pools give less noisy pool factors but fewer independent equations per cell. Sizes that share a factor with nn leave the pool system singular, and the weak equations then fix part of the answer.
  • Library size factors. Plain division by the total count is the fast default in many pipelines. It is correct only when no large set of genes changes in one direction.
  • Spike-ins. Factors from external spike-in RNA measure the total RNA of a cell, which is a different quantity from the factors here.

When to use it

Use it for single-cell counts before log transformation, highly variable gene selection and clustering, when you expect real composition differences between cells, such as a few genes that take a large share in one cell type. It needs enough cells for the pools: at least as many as the largest pool size, per cluster. For bulk RNA-seq with few zeros use median of ratios or TMM directly.

Pitfalls

  • Cells with very low counts can get factors near 0 or negative. Filter low quality cells first.
  • Too few cells per cluster. All pool sizes must fit in each cluster; smaller sizes help but give noisier pool factors.
  • Strong DE between all clusters. The scaling between clusters still needs most genes to be stable between each cluster and the reference.
  • Genes with zero mean carry no information and are skipped; filtering genes with a very low mean speeds up the computation and does not change the answer much.
  • Factors are not totals. They have mean 1 and are relative; do not mix them with library sizes from another method.

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.

pooling_size_factors.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pooling-size-factors/. The authors are listed in prov/EQZ9B0.jsonl.
"""Size factors of single cells by pooling and deconvolution (Lun, Bach and Marioni 2016).

counts[g][j] is the count of gene g in cell j. With t_j the library size of
cell j and Z[g][j] = counts[g][j] / t_j, the reference pseudo-cell is
U[g] = the mean of Z[g][j] over all cells. For a pool S of cells,
V[g] = the sum of Z[g][j] over S, and the pool factor is the median over genes
of V[g] / U[g]. Under the model of the paper this estimates the sum over S of
x_j = theta_j / t_j, up to one constant. The pools are windows of w
consecutive cells on a ring of the cells ordered by library size, for several
window sizes. The equations "sum of x over S = pool factor", together with
weak equations "x_j = single-cell estimate", are solved by weighted least
squares, and theta_j = x_j t_j. The factors are scaled to mean 1.

An optional clustering step normalizes each cluster on its own and then
scales the clusters to each other by the median ratio of their average
normalized profiles, as in scran.
"""

from __future__ import annotations

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

from rq3lin import solve

DEFAULT_SIZES = (20, 40, 60, 80, 100)
WEAK = 1e-6


def ring_order(lib_sizes: Sequence[float]) -> List[int]:
    """Cells by library size; ranks 1, 3, 5, ... go up one side of the ring and ranks 2, 4, 6, ... come down the other."""
    order = sorted(range(len(lib_sizes)), key=lambda j: (lib_sizes[j], j))
    return order[0::2] + order[1::2][::-1]  # @line L3


def ring_pools(n: int, sizes: Sequence[int]) -> List[List[int]]:
    """All windows of w consecutive positions on a ring of n, for each w in sizes, as position lists."""
    pools = []
    for w in sizes:
        if not 1 <= w <= n:
            raise ValueError("each pool size must be between 1 and the number of cells")
        for s in range(n):
            pools.append([(s + i) % n for i in range(w)])  # @line L4
    return pools


def median_ratio(values: Sequence[float], ref: Sequence[float]) -> float:
    """The median over genes with ref > 0 of values / ref."""
    ratios = [v / u for v, u in zip(values, ref) if u > 0]
    if not ratios:
        raise ValueError("no gene has a positive reference")
    return statistics.median(ratios)


def build_system(counts: Sequence[Sequence[float]], sizes: Sequence[int] = DEFAULT_SIZES,
                 weak: float = WEAK) -> Tuple[List[List[int]], List[float], List[float], List[float]]:
    """(pools as cell lists, pool factors, single-cell estimates, library sizes) for one group of cells."""
    G, n = len(counts), len(counts[0])
    t = [sum(counts[g][j] for g in range(G)) for j in range(n)]
    if min(t) <= 0:
        raise ValueError("every cell needs a positive library size")
    Z = [[counts[g][j] / t[j] for j in range(n)] for g in range(G)]  # @line L1
    U = [sum(row) / n for row in Z]  # @line L2
    ring = ring_order(t)
    pools = [[ring[p] for p in pool] for pool in ring_pools(n, sizes)]
    factors = []
    for S in pools:
        V = [sum(Z[g][j] for j in S) for g in range(G)]
        factors.append(median_ratio(V, U))  # @line L5
    single = [median_ratio([Z[g][j] for g in range(G)], U) for j in range(n)]
    return pools, factors, single, t


def solve_pools(n: int, pools: Sequence[Sequence[int]], factors: Sequence[float],
                single: Sequence[float], weak: float = WEAK) -> List[float]:
    """Weighted least squares for x: the pool equations with weight 1 and x_j = single_j with weight weak.

    The normal equations (A^T W A) x = A^T W b are solved by Gaussian elimination.
    """
    N = [[0.0] * n for _ in range(n)]
    rhs = [0.0] * n
    for S, f in zip(pools, factors):  # @line L6
        for a in S:
            rhs[a] += f
            row = N[a]
            for b in S:
                row[b] += 1.0
    for j in range(n):  # @line L7
        N[j][j] += weak
        rhs[j] += weak * single[j]
    return solve(N, rhs)  # @line L8


def deconvolve(counts: Sequence[Sequence[float]], sizes: Sequence[int] = DEFAULT_SIZES,
               weak: float = WEAK) -> List[float]:
    """Size factors theta_j = x_j t_j of one group of cells, before centering."""
    n = len(counts[0])
    pools, factors, single, t = build_system(counts, sizes, weak)
    x = solve_pools(n, pools, factors, single, weak)
    return [x[j] * t[j] for j in range(n)]  # @line L9


def pooled_size_factors(counts: Sequence[Sequence[float]], sizes: Sequence[int] = DEFAULT_SIZES,
                        clusters: Optional[Sequence[int]] = None, weak: float = WEAK) -> List[float]:
    """Size factors of all cells, scaled to mean 1.

    With clusters, each cluster is deconvolved on its own (all pool sizes must fit
    in each cluster), and cluster c is then multiplied by the median over genes of
    its mean normalized profile divided by that of the largest cluster.
    """
    G, n = len(counts), len(counts[0])
    if clusters is None:
        clusters = [0] * n
    groups: Dict[int, List[int]] = {}
    for j, c in enumerate(clusters):
        groups.setdefault(c, []).append(j)
    theta = [0.0] * n
    profile = {}
    for c, cells in groups.items():
        sub = [[counts[g][j] for j in cells] for g in range(G)]
        th = deconvolve(sub, sizes, weak)
        for j, v in zip(cells, th):
            theta[j] = v
        profile[c] = [sum(counts[g][j] / theta[j] for j in cells) / len(cells) for g in range(G)]
    ref = max(groups, key=lambda c: (len(groups[c]), -c))
    for c, cells in groups.items():
        if c == ref:
            continue
        both = [(p, q) for p, q in zip(profile[c], profile[ref]) if p > 0 and q > 0]
        tau = statistics.median(p / q for p, q in both) if both else 1.0  # @line L10
        for j in cells:
            theta[j] *= tau
    mean = sum(theta) / n
    return [v / mean for v in theta]  # @line L11
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_pooling_size_factors.py 205 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pooling-size-factors/. The authors are listed in prov/EQZ9B0.jsonl.

import math
import random
from fractions import Fraction

import pytest

from pooling_size_factors import (
    build_system,
    median_ratio,
    pooled_size_factors,
    ring_order,
    ring_pools,
    solve_pools,
)
from rq3lin import poisson_knuth

# The answers below are exact in exact arithmetic. In floating point the normal
# matrix can be nearly singular (see the circulant test), with a condition number
# up to about (total pool size) / weak, so rounding errors of about 1e-16 grow to
# about 1e-7. The tolerance leaves a factor of 100 on that.
TOL = 1e-5


def exact_data(rng, G, n, de_frac, clusters=None):
    """counts[g][j] = theta_j lam_g for non-DE genes; DE genes get a cell-specific factor."""
    theta = [rng.uniform(0.3, 3.0) for _ in range(n)]
    lam = [rng.uniform(1.0, 50.0) for _ in range(G)]
    n_de = int(de_frac * G)
    counts = []
    for g in range(G):
        row = []
        for j in range(n):
            f = 1.0
            if g < n_de:
                f = rng.choice([0.1, 1.0, 8.0]) if clusters is None else (6.0 if clusters[j] == 1 else 1.0)
            row.append(theta[j] * lam[g] * f)
        counts.append(row)
    return counts, theta


def centered(v):
    m = sum(v) / len(v)
    return [x / m for x in v]


def frac_solve(A, b):
    n = len(A)
    M = [A[i][:] + [b[i]] for i in range(n)]
    for c in range(n):
        p = next(r for r in range(c, n) if M[r][c] != 0)
        M[c], M[p] = M[p], M[c]
        for r in range(n):
            if r != c and M[r][c] != 0:
                f = M[r][c] / M[c][c]
                M[r] = [x - f * y for x, y in zip(M[r], M[c])]
    return [M[i][n] / M[i][i] for i in range(n)]


def test_page_example():
    Y = [[10, 20, 10, 40], [6, 12, 6, 24], [4, 8, 4, 96]]
    pools, f, single, t = build_system(Y, sizes=(2, 3))
    assert t == [20, 40, 20, 160]
    assert pools == [[0, 1], [1, 3], [3, 2], [2, 0], [0, 1, 3], [1, 3, 2], [3, 2, 0], [2, 0, 1]]
    want = [16, 12, 12, 16, 20, 20, 20, 24]
    assert all(math.isclose(a, b / 7, rel_tol=1e-12) for a, b in zip(f, want))
    assert all(math.isclose(a, b / 7, rel_tol=1e-12) for a, b in zip(single, [8, 8, 8, 4]))
    got = pooled_size_factors(Y, sizes=(2, 3))
    assert all(math.isclose(a, b, rel_tol=TOL) for a, b in zip(got, [0.5, 1.0, 0.5, 2.0]))
    # Pools of size 2 alone are singular on a ring of 4: x + (1, -1, 1, -1) fits them too.
    alt = [1, -1, 1, -1]
    assert all(alt[p[0]] + alt[p[1]] == 0 for p in ring_pools(4, [2]))


def test_ring_order():
    lib = [50, 10, 40, 20, 30, 60]
    # Sorted: cells 1 (10), 3 (20), 4 (30), 2 (40), 0 (50), 5 (60).
    assert ring_order(lib) == [1, 4, 0, 5, 2, 3]


def test_ring_pools_wrap_and_count():
    pools = ring_pools(5, [2, 5])
    assert len(pools) == 10
    assert pools[4] == [4, 0]
    assert all(sorted(p) == [0, 1, 2, 3, 4] for p in pools[5:])
    with pytest.raises(ValueError):
        ring_pools(5, [6])


def test_each_cell_is_in_the_sum_of_the_sizes_pools():
    pools = ring_pools(120, [20, 40, 60, 80, 100])
    for j in range(120):
        assert sum(p.count(j) for p in pools) == 300


def test_median_ratio():
    assert median_ratio([2, 4, 9, 0], [1, 2, 3, 0]) == 2
    with pytest.raises(ValueError):
        median_ratio([1, 2], [0, 0])


def test_exact_recovery_with_a_minority_of_de_genes():
    rng = random.Random(1)
    for de in (0.0, 0.2, 0.45):
        counts, theta = exact_data(rng, 40, 50, de)
        got = pooled_size_factors(counts, sizes=(10, 20, 30, 40))
        assert all(math.isclose(a, b, rel_tol=TOL) for a, b in zip(got, centered(theta)))


def test_library_size_is_wrong_under_composition_but_pooling_is_right():
    rng = random.Random(2)
    counts, theta = exact_data(rng, 40, 50, 0.3)
    lib = centered([sum(counts[g][j] for g in range(40)) for j in range(50)])
    truth = centered(theta)
    assert max(abs(a / b - 1) for a, b in zip(lib, truth)) > 0.2
    got = pooled_size_factors(counts, sizes=(10, 20, 30, 40))
    assert max(abs(a / b - 1) for a, b in zip(got, truth)) < TOL


def test_float_solution_matches_exact_rational_solution():
    rng = random.Random(3)
    n, G = 8, 6
    counts = [[rng.randint(0, 9) + (1 if g == 0 else 0) for _ in range(n)] for g in range(G)]
    pools, factors, single, t = build_system(counts, sizes=(2, 4))
    x = solve_pools(n, pools, factors, single, weak=1e-6)
    w = Fraction(1, 10 ** 6)
    N = [[Fraction(0)] * n for _ in range(n)]
    rhs = [Fraction(0)] * n
    for S, f in zip(pools, factors):
        for a in S:
            rhs[a] += Fraction(f)
            for b in S:
                N[a][b] += 1
    for j in range(n):
        N[j][j] += w
        rhs[j] += w * Fraction(single[j])
    exact = frac_solve(N, rhs)
    assert all(math.isclose(a, float(b), rel_tol=1e-7, abs_tol=1e-9) for a, b in zip(x, exact))


def test_pool_equations_alone_can_be_singular():
    """n = 100 with all sizes multiples of 20: the ring vector cos(2 pi 5 p / 100) has zero sum on every pool."""
    n, sizes = 100, (20, 40, 60, 80, 100)
    v = [math.cos(2 * math.pi * 5 * p / n) for p in range(n)]
    for pool in ring_pools(n, sizes):
        assert abs(sum(v[p] for p in pool)) < 1e-9
    # The condition of the proof: some k, not a multiple of n, with n | k w for every w.
    assert any(all(k * w % n == 0 for w in sizes) for k in range(1, n))
    assert not any(all(k * w % 101 == 0 for w in sizes) for k in range(1, 101))


def test_weak_equations_make_the_answer_unique_and_barely_move_it():
    rng = random.Random(4)
    counts, theta = exact_data(rng, 30, 100, 0.2)
    got = pooled_size_factors(counts)
    assert all(math.isclose(a, b, rel_tol=TOL) for a, b in zip(got, centered(theta)))


def test_clusters_exact():
    rng = random.Random(5)
    n = 60
    clusters = [0] * 35 + [1] * 25
    counts, theta = exact_data(rng, 40, n, 0.4, clusters)
    got = pooled_size_factors(counts, sizes=(5, 10, 15, 20), clusters=clusters)
    assert all(math.isclose(a, b, rel_tol=TOL) for a, b in zip(got, centered(theta)))


def test_errors():
    with pytest.raises(ValueError):
        pooled_size_factors([[0, 1], [0, 2]], sizes=(1,))


def test_poisson_counts_with_many_zeros_measured():
    """A measurement, not a theorem: 120 cells, 200 genes, mean count about 0.6, 20 percent DE genes."""
    rng = random.Random(2016)
    n, G = 120, 200
    theta = [math.exp(rng.gauss(0.0, 0.4)) for _ in range(n)]
    lam = [math.exp(rng.gauss(-1.0, 1.0)) for _ in range(G)]
    group = [j % 2 for j in range(n)]
    counts = []
    for g in range(G):
        up = g < 40
        counts.append([poisson_knuth(rng, theta[j] * lam[g] * (5.0 if up and group[j] else 1.0)) for j in range(n)])
    zeros = sum(c == 0 for row in counts for c in row) / (n * G)
    assert zeros > 0.5
    truth = centered(theta)
    pooled = pooled_size_factors(counts)
    lib = centered([sum(counts[g][j] for g in range(G)) for j in range(n)])

    def log_err(est):
        return sum((math.log(a / b)) ** 2 for a, b in zip(est, truth)) / n

    def group_bias(est):
        d = [math.log(a / b) for a, b in zip(est, truth)]
        return sum(d[j] for j in range(n) if group[j]) / 60 - sum(d[j] for j in range(n) if not group[j]) / 60

    assert all(v > 0 for v in pooled)
    assert log_err(pooled) < log_err(lib)
    # The library size inflates the factors of the group with the up genes (composition bias).
    assert abs(group_bias(pooled)) < 0.6 * abs(group_bias(lib))
    # The single-cell medians are mostly 0, so they cannot be used directly.
    _, _, single, _ = build_system(counts)
    assert sum(s == 0 for s in single) > n / 2

History

Before 2016, single-cell data were often normalized by the library size or by spike-in RNA, or with bulk methods that dropped most genes because of zeros. Lun, Bach and Marioni (2016) proposed pooling and deconvolution, with the ring of cells ordered by library size, the five window sizes and the weak single-cell equations. It became the default normalization of the scran package and of the Bioconductor workflows for single-cell data.

References

  1. Aaron T. L. Lun, Karsten Bach and John C. Marioni, Pooling across cells to normalize single-cell RNA sequencing data with many zero counts, Genome Biology 17 (2016), article 75, the sections on summation and deconvolution with linear equations, on constructing the linear system by selecting cell pools, on obtaining sensible least-squares solutions, and on clustering to weaken the non-DE assumption
  2. Simon Anders and Wolfgang Huber, Differential expression analysis for sequence count data, Genome Biology 11(10) (2010), article R106, the median-of-ratios size factor applied to each pool

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

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