Algorithm Search⌘K

Algorithmcore

Quantile normalization

Also called quantile normalisation.

Make the distributions of all samples identical by replacing each value with the mean of the values of the same rank across samples.

Time
Θ(m n log n) worst · best
Space
Θ(m n) extra
Where
m = the number of samples; n = the number of genes
Properties
deterministicexactofflineiterative
Origin
Benjamin M. Bolstad, Rafael A. Irizarry, Magnus Astrand, Terence P. Speed, 2003

Quantile normalization makes the distribution of values the same in every sample. It sorts each sample, averages the sorted samples position by position to get a target distribution, and then gives every value the target value of its rank in its own sample. So the smallest value of every sample becomes the mean of the smallest values, the second smallest becomes the mean of the second smallest values, and so on. Bolstad et al. (2003) proposed it for oligonucleotide microarrays, and it is the normalization step of RMA. Unlike median of ratios and TMM, it is not one scale factor per sample. It is a nonlinear map per sample, and it assumes more: that the whole distribution of expression, not just the typical gene, is the same in every sample.

In plain words

Line up the values of each sample from smallest to largest. Now look across the samples at the first place in each line, and take the average. Do the same for the second place, the third, and so on. This gives one shared line of values. Then go back to each sample and replace its smallest value with the shared smallest value, its second smallest with the shared second smallest, and so on. Every sample now has exactly the same set of values, and each gene keeps its place in the order inside its own sample. If two values in a sample are equal, they both get the average of the shared values for their places.

The problem

Input. A matrix xgjx_{gj} of expression values, genes g=1,…,ng = 1, \dots, n in rows and samples j=1,…,mj = 1, \dots, m in columns. For microarrays these are usually log intensities.

Output. A matrix ygjy_{gj} in which every column has the same empirical distribution, and the order of the values inside each column is kept.

Assumption. The differences between the distributions of the samples are technical. The biological differences affect few genes, or affect them in a way that does not change the distribution.

The algorithm

  1. QUANTILE-NORMALIZE(x) ▷ x: n genes by m samples
  2. 1sort each column j: x_(1)j ≤ … ≤ x_(n)j
  3. 2t_i ← (1/m) Σ_j x_(i)j for i = 1, …, n ▷ the target distribution
  4. 3for j ← 1 to m do
  5. 4for each block of equal values of column j, at sorted positions a, …, b do
  6. 5give each entry of the block the value (t_a + … + t_b) / (b - a + 1)
  7. 6return y

Lines L1 and L2 build the target. It is the mean of the mm sorted columns, so it is a distribution in between the samples. Lines L3 to L5 map each column onto the target by rank. Without ties, a block is one entry and gets tat_a. With ties, all entries of the block get the mean of the target over their positions, so the result does not depend on how the sort orders equal values. The code finds these means in O(1)O(1) each from the prefix sums of tt. This tie rule is one fixed choice; software packages treat ties in other ways, so results on data with many ties can differ between packages.

Example

Four genes in three samples:

gene xg1x_{g1} xg2x_{g2} xg3x_{g3}
1 2 4 7
2 5 1 3
3 3 6 9
4 8 2 5

The sorted columns are (2, 3, 5, 8), (1, 2, 4, 6) and (3, 5, 7, 9). Their means by position are the target t=(2,10/3,16/3,23/3)t = (2, 10/3, 16/3, 23/3). In column 1, gene 1 has rank 1, gene 3 rank 2, gene 2 rank 3 and gene 4 rank 4.

gene yg1y_{g1} yg2y_{g2} yg3y_{g3}
1 2 16/3 16/3
2 16/3 2 2
3 10/3 23/3 23/3
4 23/3 10/3 10/3

Every column now holds the values 2, 10/3, 16/3 and 23/3. Gene 1, which was the smallest in sample 1 and the third smallest in samples 2 and 3, gets 2 in sample 1 and 16/3 in the others.

Ties. For the matrix with rows (1, 10), (1, 20) and (3, 30), the target is (5.5,10.5,16.5)(5.5, 10.5, 16.5). In column 1, the two values 1 hold positions 1 and 2, so both get (5.5+10.5)/2=8(5.5 + 10.5)/2 = 8, and the value 3 gets 16.5. Column 2 has no ties and gets 5.5, 10.5 and 16.5. Both columns sum to 32.5.

