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
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 of expression values, genes in rows and samples in columns. For microarrays these are usually log intensities.
Output. A matrix 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
QUANTILE-NORMALIZE(x) ▷ x: n genes by m samples- 1
sort each column j: x_(1)j ≤ … ≤ x_(n)j - 2
t_i ← (1/m) Σ_j x_(i)j for i = 1, …, n ▷ the target distribution - 3
for j ← 1 to m do - 4
for each block of equal values of column j, at sorted positions a, …, b do - 5
give each entry of the block the value (t_a + … + t_b) / (b - a + 1) - 6
return y
Lines L1 and L2 build the target. It is the mean of the 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 . 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 each from the prefix sums of . 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 | |||
|---|---|---|---|
| 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 . In column 1, gene 1 has rank 1, gene 3 rank 2, gene 2 rank 3 and gene 4 rank 4.
| gene | |||
|---|---|---|---|
| 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 . In column 1, the two values 1 hold positions 1 and 2, so both get , 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 , 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 with rows (genes) and columns (samples). For each column , let be its sorted values. The target is for . In column , the entries split into tie blocks: maximal sets of equal values. A block that holds the sorted positions gets the value in every entry. A block of one entry at position gets .
Lemma 1 (the target is sorted). .
Proof. For each , . Summing over and dividing by gives .
Theorem 2 (the same distribution). If column has no ties, the multiset of its output values is , and the entry at sorted position gets . So every column without ties has the same sorted values , and the same empirical distribution.
Proof. Without ties every block has one entry, so the entry at position gets , and the positions each occur once.
Lines L1 and L2 compute , 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 , if then , and if then .
Proof. Equal values are in the same block and get the same value. If , the block of holds positions and the block of holds with . 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, .
Strict order can become equality, when the target has two equal neighbours . Order is never reversed.
Lemma 4 (equal sums). Every output column has the sum , with or without ties.
Proof. A block over positions has entries, each equal to , so it contributes . The blocks of a column cover the positions once, so the column sum is . Then , since sorting a column does not change its sum.
So all columns get the mean of the original column sums, and so the same mean value.
Lemma 5 (idempotence). Suppose no column of has ties and the target has no ties, . Then normalizing the output again gives .
Proof. By Theorem 2, every column of has the sorted values , so the new target is . The columns of have no ties, so each entry at sorted position gets , which is its present value.
In floating point, can differ from in the last bits, so the tests check idempotence with a relative tolerance.
Equivariance. Permuting the rows of permutes the rows of the output in the same way, and permuting the columns permutes the output columns. Both follow because 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 columns takes time. Computing and the prefix sums of takes , and with the prefix sums each block mean costs , so the assignment takes after the sorts. The extra space is for the output and 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 , 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 over the positions of each value.
Complexity
On a real RAM, sorting the columns at line L1 takes time, which is the cost of the sorting problem. The target at line L2 and the assignment at lines L3 to L5 take , given the sorted order of each column and the prefix sums of . The extra space is 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.
# 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag C7FM0S Edit this page History Report an error Markdown