Algorithmadvanced
Weighted gene coexpression network analysis
Also called WGCNA.
Build a soft-thresholded correlation network of genes, then find modules by hierarchical clustering of topological overlap.
- Time
- Θ(n^2 m + n^3) worst · best
- Space
- Θ(n^2) extra
- Where
- m = the number of samples; n = the number of genes
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Bin Zhang, Steve Horvath, 2005
Weighted gene coexpression network analysis builds a network in which every pair of genes is joined with a weight that grows with the correlation of their expression across samples, and then finds modules, groups of genes that are tightly connected in this network. The weight is a power of the absolute correlation, , a soft threshold that keeps all edges but pushes weak correlations toward zero. The similarity used for clustering is the topological overlap, which counts how much two genes share their neighbours, not only how strongly they are joined. Modules come from hierarchical clustering of with average linkage, and each module is summarized by its eigengene, the first principal component of its genes. Zhang and Horvath (2005) introduced the method. It finds modules over all samples; a biclustering method instead looks for genes that are coexpressed in a subset of the samples only.
In plain words
Genes that work together often go up and down together across samples. So you measure, for every pair of genes, how closely their patterns match. Instead of keeping only the strong pairs, you keep all pairs but make weak links much weaker than strong ones. Then you ask a second question for each pair: do these two genes have the same friends? Two genes count as close if they are linked to each other and to the same other genes. You group genes that are close in this sense into modules, and you describe each module by one pattern across the samples, the pattern that its genes share most. You can then ask which modules follow a disease or a treatment.
The problem
Input. An expression matrix of genes in samples, a power , a cut height and a minimum module size.
Output. A module label for each gene, with 0 for genes in no module, and an eigengene for each module, a vector of length .
Aim. Modules should be sets of genes with high topological overlap among themselves and lower overlap with other genes. There is no single objective function; the result is defined by the steps below.
The algorithm
WGCNA(X, β, H, minSize) ▷ X: n genes by m samples- 1
r_ij ← Pearson correlation of genes i and j across the samples - 2
a_ij ← |r_ij|^β (or ((1 + r_ij) / 2)^β for a signed network); a_ii ← 1 - 3
k_i ← Σ_{u ≠ i} a_iu ▷ connectivity - 4
TOM_ij ← (Σ_{u ≠ i, j} a_iu a_uj + a_ij) / (min(k_i, k_j) + 1 - a_ij) - 5
d_ij ← 1 - TOM_ij - 6
T ← average-linkage hierarchical clustering of d - 7
labels ← clusters of T cut at height H; clusters smaller than minSize get label 0 - 8
for each module: eigengene ← first right singular vector of its standardized genes - 9
return labels, eigengenes
Line L1 computes all pairwise correlations. Line L2 is the soft threshold. In the unsigned network, strong negative correlations count as strong links; in the signed network, they count as weak ones. Line L3 sums the weights of each gene. Line L4 is the topological overlap of Ravasz et al. (2002), generalized by Zhang and Horvath to weights: the numerator adds the direct link to the weight of all paths of length 2, and the denominator is the largest value the numerator can take, so TOM lies in . Lines L5 and L6 cluster the genes, using the Lance-Williams update for average linkage. Line L7 cuts the tree at one fixed height. This is a static cut; the WGCNA package uses Dynamic Tree Cut, which cuts branches at different heights and can give different modules. Line L8 computes the eigengene by power iteration on the matrix , where holds the genes of the module, each standardized, and fixes its sign so that it agrees with the mean of those genes.
Choosing the power. Zhang and Horvath chose by the scale-free topology criterion: for each candidate power, fit a line to against , where is the fraction of genes with connectivity near , and take the smallest for which the of the fit is high. The idea is that many biological networks look roughly like a scale-free network. This is a heuristic, and the code gives the fit so that it can be checked.
Example
Take four genes whose adjacency matrix, after the soft threshold, is already given:
| 1 | 2 | 3 | 4 | |
|---|---|---|---|---|
| 1 | 1 | 0.9 | 0.8 | 0 |
| 2 | 0.9 | 1 | 0.7 | 0.1 |
| 3 | 0.8 | 0.7 | 1 | 0 |
| 4 | 0 | 0.1 | 0 | 1 |
The connectivities are . For genes 1 and 3, the paths of length 2 give , so . All values:
| 1 | 2 | 3 | 4 | |
|---|---|---|---|---|
| 1 | 1 | 0.8111 | 0.8412 | 0.0818 |
| 2 | 0.8111 | 1 | 0.7889 | 0.1 |
| 3 | 0.8412 | 0.7889 | 1 | 0.0636 |
| 4 | 0.0818 | 0.1 | 0.0636 | 1 |
Genes 1 and 4 have no direct link, but , because both are joined to gene 2. Average linkage on first joins genes 1 and 3 at height 0.1588, then adds gene 2 at height , and last adds gene 4 at height 0.9182. A cut at gives the labels : one module of three genes and gene 4 on its own.
Correctness
The proof shows that each step computes what it claims. The adjacency is symmetric with entries in . The topological overlap is symmetric and in , because the shared weight is at most . The Lance-Williams update gives the exact average distance between clusters, and the merge heights never decrease, because average linkage is reducible. So a cut at height keeps a prefix of the merges, and the labels are the clusters after that prefix. The power iteration converges to the first right singular vector of the standardized module matrix when the top eigenvalue is simple. The proof does not claim that the modules are biologically meaningful or that the network is scale free; those are questions about data.
Proof: Topological overlap lies in the unit interval, and average linkage on it gives a monotone tree that a static cut splits into modulesfull
We prove what the steps of the pipeline compute. The soft-threshold adjacency has entries in (Lemma 1). The topological overlap is symmetric and lies in (Lemma 2). The Lance-Williams update computes average linkage exactly (Lemma 3), the merge heights never decrease (Lemma 4), so a cut at a fixed height gives the clusters of the tree at that height (Lemma 5). Power iteration returns the first eigenvector of , which is the module eigengene, when the top eigenvalue is simple (Lemma 6). That modules found this way are biological units is a modelling claim, and the choice of the power by a scale-free fit is a heuristic. Neither is proved here.
Setting. The matrix holds genes and samples. Line L1 computes the Pearson correlations . Line L2 sets (unsigned) or (signed) for , with , and . Line L3 computes the connectivity . Line L4 computes, for ,
and . Line L5 sets the distance .
Lemma 1 (adjacency). is symmetric and .
Proof. , and by the Cauchy-Schwarz inequality. So and lie in , and so do their powers with .
Lemma 2 (topological overlap). For any symmetric with entries in and , is symmetric and . Also exactly when and no third gene is joined to both and .
Proof. Symmetry holds because , and are symmetric in and . Since , , and in the same way . So . The denominator is , since . It is positive: if it is greater than , and if it is . So , which gives . The numerator is a sum of nonnegative terms, so it is 0 exactly when and every product is 0.
So is a symmetric dissimilarity with entries in and a zero diagonal. It need not satisfy the triangle inequality, and the steps below do not need it.
Lemma 3 (the Lance-Williams update is average linkage). At every step of average_linkage, the stored distance between two current clusters and equals .
Proof. By induction on the steps. At the start every cluster is one gene and the stored distance is . Suppose the claim holds before clusters and merge. For another cluster ,
which is the value the code stores. The distances between clusters other than and do not change.
Lemma 4 (monotone heights). The heights of the merges satisfy .
Proof. At step the code merges a pair with the smallest current distance , so every current distance is at least . After the merge, the new distances are weighted means of and , so they are at least as well. The other distances do not change. So every distance after step is at least , and .
This is the reducibility property of average linkage. It fails for centroid and median linkage, where a later merge can be lower than an earlier one.
Lemma 5 (the static cut). For a height , the labels of cut_tree put two genes in the same module exactly when they are in the same cluster after the merges with , and by Lemma 4 these merges are the first merges for some . Clusters with fewer than min_size genes get the label 0.
Proof. By Lemma 4, the set is an initial segment . For each kept merge, the code joins all its members in a union-find structure. The clusters after merges are exactly the members of the clusters that these merges create, together with the genes not yet merged, so the union-find classes are these clusters. The code then numbers the classes with at least min_size genes by decreasing size and gives 0 to the rest.
This static cut is not the Dynamic Tree Cut of Langfelder, Zhang and Horvath (2008), which the WGCNA package uses by default. A dynamic cut can split one branch at different heights, so its modules need not be clusters of one level of the tree.
Lemma 6 (the eigengene). Let be the module matrix with each gene standardized to mean 0 and sample standard deviation 1. Let , a symmetric positive semidefinite matrix with eigenvalues and unit eigenvectors . If and the start vector has , the iterates converge to , and is the first right singular vector of , the direction with that maximizes .
Proof. Write with . Then , and is this vector divided by its length. The terms with have size at most relative to the first term, which tends to 0. So , since every and no sign changes occur. For a unit vector , , with equality at . This is the first right singular vector by the definition of the singular value decomposition.
The error after steps is , so the iteration is slow when the module has two strong directions. The code fixes the sign of the result so that it has a nonnegative inner product with the mean standardized gene of the module, as WGCNA does, so that the eigengene goes up when most module genes go up. The start vector is fixed. It is orthogonal to only for special data, and then the code returns another eigenvector; the tests do not hit this case.
The scale-free fit. scale_free_fit bins the connectivities, fits a least-squares line to against , and returns and the slope. WGCNA picks the smallest whose passes a threshold such as 0.8. This rule is a heuristic of Zhang and Horvath (2005). It is not a test, and coexpression networks need not be scale-free.
What the tests check. The test file checks the Pearson correlation, both adjacencies, the page example, the TOM against a brute force and against the bounds of Lemma 2 with its two extreme cases, average linkage against a brute force that recomputes from its definition, the order of Lemma 4, the cut labels of Lemma 5, the eigengene against a rank one module and against the Rayleigh quotient bound of Lemma 6, and the scale-free fit against a direct regression. The recovery of planted modules is a measurement.
Complexity. With genes and samples, the correlations take time and the TOM takes time as written (a matrix product does the same work). The average linkage code scans all current pairs at each of the steps, which is time; a nearest-neighbour chain makes it . The cut takes time in the worst case because it reads the member lists. For a module of genes, the eigengene takes to form and per iteration. The extra space is .
Complexity
On a real RAM, line L1 takes time for the correlations. Line L4 takes , since each of the pairs sums over genes; this is the cost of a product of two matrices, and a fast matrix product lowers it. The code finds each merge of line L6 by a scan over all current pairs, so the clustering also takes in total; the nearest-neighbour chain algorithm does it in . The eigengenes take to form the matrices plus per iteration. The extra space is for the matrices, which is why the package splits large data sets into blocks.
Properties
- Soft. No correlation is thrown away by a hard threshold, so small changes in the data change the network a little, not by adding or removing edges.
- Neighbourhood based. Topological overlap is high for genes that share many neighbours, which makes modules more robust to noise in single correlations.
- Bounded. All adjacencies and overlaps lie in , and exactly when and no third gene is joined to both.
- Not invariant to . The modules depend on the power and on the cut, and there is no correct choice in a mathematical sense.
- Unsupervised. The modules are found without the sample traits; traits are related to the eigengenes afterwards.
Variants and improvements
- Signed networks. The adjacency separates genes that go up together from genes that go in opposite directions.
- Dynamic Tree Cut. Langfelder, Zhang and Horvath (2008) cut the branches of the tree adaptively, by their shape, instead of at one height.
- Merging modules. Modules whose eigengenes are highly correlated are merged after the cut.
- Robust correlation. The biweight midcorrelation or Spearman's rank correlation can replace Pearson's correlation, so that a few outlying samples do not create links.
- Consensus modules. Modules found in several data sets at once, by taking the smallest overlap over the data sets.
- Module membership. The correlation of each gene with each eigengene shows how central the gene is to the module, and its hub genes.
When to use it
Use it to reduce thousands of genes to tens of modules, when there are enough samples to estimate correlations, say 20 or more, and when the samples vary in a way that moves groups of genes together, such as different patients, tissues or conditions. Relate the eigengenes to clinical traits, and test the modules for function with over-representation analysis. Do not use it as a method to find regulators; correlation does not give direction, which is what gene regulatory network inference tries to find.
Pitfalls
- Few samples. Correlations from few samples are noisy, and the modules are unstable.
- Batch effects. A batch or a technical factor makes many genes correlated and gives large modules of no biological meaning. Remove or model it first.
- Unsigned networks. In an unsigned network, a gene and its repressor can fall into the same module, which mixes processes.
- Overreading the scale-free fit. The fit of a line to a few binned points on a log scale is a weak test, and real coexpression networks often do not fit well at any power.
- The cut. The modules change with the cut height and the minimum size. Report them, and check that the main modules survive other choices.
- Memory. The matrices of 20,000 genes take several gigabytes. Filter genes, or work in blocks.
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/weighted-gene-coexpression-network-analysis/. The authors are listed in prov/WN4DQ5.jsonl.
"""Weighted gene coexpression network analysis (Zhang and Horvath 2005).
expr is a list of rows, one row per gene and one column per sample. The
steps are: Pearson correlations r_ij; the soft-threshold adjacency
a_ij = |r_ij|^beta (unsigned) or ((1 + r_ij) / 2)^beta (signed); the
topological overlap
TOM_ij = (l_ij + a_ij) / (min(k_i, k_j) + 1 - a_ij),
l_ij = sum_{u != i, j} a_iu a_uj, k_i = sum_{u != i} a_iu;
average-linkage clustering of 1 - TOM; a cut of the tree at a fixed height
(a static cut, not the Dynamic Tree Cut of the WGCNA package); and the
eigengene of each module, the first principal component of its standardized
genes. scale_free_fit gives the R^2 of log10 p(k) against log10 k over
equal-width bins of k, the fit used to choose beta.
"""
from __future__ import annotations
import math
from typing import Dict, List, Sequence, Tuple
Matrix = List[List[float]]
def pearson(x: Sequence[float], y: Sequence[float]) -> float:
n = len(x)
if n != len(y) or n < 2:
raise ValueError("need two vectors of the same length >= 2")
mx, my = sum(x) / n, sum(y) / n
sxy = sum((a - mx) * (b - my) for a, b in zip(x, y))
sxx = sum((a - mx) ** 2 for a in x)
syy = sum((b - my) ** 2 for b in y)
if sxx == 0 or syy == 0:
raise ValueError("a gene has no variation")
return max(-1.0, min(1.0, sxy / math.sqrt(sxx * syy)))
def correlation_matrix(expr: Sequence[Sequence[float]]) -> Matrix:
n = len(expr)
r = [[1.0] * n for _ in range(n)]
for i in range(n):
for j in range(i + 1, n):
r[i][j] = r[j][i] = pearson(expr[i], expr[j]) # @line L1
return r
def adjacency(r: Sequence[Sequence[float]], beta: float, signed: bool = False) -> Matrix:
"""Soft-threshold adjacency; the diagonal is 1."""
n = len(r)
a = [[1.0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
if i != j:
base = (1.0 + r[i][j]) / 2.0 if signed else abs(r[i][j])
a[i][j] = base ** beta # @line L2
return a
def connectivity(a: Sequence[Sequence[float]]) -> List[float]:
"""k_i = sum over u != i of a_iu."""
n = len(a)
return [sum(a[i][u] for u in range(n) if u != i) for i in range(n)]
def topological_overlap(a: Sequence[Sequence[float]]) -> Matrix:
"""The topological overlap matrix of an adjacency with entries in [0, 1]."""
n = len(a)
k = connectivity(a) # @line L3
t = [[1.0] * n for _ in range(n)]
for i in range(n):
for j in range(i + 1, n):
shared = sum(a[i][u] * a[u][j] for u in range(n) if u != i and u != j)
t[i][j] = t[j][i] = (shared + a[i][j]) / (min(k[i], k[j]) + 1.0 - a[i][j]) # @line L4
return t
def average_linkage(d: Sequence[Sequence[float]]) -> List[Tuple[int, int, float, Tuple[int, ...]]]:
"""Agglomerative clustering with average linkage (UPGMA) on the distance matrix d.
Returns the n - 1 merges as (id_a, id_b, height, members). Leaves have
ids 0..n-1 and the cluster made by merge t has id n + t. Ties go to the
pair with the smallest ids. Distances are updated by the Lance-Williams
rule d(k, a + b) = (n_a d(k, a) + n_b d(k, b)) / (n_a + n_b).
"""
n = len(d)
members: Dict[int, Tuple[int, ...]] = {i: (i,) for i in range(n)}
dist: Dict[Tuple[int, int], float] = {}
for i in range(n):
for j in range(i + 1, n):
dist[(i, j)] = d[i][j]
merges = []
next_id = n
while len(members) > 1:
(ia, ib), h = min(dist.items(), key=lambda kv: (kv[1], kv[0]))
na, nb = len(members[ia]), len(members[ib])
new = tuple(sorted(members[ia] + members[ib]))
del members[ia], members[ib]
for c in members:
dac = dist.pop((min(c, ia), max(c, ia)))
dbc = dist.pop((min(c, ib), max(c, ib)))
dist[(c, next_id)] = (na * dac + nb * dbc) / (na + nb)
del dist[(ia, ib)]
members[next_id] = new
merges.append((ia, ib, h, new))
next_id += 1
return merges
def cut_tree(merges, n: int, height: float, min_size: int = 1) -> List[int]:
"""Labels from a static cut: merges at height <= height are kept.
Modules are numbered 1, 2, ... by decreasing size (ties by smallest
gene); genes in clusters smaller than min_size get label 0.
"""
parent = list(range(n))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
for _, _, h, mem in merges:
if h <= height:
root = find(mem[0])
for g in mem[1:]:
parent[find(g)] = root
groups: Dict[int, List[int]] = {}
for g in range(n):
groups.setdefault(find(g), []).append(g)
big = sorted((grp for grp in groups.values() if len(grp) >= min_size), key=lambda grp: (-len(grp), grp[0]))
labels = [0] * n
for lab, grp in enumerate(big, start=1):
for g in grp:
labels[g] = lab
return labels
def standardize(row: Sequence[float]) -> List[float]:
n = len(row)
m = sum(row) / n
sd = math.sqrt(sum((x - m) ** 2 for x in row) / (n - 1))
if sd == 0:
raise ValueError("a gene has no variation")
return [(x - m) / sd for x in row]
def eigengene(expr: Sequence[Sequence[float]], iters: int = 1000, tol: float = 1e-13) -> List[float]:
"""The first right singular vector of the standardized module matrix (unit length).
Found by power iteration on the samples-by-samples matrix X^T X. Its sign
is set so that it has a nonnegative correlation with the mean of the
standardized genes.
"""
x = [standardize(row) for row in expr]
m = len(x[0])
c = [[sum(row[s] * row[t] for row in x) for t in range(m)] for s in range(m)]
avg = [sum(row[s] for row in x) / len(x) for s in range(m)]
v = [1.0 + 0.01 * s for s in range(m)]
norm = math.sqrt(sum(t * t for t in v))
v = [t / norm for t in v]
for _ in range(iters):
w = [sum(c[s][t] * v[t] for t in range(m)) for s in range(m)]
norm = math.sqrt(sum(t * t for t in w))
if norm == 0:
break
w = [t / norm for t in w]
if w[0] * v[0] < 0:
w = [-t for t in w]
done = max(abs(a - b) for a, b in zip(w, v)) < tol
v = w
if done:
break
if sum(a * b for a, b in zip(v, avg)) < 0:
v = [-t for t in v]
return v
def scale_free_fit(k: Sequence[float], n_bins: int = 10) -> Tuple[float, float]:
"""(R^2, slope) of the least-squares line of log10 p(k) on log10 mean k, over the non-empty bins."""
lo, hi = min(k), max(k)
if hi <= lo or lo <= 0:
raise ValueError("need positive connectivities that are not all equal")
width = (hi - lo) / n_bins
bins: Dict[int, List[float]] = {}
for v in k:
b = min(int((v - lo) / width), n_bins - 1)
bins.setdefault(b, []).append(v)
xs = [math.log10(sum(vs) / len(vs)) for _, vs in sorted(bins.items())]
ys = [math.log10(len(vs) / len(k)) for _, vs in sorted(bins.items())]
if len(xs) < 3:
raise ValueError("need at least three non-empty bins")
mx, my = sum(xs) / len(xs), sum(ys) / len(ys)
sxx = sum((a - mx) ** 2 for a in xs)
sxy = sum((a - mx) * (b - my) for a, b in zip(xs, ys))
syy = sum((b - my) ** 2 for b in ys)
slope = sxy / sxx
r2 = sxy * sxy / (sxx * syy) if syy > 0 else 1.0
return r2, slope
def wgcna(expr: Sequence[Sequence[float]], beta: float, height: float, min_size: int = 1,
signed: bool = False):
"""Module labels and module eigengenes (a dict from label to eigengene; label 0 has none)."""
r = correlation_matrix(expr)
a = adjacency(r, beta, signed)
t = topological_overlap(a)
d = [[1.0 - v for v in row] for row in t] # @line L5
merges = average_linkage(d) # @line L6
labels = cut_tree(merges, len(expr), height, min_size) # @line L7
eig = {}
for lab in sorted(set(labels) - {0}):
eig[lab] = eigengene([expr[g] for g in range(len(expr)) if labels[g] == lab]) # @line L8
return labels, eig # @line L9
test_weighted_gene_coexpression_network_analysis.py 212 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/weighted-gene-coexpression-network-analysis/. The authors are listed in prov/WN4DQ5.jsonl.
import itertools
import math
import random
import statistics
import pytest
from weighted_gene_coexpression_network_analysis import (
adjacency,
average_linkage,
correlation_matrix,
cut_tree,
eigengene,
pearson,
scale_free_fit,
standardize,
topological_overlap,
wgcna,
)
PAGE_A = [
[1.0, 0.9, 0.8, 0.0],
[0.9, 1.0, 0.7, 0.1],
[0.8, 0.7, 1.0, 0.0],
[0.0, 0.1, 0.0, 1.0],
]
def random_adjacency(rng, n):
a = [[1.0] * n for _ in range(n)]
for i in range(n):
for j in range(i + 1, n):
a[i][j] = a[j][i] = rng.random()
return a
def tom_brute(a):
"""The definition, entry by entry, with sets of neighbours written out."""
n = len(a)
out = [[1.0] * n for _ in range(n)]
for i, j in itertools.permutations(range(n), 2):
others = [u for u in range(n) if u not in (i, j)]
l_ij = sum(a[i][u] * a[u][j] for u in others)
k_i = sum(a[i][u] for u in range(n) if u != i)
k_j = sum(a[j][u] for u in range(n) if u != j)
out[i][j] = (l_ij + a[i][j]) / (min(k_i, k_j) + 1 - a[i][j])
return out
def test_pearson_matches_statistics():
rng = random.Random(71)
for _ in range(50):
x = [rng.gauss(0, 1) for _ in range(8)]
y = [rng.gauss(0, 1) + 0.5 * v for v in x]
assert math.isclose(pearson(x, y), statistics.correlation(x, y), rel_tol=1e-12)
with pytest.raises(ValueError):
pearson([1, 1, 1], [1, 2, 3])
def test_adjacency_unsigned_and_signed():
r = [[1.0, -0.5], [-0.5, 1.0]]
assert adjacency(r, 2)[0][1] == 0.25
assert adjacency(r, 2, signed=True)[0][1] == 0.0625
assert adjacency(r, 2)[0][0] == 1.0
def test_page_example():
t = topological_overlap(PAGE_A)
# k = (1.7, 1.7, 1.5, 0.1); l_12 = 0.8 * 0.7 + 0 * 0.1 = 0.56
assert math.isclose(t[0][1], (0.56 + 0.9) / (1.7 + 1 - 0.9), rel_tol=1e-12)
assert math.isclose(t[0][3], (0.09 + 0.0) / (0.1 + 1 - 0.0), rel_tol=1e-12)
def test_tom_matches_brute_force_and_lies_in_unit_interval():
rng = random.Random(72)
for _ in range(50):
n = rng.randint(2, 9)
a = random_adjacency(rng, n)
t = topological_overlap(a)
b = tom_brute(a)
for i in range(n):
for j in range(n):
assert math.isclose(t[i][j], b[i][j], rel_tol=1e-12)
assert t[i][j] == t[j][i]
assert -1e-15 <= t[i][j] <= 1 + 1e-15
def test_tom_extremes():
full = [[1.0] * 5 for _ in range(5)]
assert all(math.isclose(v, 1.0) for row in topological_overlap(full) for v in row)
empty = [[1.0 if i == j else 0.0 for j in range(4)] for i in range(4)]
t = topological_overlap(empty)
assert all(t[i][j] == 0.0 for i in range(4) for j in range(4) if i != j)
def brute_average_linkage(d):
"""Recompute every cluster distance as the mean of the pairwise distances."""
clusters = [(i,) for i in range(len(d))]
heights = []
sets = []
while len(clusters) > 1:
best = None
for x, y in itertools.combinations(range(len(clusters)), 2):
a, b = clusters[x], clusters[y]
h = sum(d[i][j] for i in a for j in b) / (len(a) * len(b))
if best is None or h < best[0]:
best = (h, x, y)
h, x, y = best
new = tuple(sorted(clusters[x] + clusters[y]))
clusters = [c for i, c in enumerate(clusters) if i not in (x, y)] + [new]
heights.append(h)
sets.append(new)
return heights, sets
def test_average_linkage_matches_brute_force_and_is_monotone():
rng = random.Random(73)
for _ in range(60):
n = rng.randint(2, 10)
d = [[0.0] * n for _ in range(n)]
for i in range(n):
for j in range(i + 1, n):
d[i][j] = d[j][i] = rng.random()
merges = average_linkage(d)
heights, sets = brute_average_linkage(d)
assert [m[3] for m in merges] == sets
for m, h in zip(merges, heights):
assert math.isclose(m[2], h, rel_tol=1e-12)
assert all(merges[t][2] <= merges[t + 1][2] + 1e-12 for t in range(len(merges) - 1))
def test_cut_tree_labels():
d = [[0, 1, 9, 9, 9], [1, 0, 9, 9, 9], [9, 9, 0, 2, 9], [9, 9, 2, 0, 9], [9, 9, 9, 9, 0]]
merges = average_linkage(d)
assert cut_tree(merges, 5, 2.5) == [1, 1, 2, 2, 3]
assert cut_tree(merges, 5, 2.5, min_size=2) == [1, 1, 2, 2, 0]
assert cut_tree(merges, 5, 0.5) == [1, 2, 3, 4, 5]
assert cut_tree(merges, 5, 100) == [1] * 5
def test_eigengene_of_a_rank_one_module():
rng = random.Random(74)
pattern = [rng.gauss(0, 1) for _ in range(7)]
expr = [[c * p + b for p in pattern] for c, b in ((1.0, 3.0), (2.5, -1.0), (0.3, 0.0), (4.0, 2.0))]
v = eigengene(expr)
z = standardize(pattern)
norm = math.sqrt(sum(t * t for t in z))
for a, b in zip(v, z):
assert math.isclose(a, b / norm, rel_tol=1e-9, abs_tol=1e-12)
def test_eigengene_is_the_top_eigenvector():
rng = random.Random(75)
expr = [[rng.gauss(0, 1) for _ in range(6)] for _ in range(9)]
v = eigengene(expr)
x = [standardize(row) for row in expr]
c = [[sum(row[s] * row[t] for row in x) for t in range(6)] for s in range(6)]
cv = [sum(c[s][t] * v[t] for t in range(6)) for s in range(6)]
lam = sum(a * b for a, b in zip(v, cv))
assert math.isclose(sum(t * t for t in v), 1.0, rel_tol=1e-12)
for a, b in zip(cv, v):
assert math.isclose(a, lam * b, rel_tol=1e-6, abs_tol=1e-9)
for _ in range(200):
u = [rng.gauss(0, 1) for _ in range(6)]
nu = math.sqrt(sum(t * t for t in u))
u = [t / nu for t in u]
cu = [sum(c[s][t] * u[t] for t in range(6)) for s in range(6)]
assert sum(a * b for a, b in zip(u, cu)) <= lam + 1e-9
def test_scale_free_fit_matches_a_direct_regression():
rng = random.Random(76)
k = [rng.paretovariate(1.5) for _ in range(400)]
r2, slope = scale_free_fit(k)
lo, hi = min(k), max(k)
w = (hi - lo) / 10
bins = {}
for v in k:
bins.setdefault(min(int((v - lo) / w), 9), []).append(v)
xs = [math.log10(statistics.mean(vs)) for _, vs in sorted(bins.items())]
ys = [math.log10(len(vs) / 400) for _, vs in sorted(bins.items())]
fit = statistics.linear_regression(xs, ys)
assert math.isclose(slope, fit.slope, rel_tol=1e-9)
assert math.isclose(r2, statistics.correlation(xs, ys) ** 2, rel_tol=1e-9)
assert slope < 0
def test_planted_modules_measurement():
# A measurement with a fixed seed: two modules of 8 genes, each driven by
# its own hidden factor, and 4 noise genes, over 20 samples.
rng = random.Random(77)
samples = 20
f1 = [rng.gauss(0, 1) for _ in range(samples)]
f2 = [rng.gauss(0, 1) for _ in range(samples)]
expr = []
for f in (f1, f2):
for _ in range(8):
c = rng.choice([1.0, -1.0]) * rng.uniform(0.8, 1.2)
expr.append([c * x + rng.gauss(0, 0.3) for x in f])
for _ in range(4):
expr.append([rng.gauss(0, 1) for _ in range(samples)])
labels, eig = wgcna(expr, beta=6, height=0.8, min_size=4)
first, second = set(labels[:8]), set(labels[8:16])
assert len(first) == 1 and len(second) == 1 and first != second and 0 not in first | second
assert all(lab == 0 for lab in labels[16:])
for lab, f in ((labels[0], f1), (labels[8], f2)):
assert abs(pearson(eig[lab], f)) > 0.95
r = correlation_matrix(expr)
assert r[0][1] == r[1][0]
History
Ravasz et al. (2002) defined the topological overlap for unweighted metabolic networks and used it to cluster them into modules. Zhang and Horvath (2005) replaced the hard threshold on correlations by a soft power, generalized the overlap to weighted networks, and proposed the scale-free criterion for the power. Langfelder and Horvath (2008) released the WGCNA R package, with module eigengenes, module membership and Dynamic Tree Cut, and it became a common tool for the analysis of microarray and RNA-seq data.
References
- Bin Zhang and Steve Horvath, A general framework for weighted gene co-expression network analysis, Statistical Applications in Genetics and Molecular Biology 4(1) (2005), Article 17, the soft-threshold adjacency, the scale-free topology criterion for choosing the power, the generalized topological overlap for weighted networks, and modules from average-linkage clustering of the dissimilarity 1 - TOM
- Peter Langfelder and Steve Horvath, WGCNA, an R package for weighted correlation network analysis, BMC Bioinformatics 9 (2008), article 559, the package, module eigengenes, module membership, and the relation of modules to sample traits
- E. Ravasz, A. L. Somera, D. A. Mongru, Z. N. Oltvai and A.-L. Barabási, Hierarchical organization of modularity in metabolic networks, Science 297(5586) (2002), pages 1551 to 1555, the topological overlap of two nodes of an unweighted network, used to cluster metabolic networks into modules
- Peter Langfelder, Bin Zhang and Steve Horvath, Defining clusters from a hierarchical cluster tree, the Dynamic Tree Cut package for R, Bioinformatics 24(5) (2008), pages 719 to 720, the adaptive branch cutting used by WGCNA in place of a cut at one fixed height
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 WN4DQ5 Edit this page History Report an error Markdown