Algorithm Search⌘K

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
Properties
deterministicnot exactofflineiterative
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, aij=∣rij∣βa_{ij} = |r_{ij}|^\beta, 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 1−TOM1 - \text{TOM} 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 nn genes in mm samples, a power β≥1\beta \ge 1, a cut height HH 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 mm.

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

  1. WGCNA(X, β, H, minSize) ▷ X: n genes by m samples
  2. 1r_ij ← Pearson correlation of genes i and j across the samples
  3. 2a_ij ← |r_ij|^β (or ((1 + r_ij) / 2)^β for a signed network); a_ii ← 1
  4. 3k_i ← Σ_{u ≠ i} a_iu ▷ connectivity
  5. 4TOM_ij ← (Σ_{u ≠ i, j} a_iu a_uj + a_ij) / (min(k_i, k_j) + 1 - a_ij)
  6. 5d_ij ← 1 - TOM_ij
  7. 6T ← average-linkage hierarchical clustering of d
  8. 7labels ← clusters of T cut at height H; clusters smaller than minSize get label 0
  9. 8for each module: eigengene ← first right singular vector of its standardized genes
  10. 9return 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 [0,1][0, 1]. 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 m×mm \times m matrix Z⊤ZZ^\top Z, where ZZ 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 β\beta by the scale-free topology criterion: for each candidate power, fit a line to log⁡p(k)\log p(k) against log⁡k\log k, where p(k)p(k) is the fraction of genes with connectivity near kk, and take the smallest β\beta for which the R2R^2 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 k=(1.7,1.7,1.5,0.1)k = (1.7, 1.7, 1.5, 0.1). For genes 1 and 3, the paths of length 2 give a12a23+a14a43=0.63a_{12}a_{23} + a_{14}a_{43} = 0.63, so TOM13=(0.63+0.8)/(1.5+1−0.8)=0.8412\text{TOM}_{13} = (0.63 + 0.8)/(1.5 + 1 - 0.8) = 0.8412. 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 TOM14=0.0818\text{TOM}_{14} = 0.0818, because both are joined to gene 2. Average linkage on 1−TOM1 - \text{TOM} first joins genes 1 and 3 at height 0.1588, then adds gene 2 at height (0.1889+0.2111)/2=0.2(0.1889 + 0.2111)/2 = 0.2, and last adds gene 4 at height 0.9182. A cut at H=0.5H = 0.5 gives the labels (1,1,1,2)(1, 1, 1, 2): 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 [0,1][0, 1]. The topological overlap is symmetric and in [0,1][0, 1], because the shared weight ∑uaiuauj\sum_u a_{iu}a_{uj} is at most min⁡(ki,kj)−aij\min(k_i, k_j) - a_{ij}. 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 HH 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 [0,1][0, 1] (Lemma 1). The topological overlap is symmetric and lies in [0,1][0, 1] (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 X⊤XX^\top X, 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 β\beta by a scale-free fit is a heuristic. Neither is proved here.

Setting. The matrix XX holds nn genes and mm samples. Line L1 computes the Pearson correlations rijr_{ij}. Line L2 sets aij=∣rij∣βa_{ij} = |r_{ij}|^\beta (unsigned) or aij=((1+rij)/2)βa_{ij} = ((1 + r_{ij})/2)^\beta (signed) for i≠ji \ne j, with β>0\beta > 0, and aii=1a_{ii} = 1. Line L3 computes the connectivity ki=∑u≠iaiuk_i = \sum_{u \ne i}a_{iu}. Line L4 computes, for i≠ji \ne j,

TOMij=lij+aijmin⁡(ki,kj)+1−aij,lij=∑u≠i,jaiuauj,\mathrm{TOM}_{ij} = \frac{l_{ij} + a_{ij}}{\min(k_i, k_j) + 1 - a_{ij}}, \qquad l_{ij} = \sum_{u \ne i, j}a_{iu}a_{uj},

and TOMii=1\mathrm{TOM}_{ii} = 1. Line L5 sets the distance dij=1−TOMijd_{ij} = 1 - \mathrm{TOM}_{ij}.

Lemma 1 (adjacency). aa is symmetric and 0≤aij≤10 \le a_{ij} \le 1.

Proof. rij=rjir_{ij} = r_{ji}, and −1≤rij≤1-1 \le r_{ij} \le 1 by the Cauchy-Schwarz inequality. So ∣rij∣|r_{ij}| and (1+rij)/2(1 + r_{ij})/2 lie in [0,1][0, 1], and so do their powers with β>0\beta > 0. □\square

Lemma 2 (topological overlap). For any symmetric aa with entries in [0,1][0, 1] and aii=1a_{ii} = 1, TOM\mathrm{TOM} is symmetric and 0≤TOMij≤10 \le \mathrm{TOM}_{ij} \le 1. Also TOMij=0\mathrm{TOM}_{ij} = 0 exactly when aij=0a_{ij} = 0 and no third gene is joined to both ii and jj.

Proof. Symmetry holds because lijl_{ij}, aija_{ij} and min⁡(ki,kj)\min(k_i, k_j) are symmetric in ii and jj. Since auj≤1a_{uj} \le 1, lij≤∑u≠i,jaiu=ki−aijl_{ij} \le \sum_{u \ne i, j}a_{iu} = k_i - a_{ij}, and in the same way lij≤kj−aijl_{ij} \le k_j - a_{ij}. So lij+aij≤min⁡(ki,kj)l_{ij} + a_{ij} \le \min(k_i, k_j). The denominator is min⁡(ki,kj)+1−aij≥min⁡(ki,kj)\min(k_i, k_j) + 1 - a_{ij} \ge \min(k_i, k_j), since aij≤1a_{ij} \le 1. It is positive: if aij<1a_{ij} < 1 it is greater than min⁡(ki,kj)≥0\min(k_i, k_j) \ge 0, and if aij=1a_{ij} = 1 it is min⁡(ki,kj)≥aij=1\min(k_i, k_j) \ge a_{ij} = 1. So 0≤lij+aij≤denominator0 \le l_{ij} + a_{ij} \le \text{denominator}, which gives 0≤TOMij≤10 \le \mathrm{TOM}_{ij} \le 1. The numerator is a sum of nonnegative terms, so it is 0 exactly when aij=0a_{ij} = 0 and every product aiuauja_{iu}a_{uj} is 0. □\square

So dd is a symmetric dissimilarity with entries in [0,1][0, 1] 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 PP and QQ equals D(P,Q)=1∣P∣∣Q∣∑x∈P,y∈QdxyD(P, Q) = \frac{1}{|P||Q|}\sum_{x \in P, y \in Q}d_{xy}.

Proof. By induction on the steps. At the start every cluster is one gene and the stored distance is dxyd_{xy}. Suppose the claim holds before clusters AA and BB merge. For another cluster CC,

D(C,A∪B)=1∣C∣(∣A∣+∣B∣)(∑x∈C,y∈Adxy+∑x∈C,y∈Bdxy)=∣A∣D(C,A)+∣B∣D(C,B)∣A∣+∣B∣,D(C, A \cup B) = \frac{1}{|C|(|A| + |B|)}\left(\sum_{x \in C, y \in A}d_{xy} + \sum_{x \in C, y \in B}d_{xy}\right) = \frac{|A|D(C, A) + |B|D(C, B)}{|A| + |B|},

which is the value the code stores. The distances between clusters other than AA and BB do not change. □\square

Lemma 4 (monotone heights). The heights h1,h2,…,hn−1h_1, h_2, \dots, h_{n-1} of the merges satisfy h1≤h2≤⋯≤hn−1h_1 \le h_2 \le \dots \le h_{n-1}.

Proof. At step tt the code merges a pair A,BA, B with the smallest current distance hth_t, so every current distance is at least hth_t. After the merge, the new distances D(C,A∪B)D(C, A \cup B) are weighted means of D(C,A)≥htD(C, A) \ge h_t and D(C,B)≥htD(C, B) \ge h_t, so they are at least hth_t as well. The other distances do not change. So every distance after step tt is at least hth_t, and ht+1≥hth_{t+1} \ge h_t. □\square

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 HH, the labels of cut_tree put two genes in the same module exactly when they are in the same cluster after the merges with ht≤Hh_t \le H, and by Lemma 4 these merges are the first TT merges for some TT. Clusters with fewer than min_size genes get the label 0.

Proof. By Lemma 4, the set {t:ht≤H}\{t : h_t \le H\} is an initial segment {1,…,T}\{1, \dots, T\}. For each kept merge, the code joins all its members in a union-find structure. The clusters after TT 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. □\square

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 ZZ be the module matrix with each gene standardized to mean 0 and sample standard deviation 1. Let C=Z⊤ZC = Z^\top Z, a symmetric positive semidefinite m×mm \times m matrix with eigenvalues λ1≥λ2≥⋯≥0\lambda_1 \ge \lambda_2 \ge \dots \ge 0 and unit eigenvectors e1,…,eme_1, \dots, e_m. If λ1>λ2\lambda_1 > \lambda_2 and the start vector v0v_0 has e1⊤v0≠0e_1^\top v_0 \ne 0, the iterates vt=Cvt−1/∥Cvt−1∥v_t = Cv_{t-1}/\|Cv_{t-1}\| converge to ±e1\pm e_1, and e1e_1 is the first right singular vector of ZZ, the direction vv with ∥v∥=1\|v\| = 1 that maximizes ∥Zv∥2\|Zv\|^2.

Proof. Write v0=∑icieiv_0 = \sum_i c_ie_i with c1≠0c_1 \ne 0. Then Ctv0=∑iciλiteiC^tv_0 = \sum_i c_i\lambda_i^te_i, and vtv_t is this vector divided by its length. The terms with i≥2i \ge 2 have size at most ∣ci∣(λ2/λ1)t|c_i|(\lambda_2/\lambda_1)^t relative to the first term, which tends to 0. So vt→sign⁡(c1)e1v_t \to \operatorname{sign}(c_1)e_1, since every λi≥0\lambda_i \ge 0 and no sign changes occur. For a unit vector vv, ∥Zv∥2=v⊤Cv≤λ1\|Zv\|^2 = v^\top Cv \le \lambda_1, with equality at v=e1v = e_1. This is the first right singular vector by the definition of the singular value decomposition. □\square

The error after tt steps is O((λ2/λ1)t)O((\lambda_2/\lambda_1)^t), 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 (1,1.01,1.02,… )(1, 1.01, 1.02, \dots) is fixed. It is orthogonal to e1e_1 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 log⁡10p(k)\log_{10}p(k) against log⁡10k\log_{10}k, and returns R2R^2 and the slope. WGCNA picks the smallest β\beta whose R2R^2 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 D(P,Q)D(P, Q) 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 nn genes and mm samples, the correlations take Θ(n2m)\Theta(n^2m) time and the TOM takes Θ(n3)\Theta(n^3) time as written (a matrix product does the same work). The average linkage code scans all current pairs at each of the n−1n - 1 steps, which is O(n3)O(n^3) time; a nearest-neighbour chain makes it O(n2)O(n^2). The cut takes O(n2)O(n^2) time in the worst case because it reads the member lists. For a module of gg genes, the eigengene takes O(gm2)O(gm^2) to form CC and O(m2)O(m^2) per iteration. The extra space is Θ(n2)\Theta(n^2).

Complexity

On a real RAM, line L1 takes Θ(n2m)\Theta(n^2m) time for the n2/2n^2/2 correlations. Line L4 takes Θ(n3)\Theta(n^3), since each of the n2/2n^2/2 pairs sums over nn genes; this is the cost of a product of two n×nn \times n 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 Θ(n3)\Theta(n^3) in total; the nearest-neighbour chain algorithm does it in O(n2)O(n^2). The eigengenes take O(nm2)O(nm^2) to form the matrices plus O(m2)O(m^2) per iteration. The extra space is Θ(n2)\Theta(n^2) 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 [0,1][0, 1], and TOMij=0\text{TOM}_{ij} = 0 exactly when aij=0a_{ij} = 0 and no third gene is joined to both.
  • Not invariant to β\beta. 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 ((1+r)/2)β((1 + r)/2)^\beta 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 n×nn \times n 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.

weighted_gene_coexpression_network_analysis.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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
  4. 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.

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
  • a scene preset for the example