Correctness

The proof shows that the target is sorted, so that a column with no ties gets exactly the values t1≤⋯≤tnt_1 \le \dots \le t_n, and so all such columns have the same distribution. It shows that the order inside a column is kept, with ties or without: a smaller value never gets a larger result, because a mean of a sorted run lies between its first and its last terms. Every output column has the same sum, the mean of the input column sums, also with ties. Without ties the method is idempotent: normalizing the result again changes nothing. That the samples should have the same distribution is an assumption about the data, not something the proof can show.

Proof: Quantile normalization gives every sample the target distribution and keeps the order within each samplefull

We prove that quantile normalization does what its name says. Without ties, every column of the output has exactly the target values (Theorem 2). With or without ties, it keeps the order of the values inside each column (Lemma 3) and gives every column the same sum (Lemma 4). Without ties, it is idempotent in exact arithmetic (Lemma 5). That the samples should have the same distribution is a modelling assumption. It is not proved here, and the page states when it fails.

Setting. A matrix xx with nn rows (genes) and mm columns (samples). For each column jj, let x(1)j≤⋯≤x(n)jx_{(1)j} \le \dots \le x_{(n)j} be its sorted values. The target is ti=1m∑j=1mx(i)jt_i = \frac1m\sum_{j=1}^m x_{(i)j} for i=1,…,ni = 1, \dots, n. In column jj, the entries split into tie blocks: maximal sets of equal values. A block that holds the sorted positions a,…,ba, \dots, b gets the value tˉ[a,b]=1b−a+1∑i=abti\bar t_{[a,b]} = \frac{1}{b-a+1}\sum_{i=a}^b t_i in every entry. A block of one entry at position aa gets tat_a.

Lemma 1 (the target is sorted). t1≤t2≤⋯≤tnt_1 \le t_2 \le \dots \le t_n.

Proof. For each jj, x(i)j≤x(i+1)jx_{(i)j} \le x_{(i+1)j}. Summing over jj and dividing by mm gives ti≤ti+1t_i \le t_{i+1}. □\square

Theorem 2 (the same distribution). If column jj has no ties, the multiset of its output values is {t1,…,tn}\{t_1, \dots, t_n\}, and the entry at sorted position ii gets tit_i. So every column without ties has the same sorted values t1≤⋯≤tnt_1 \le \dots \le t_n, and the same empirical distribution.

Proof. Without ties every block has one entry, so the entry at position ii gets tit_i, and the positions 1,…,n1, \dots, n each occur once. □\square

Lines L1 and L2 compute tt, and lines L3 to L5 give each block its value. The code sorts each column with a stable sort and then finds the blocks as runs of equal values, so the result does not depend on the input order of tied entries.

Lemma 3 (order within a column). In each column jj, if xgj<xhjx_{gj} < x_{hj} then ygj≤yhjy_{gj} \le y_{hj}, and if xgj=xhjx_{gj} = x_{hj} then ygj=yhjy_{gj} = y_{hj}.

Proof. Equal values are in the same block and get the same value. If xgj<xhjx_{gj} < x_{hj}, the block of gg holds positions [a,b][a, b] and the block of hh holds [c,d][c, d] with b<cb < c. A mean of a sorted sequence over a range is at most its last term, and at least its first term. So, by Lemma 1, tˉ[a,b]≤tb≤tc≤tˉ[c,d]\bar t_{[a,b]} \le t_b \le t_c \le \bar t_{[c,d]}. □\square

Strict order can become equality, when the target has two equal neighbours tb=tct_b = t_c. Order is never reversed.

Lemma 4 (equal sums). Every output column has the sum ∑i=1nti=1m∑g,jxgj\sum_{i=1}^n t_i = \frac1m\sum_{g,j} x_{gj}, with or without ties.

Proof. A block over positions [a,b][a, b] has b−a+1b - a + 1 entries, each equal to tˉ[a,b]\bar t_{[a,b]}, so it contributes ∑i=abti\sum_{i=a}^b t_i. The blocks of a column cover the positions 1,…,n1, \dots, n once, so the column sum is ∑iti\sum_i t_i. Then ∑iti=1m∑j∑ix(i)j=1m∑g,jxgj\sum_i t_i = \frac1m\sum_j\sum_i x_{(i)j} = \frac1m\sum_{g,j}x_{gj}, since sorting a column does not change its sum. □\square

So all columns get the mean of the original column sums, and so the same mean value.

Lemma 5 (idempotence). Suppose no column of xx has ties and the target has no ties, t1<⋯<tnt_1 < \dots < t_n. Then normalizing the output yy again gives yy.

Proof. By Theorem 2, every column of yy has the sorted values t1<⋯<tnt_1 < \dots < t_n, so the new target is ti′=1m∑jti=tit'_i = \frac1m\sum_j t_i = t_i. The columns of yy have no ties, so each entry at sorted position ii gets ti′=tit'_i = t_i, which is its present value. □\square

In floating point, 1m∑jti\frac1m\sum_j t_i can differ from tit_i in the last bits, so the tests check idempotence with a relative tolerance.

Equivariance. Permuting the rows of xx permutes the rows of the output in the same way, and permuting the columns permutes the output columns. Both follow because tt depends only on the multisets of the columns and on the set of columns, and each entry depends only on its rank in its column.

Complexity. Sorting the mm columns takes Θ(mnlog⁡n)\Theta(mn\log n) time. Computing tt and the prefix sums of tt takes Θ(mn)\Theta(mn), and with the prefix sums each block mean costs O(1)O(1), so the assignment takes Θ(mn)\Theta(mn) after the sorts. The extra space is Θ(mn)\Theta(mn) for the output and Θ(n)\Theta(n) for the sorted order of one column.

What the tests check. The test file checks Theorem 2 by exact equality of the sorted columns with tt, Lemma 3 on every pair of entries, Lemma 4, Lemma 5 with a tolerance, the equivariance, and the tie rule against a brute force that averages tt over the positions of each value.

Complexity

On a real RAM, sorting the mm columns at line L1 takes Θ(mnlog⁡n)\Theta(mn\log n) time, which is the cost of the sorting problem. The target at line L2 and the assignment at lines L3 to L5 take Θ(mn)\Theta(mn), given the sorted order of each column and the prefix sums of tt. The extra space is Θ(mn)\Theta(mn) for the output and the sorted columns. If the sorted order of each column is kept from line L1, line L3 needs no new sort.

Properties

  • Same distribution. Without ties, every column of the output has exactly the target values.
  • Order kept. Within each column, the order of the values is kept, and equal values stay equal.
  • Same sum and same mean. Every column of the output has the mean of the input column sums.
  • Idempotent. Without ties, a second pass changes nothing, in exact arithmetic.
  • Not a scale factor. The map differs between samples and between parts of the distribution, so it can fix nonlinear differences that a single factor cannot fix.
  • Rank based. The output depends on each value only through its rank in its column. Two genes with the same rank in every sample get the same values.

Variants and improvements

  • Fixed target. Use a target computed from a reference set of samples, so that new samples can be normalized without changing the old ones. The code accepts a target as an argument.
  • Normalization within groups. When the groups of a study are expected to differ in distribution, normalize within each group only. This keeps the differences between groups, at the price of not removing technical effects that line up with the groups.
  • Median target. Use the median of the sorted values at each position instead of the mean, which is more robust to one bad sample.
  • Scaling methods. For RNA-seq counts, the usual choice is a factor per sample, from median of ratios or TMM, which assumes only that most genes do not change.

When to use it

Use it for microarray data, on the log scale, when the samples come from similar biological material, and before a gene-wise test such as the moderated t-statistic. Use it when the distributions differ for technical reasons, such as scanner settings or RNA quality, in a nonlinear way. Do not use it when the conditions are expected to differ in their overall distribution, such as different tissues, or a treatment that changes the expression of many genes in one direction. Hicks and Irizarry (2015) give a test of this assumption. For RNA-seq counts in a negative binomial model, use a scale factor instead.

Pitfalls

  • Removing real differences. If one condition has globally higher expression of many genes, quantile normalization forces it back to the common distribution and removes the effect.
  • Many ties. RNA-seq counts have many zeros and small integers, so large tied blocks occur, and the tie rule matters. Packages differ, so results are not always comparable.
  • Counts after normalization. The output values are not counts, so they cannot go into a count model.
  • Few genes. With few genes, the target is a poor estimate of a distribution, and the method can create artifacts.
  • Normalizing with batch structure. Quantile normalization is not batch effect correction. It removes differences in distribution, but not effects that move some genes and not others.

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.

quantile_normalization.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/quantile-normalization/. The authors are listed in prov/C7FM0S.jsonl.
"""Quantile normalization (Bolstad, Irizarry, Astrand and Speed 2003).

x is a list of rows, one row per gene and one column per sample. Sort each
column, average the sorted columns position by position to get the target
t[1] <= ... <= t[n], and give each entry the target value at its rank in its
column. Entries that tie in a column get the mean of the target values over
the ranks of the tie, so that the result does not depend on how the sort
orders them. Packages treat ties in other ways; this is one fixed choice.
"""

from __future__ import annotations

from typing import List, Sequence


def _check(x: Sequence[Sequence[float]]) -> int:
    if not x:
        raise ValueError("need at least one gene")
    m = len(x[0])
    if m == 0 or any(len(row) != m for row in x):
        raise ValueError("every gene needs the same positive number of samples")
    return m


def target_distribution(x: Sequence[Sequence[float]]) -> List[float]:
    """The mean, over the samples, of the i-th smallest value, for i = 1..n."""
    m = _check(x)
    n = len(x)
    cols = [sorted(row[j] for row in x) for j in range(m)]  # @line L1
    return [sum(cols[j][i] for j in range(m)) / m for i in range(n)]  # @line L2


def normalize_to_target(x: Sequence[Sequence[float]], target: Sequence[float]) -> List[List[float]]:
    """Give each entry the target value at its rank in its column (ties share the mean)."""
    m = _check(x)
    n = len(x)
    t = sorted(target)
    if len(t) != n:
        raise ValueError("the target needs one value per gene")
    prefix = [0.0]
    for v in t:
        prefix.append(prefix[-1] + v)
    out = [[0.0] * m for _ in range(n)]
    for j in range(m):  # @line L3
        order = sorted(range(n), key=lambda g: x[g][j])
        a = 0
        while a < n:  # @line L4
            b = a
            while b + 1 < n and x[order[b + 1]][j] == x[order[a]][j]:
                b += 1
            value = t[a] if a == b else (prefix[b + 1] - prefix[a]) / (b - a + 1)  # @line L5
            for r in range(a, b + 1):
                out[order[r]][j] = value
            a = b + 1
    return out  # @line L6


def quantile_normalize(x: Sequence[Sequence[float]]) -> List[List[float]]:
    """Quantile normalization of the columns of x."""
    return normalize_to_target(x, target_distribution(x))
test_quantile_normalization.py 124 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/quantile-normalization/. The authors are listed in prov/C7FM0S.jsonl.

import math
import random

import pytest

from quantile_normalization import normalize_to_target, quantile_normalize, target_distribution

PAGE = [
    [2, 4, 7],
    [5, 1, 3],
    [3, 6, 9],
    [8, 2, 5],
]


def close_rows(a, b, rel=1e-12):
    return all(math.isclose(x, y, rel_tol=rel, abs_tol=1e-12)
               for ra, rb in zip(a, b, strict=True) for x, y in zip(ra, rb, strict=True))


def brute_force(x):
    """Each entry gets the mean of the target over the positions where its value sits in the sorted column."""
    n, m = len(x), len(x[0])
    cols = [sorted(row[j] for row in x) for j in range(m)]
    t = [sum(cols[j][i] for j in range(m)) / m for i in range(n)]
    out = []
    for g in range(n):
        row = []
        for j in range(m):
            pos = [i for i in range(n) if cols[j][i] == x[g][j]]
            row.append(sum(t[i] for i in pos) / len(pos))
        out.append(row)
    return out


def test_page_example():
    t = target_distribution(PAGE)
    assert close_rows([t], [[2.0, 10 / 3, 16 / 3, 23 / 3]])
    assert close_rows(quantile_normalize(PAGE), [
        [2.0, 16 / 3, 16 / 3],
        [16 / 3, 2.0, 2.0],
        [10 / 3, 23 / 3, 23 / 3],
        [23 / 3, 10 / 3, 10 / 3],
    ])


def test_ties_share_the_mean_of_their_targets():
    x = [[1, 10], [1, 20], [3, 30]]
    # targets: (5.5, 10.5, 16.5); the two 1s share ranks 1 and 2
    assert close_rows(quantile_normalize(x), [[8.0, 5.5], [8.0, 10.5], [16.5, 16.5]])


def test_matches_brute_force_with_ties():
    rng = random.Random(31)
    for _ in range(200):
        n = rng.randint(1, 15)
        m = rng.randint(1, 5)
        x = [[rng.randint(0, 6) for _ in range(m)] for _ in range(n)]
        assert close_rows(quantile_normalize(x), brute_force(x))


def test_without_ties_every_column_gets_the_target():
    rng = random.Random(32)
    for _ in range(50):
        n = rng.randint(1, 30)
        m = rng.randint(1, 6)
        x = [[rng.random() for _ in range(m)] for _ in range(n)]
        t = target_distribution(x)
        y = quantile_normalize(x)
        for j in range(m):
            assert sorted(row[j] for row in y) == t


def test_order_in_each_column_is_kept_and_sums_agree():
    rng = random.Random(33)
    for _ in range(100):
        n = rng.randint(1, 20)
        m = rng.randint(1, 5)
        x = [[rng.randint(0, 9) for _ in range(m)] for _ in range(n)]
        y = quantile_normalize(x)
        total = sum(target_distribution(x))
        for j in range(m):
            for g in range(n):
                for h in range(n):
                    if x[g][j] < x[h][j]:
                        assert y[g][j] <= y[h][j]
                    if x[g][j] == x[h][j]:
                        assert y[g][j] == y[h][j]
            assert math.isclose(sum(row[j] for row in y), total, rel_tol=1e-12, abs_tol=1e-12)


def test_idempotent_without_ties():
    rng = random.Random(34)
    for _ in range(50):
        x = [[rng.gauss(0, 1) for _ in range(4)] for _ in range(rng.randint(1, 25))]
        y = quantile_normalize(x)
        assert close_rows(quantile_normalize(y), y, rel=1e-9)


def test_permuting_genes_and_samples_permutes_the_result():
    rng = random.Random(35)
    x = [[rng.randint(0, 20) for _ in range(5)] for _ in range(12)]
    y = quantile_normalize(x)
    rows = list(range(12))
    cols = list(range(5))
    rng.shuffle(rows)
    rng.shuffle(cols)
    xp = [[x[g][j] for j in cols] for g in rows]
    yp = quantile_normalize(xp)
    assert close_rows(yp, [[y[g][j] for j in cols] for g in rows])


def test_given_target_and_errors():
    x = [[3, 1], [1, 2], [2, 3]]
    assert normalize_to_target(x, [30, 10, 20]) == [[30, 10], [10, 20], [20, 30]]
    with pytest.raises(ValueError):
        normalize_to_target(x, [1, 2])
    with pytest.raises(ValueError):
        quantile_normalize([])
    with pytest.raises(ValueError):
        quantile_normalize([[1, 2], [3]])

History

Before 2003, arrays were normalized by a scale factor per array or by smooth curves fitted between pairs of arrays. Bolstad et al. (2003) proposed to make the distributions identical, an idea that comes from the quantile-quantile plot: two samples with the same distribution lie on the diagonal of that plot. They showed that it reduced variance with little bias on spike-in data sets, and it became the normalization step of the RMA method for Affymetrix arrays. Hicks and Irizarry (2015) studied when its assumption fails and gave a test.

References

  1. B. M. Bolstad, R. A. Irizarry, M. Astrand and T. P. Speed, A comparison of normalization methods for high density oligonucleotide array data based on variance and bias, Bioinformatics 19(2) (2003), pages 185 to 193, the quantile normalization algorithm, its motivation by the quantile-quantile plot, and its comparison with scaling and nonlinear methods
  2. Stephanie C. Hicks and Rafael A. Irizarry, quantro, a data-driven approach to guide the choice of an appropriate normalization method, Genome Biology 16 (2015), article 117, the assumption that the distributions do not differ between groups, and a test of it before quantile normalization is used

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.best
  • 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