Algorithm Search⌘K

Algorithmadvanced

ARACNE

Also called algorithm for the reconstruction of accurate cellular networks.

Keep gene pairs with high mutual information, then delete the weakest edge of each triangle by the data processing inequality.

Time
O(m n log n + m^2 (n + b^2) + m^3) worst
Space
Θ(m^2 + m n) extra
Where
b = the number of bins per gene; m = the number of genes; n = the number of samples
Properties
deterministicnot exactofflineiterative
Origin
Adam A. Margolin, Ilya Nemenman, Katia Basso, Chris Wiggins, Gustavo Stolovitzky, Riccardo Dalla Favera, Andrea Califano, 2006

ARACNE builds an undirected network of genes from expression data in two steps. First it estimates the mutual information of every pair of genes and keeps the pairs above a threshold I0I_0. Then it looks at every triangle of kept pairs and deletes the edge with the smallest mutual information, because the data processing inequality says that an indirect link through a third gene can never carry more information than the two direct links it passes through. The method is one heuristic answer to gene regulatory network inference. With exact mutual information values and a true network that is a tree, it returns that tree exactly; with estimated values it has no such guarantee. For mm genes and nn samples it runs in O(mnlog⁡n+m2(n+b2)+m3)O(m n \log n + m^2 (n + b^2) + m^3) time with a binned estimator on bb bins.

In plain words

Two genes whose levels rise and fall together across many samples share information: knowing one tells you something about the other. A first guess at the network joins every pair that shares a lot of information. That guess has too many links. If gene A controls B and B controls C, then A and C also move together, only because B sits between them.

ARACNE removes those extra links with one rule. Look at any three genes that are all joined. The weakest of the three links is the most likely to be the indirect one, so cut it. Do this for every such group of three, decide all the cuts first, and then remove them together. What is left is a sparse network that keeps the strongest direct links.

The problem

Input. An expression matrix with mm genes and nn samples, xgsx_{g s} for gene gg and sample ss; a threshold I0≥0I_0 \ge 0; and a tolerance τ∈[0,1)\tau \in [0, 1). Genes are numbered 1 to mm on this page and 0 to m−1m - 1 in the code.

Output. A set of undirected edges {i,j}\{i, j\}, read as "genes ii and jj interact, directly". ARACNE gives no direction and no sign.

The mutual information of two random variables is the Kullback-Leibler divergence of their joint law from the product of the marginals,

I(X;Y)=DKL(PXY ∥ PXPY)=H(X)+H(Y)−H(X,Y),I(X; Y) = D_{\mathrm{KL}}(P_{XY} \,\|\, P_X P_Y) = H(X) + H(Y) - H(X, Y),

with HH the Shannon entropy in nats. It is zero exactly when XX and YY are independent, and for jointly normal variables with correlation ρ\rho it is −12ln⁡(1−ρ2)-\tfrac12 \ln(1 - \rho^2). This site has no separate page on mutual information.

The algorithm

Write IijI_{ij} for the estimate of I(Xi;Xj)I(X_i; X_j).

  1. ARACNE(X, I0, τ)
  2. 1for each pair of genes i < j do
  3. 2I[i, j] ← estimated mutual information of rows i and j of X
  4. 3E ← { {i, j} : I[i, j] > I0 }
  5. 4D ← ∅ ▷ edges to delete
  6. 5for each triangle {i, j, k} whose three edges are all in E do
  7. 6for each edge e of the triangle do
  8. 7if I(e) < (1 - τ) · I(f) for both other edges f of the triangle then D ← D ∪ {e}
  9. 8return E \ D

Lines L1 and L2 fill the matrix of pairwise estimates. Line L3 is the relevance network: all pairs above the threshold. Lines L5 to L7 apply the data processing inequality to every triangle of the relevance network, and line L8 removes all marked edges at the end. Because the marks are made on the fixed set EE, the result does not depend on the order in which the triangles are visited. With τ=0\tau = 0, line L7 marks the strict minimum of each triangle, and it marks nothing when the two smallest values are equal. A tolerance τ>0\tau > 0 marks an edge only when it is clearly the weakest, so it keeps more edges and some small loops. Margolin et al. write the condition as Iij≤Iik(1−τ)I_{ij} \le I_{ik} (1 - \tau) and report that values of τ\tau below 0.15 gave a reasonable trade-off on their test networks.

Estimating IijI_{ij}. The paper applies a rank (copula) transform to each gene, so that each marginal is uniform on [0,1][0, 1], and then uses a Gaussian kernel density estimator with one fixed kernel width. The threshold I0I_0 comes from a null: shuffle the samples of each gene to break all dependence, estimate the mutual information of the shuffled pairs, and pick I0I_0 at a chosen p-value, with an exponential fit to the tail for small p-values. The implementation on this site uses a simpler estimator: it puts the ranks of each gene into bb bins of equal size and computes the plug-in value ∑u,vp^uvln⁡(p^uv/(p^up^v))\sum_{u, v} \hat p_{uv} \ln(\hat p_{uv} / (\hat p_u \hat p_v)). It takes I0I_0 as a parameter, and it leaves out the kernel estimator, the permutation null and the bootstrap of later versions. The pruning step, lines L3 to L8, is the same as in the paper.

Example

Take four genes A, B, C and D in a tree with B at the center: A, C and D each connect to B only. Let the expression be jointly normal with correlations 0.9 for A and B, 0.8 for B and C and 0.7 for B and D. In such a tree, the correlation of two genes is the product of the correlations along the path between them, so A and C have 0.72, A and D have 0.63, and C and D have 0.56. The exact mutual information values −12ln⁡(1−ρ2)-\tfrac12 \ln(1 - \rho^2) are:

pair AB BC AC BD AD CD
ρ\rho 0.9 0.8 0.72 0.7 0.63 0.56
II (nats) 0.830366 0.510826 0.365321 0.336672 0.252836 0.188147

With I0=0.1I_0 = 0.1, line L3 keeps all six pairs, so all four triangles are present. With τ=0\tau = 0, line L7 marks AC in triangle ABC, AD in ABD, CD in ACD and CD again in BCD. Line L8 returns AB, BC and BD, the true tree. With τ=0.15\tau = 0.15 the result is the same, because in every triangle the weakest edge is below 0.850.85 times the other two (the largest ratio is 0.252836/0.336672=0.7510.252836 / 0.336672 = 0.751, in ABD). With τ=0.3\tau = 0.3 the factor is 0.7. Then AC survives, since 0.365321/0.510826=0.715>0.70.365321 / 0.510826 = 0.715 > 0.7, and so does AD, since 0.751>0.70.751 > 0.7; CD is still marked in BCD, where its ratio to BD is 0.5590.559. So the result has five edges: the tree and the two indirect edges AC and AD.

On sampled data. The test of the implementation simulates a normal tree model with 8 genes, 7 edges with correlations from 0.7 to 0.85, and 250 samples (seed 7), and uses 4 bins and I0=0.05I_0 = 0.05. All 28 pairs pass the threshold, so the relevance network is the complete graph. After the DPI step, the result is exactly the 7 true edges. This is one measurement on easy data, not a guarantee: with fewer samples, weaker links or a network with many short loops, ARACNE deletes true edges and keeps false ones.

Correctness

ARACNE is a heuristic, so its correctness has two parts. The first part is that the code computes what lines L3 to L8 define: the set of edges of the relevance network that are not the (1−τ)(1 - \tau)-weakest edge of any of its triangles. The loop visits each triangle once and the marks do not change EE, so this holds by inspection; the test compares it with a direct check of the definition over all triples.

The second part is what the output means. The data processing inequality (Cover and Thomas, Theorem 2.8.1) says that if X→Y→ZX \to Y \to Z is a Markov chain, then I(X;Z)≤I(X;Y)I(X; Z) \le I(X; Y), and since Z→Y→XZ \to Y \to X is also a Markov chain, I(X;Z)≤min⁡(I(X;Y),I(Y;Z))I(X; Z) \le \min(I(X; Y), I(Y; Z)). Suppose the joint law of the genes is Markov with respect to a tree TT, so that XiX_i and XkX_k are independent given XjX_j whenever jj lies on the path from ii to kk in TT.

Theorem. Assume the values IijI_{ij} are exact, I0<IijI_0 < I_{ij} for every edge {i,j}\{i, j\} of TT, and for any three distinct genes with jj on the path from ii to kk in TT, Iik<(1−τ)min⁡(Iij,Ijk)I_{ik} < (1 - \tau) \min(I_{ij}, I_{jk}). Then ARACNE returns exactly the edges of TT.

The proof has two steps. No edge of TT is marked: for an edge {i,j}\{i, j\} and a third gene kk on the side of ii, gene ii is on the path from kk to jj, so Ikj<IijI_{kj} < I_{ij}, and line L7 cannot mark {i,j}\{i, j\} against {k,j}\{k, j\}. Every other edge that passes the threshold is marked: for a pair {i,k}\{i, k\} at distance at least 2 in TT, let jj be the neighbor of ii on the path; then {i,j}\{i, j\} passes the threshold by assumption, {j,k}\{j, k\} passes it because Ijk>Iik>I0I_{jk} > I_{ik} > I_0, and line L7 marks {i,k}\{i, k\} in the triangle {i,j,k}\{i, j, k\}. This is Theorem 1 of Margolin et al. The DPI gives the hypothesis with ≤\le in place of << and τ=0\tau = 0; the strict form holds, for example, for a normal tree with all correlations in (0,1)(0, 1) in absolute value, because ∣ρik∣=∣ρij∣∣ρjk∣|\rho_{ik}| = |\rho_{ij}| |\rho_{jk}|. The full proof is below.

The theorem says nothing about networks with loops, such as a feed-forward loop, where the true triangle loses its weakest edge.

Proof: ARACNE computes its pruned network, and recovers a tree from exact valuesfull

Setup. Let II be a symmetric m×mm \times m matrix of non-negative numbers, I0≥0I_0 \ge 0 and τ∈[0,1)\tau \in [0, 1). Let E={{i,j}:Iij>I0}E = \{\{i, j\} : I_{ij} > I_0\}, the set of line L3. A triangle of EE is a set {i,j,k}\{i, j, k\} of three genes whose three pairs are all in EE. Call an edge ee of a triangle weak in it when I(e)<(1−τ)I(f)I(e) < (1 - \tau) I(f) for both other edges ff of the triangle. Define

A={ e∈E:e is weak in no triangle of E }.A = \{\, e \in E : e \text{ is weak in no triangle of } E \,\}.

Lemma 1. ARACNE returns AA.

Proof. Line L4 starts with D=∅D = \emptyset. Lines L5 to L7 visit every triangle of EE, and line L7 adds to DD exactly the edges that are weak in the visited triangle. The loop does not change EE or II, so the triangles and the test of line L7 are the same whatever the order of the visits. After the loop, DD is the set of edges of EE that are weak in at least one triangle of EE, and line L8 returns E∖D=AE \setminus D = A. □\square

Lemma 2 (data processing inequality). If the random variables XX, YY and ZZ satisfy that XX and ZZ are independent given YY, then I(X;Z)≤min⁡(I(X;Y),I(Y;Z))I(X; Z) \le \min(I(X; Y), I(Y; Z)).

Proof. By the chain rule of mutual information, I(X;Y,Z)=I(X;Z)+I(X;Y∣Z)=I(X;Y)+I(X;Z∣Y)I(X; Y, Z) = I(X; Z) + I(X; Y \mid Z) = I(X; Y) + I(X; Z \mid Y). The term I(X;Z∣Y)I(X; Z \mid Y) is zero by the conditional independence, and I(X;Y∣Z)≥0I(X; Y \mid Z) \ge 0. So I(X;Z)≤I(X;Y)I(X; Z) \le I(X; Y). The hypothesis is symmetric in XX and ZZ, so the same argument with XX and ZZ exchanged gives I(X;Z)≤I(Z;Y)I(X; Z) \le I(Z; Y). This is Theorem 2.8.1 of Cover and Thomas. □\square

Now let TT be a tree on the genes. Say that the law of (X1,…,Xm)(X_1, \ldots, X_m) is Markov on TT if XiX_i and XkX_k are independent given XjX_j whenever jj is an inner node of the path from ii to kk in TT. By Lemma 2, exact values then satisfy Iik≤min⁡(Iij,Ijk)I_{ik} \le \min(I_{ij}, I_{jk}) for each such triple. The theorem needs a strict form with the tolerance.

Theorem. Let Iij=I(Xi;Xj)I_{ij} = I(X_i; X_j) be exact, and assume:

  1. Iij>I0I_{ij} > I_0 for every edge {i,j}\{i, j\} of TT;
  2. for any three distinct genes ii, jj, kk with jj an inner node of the path from ii to kk in TT, Iik<(1−τ)min⁡(Iij,Ijk)I_{ik} < (1 - \tau) \min(I_{ij}, I_{jk}).

Then ARACNE returns the edge set of TT.

Proof. By Lemma 1 it is enough to show that AA is the edge set of TT.

Step 1: every edge of TT is in AA. Let {i,j}\{i, j\} be an edge of TT. By assumption 1 it is in EE. Suppose it were weak in a triangle {i,j,k}\{i, j, k\} of EE. Deleting the edge {i,j}\{i, j\} from TT splits the tree into two parts, one with ii and one with jj. By the symmetry of the claim we may assume that kk is in the part of ii. Then the path from kk to jj in TT goes through ii, and ii is an inner node of it. Assumption 2 for the triple (k,i,j)(k, i, j) gives Ikj<(1−τ)Iij≤IijI_{kj} < (1 - \tau) I_{ij} \le I_{ij}. Weakness of {i,j}\{i, j\} needs Iij<(1−τ)Ikj≤IkjI_{ij} < (1 - \tau) I_{kj} \le I_{kj}, which contradicts Ikj<IijI_{kj} < I_{ij}. So {i,j}\{i, j\} is weak in no triangle, and it is in AA.

Step 2: no other pair is in AA. Let {i,k}\{i, k\} be a pair that is not an edge of TT. If {i,k}∉E\{i, k\} \notin E, it is not in AA. Otherwise, the path from ii to kk in TT has at least two edges. Let jj be the node after ii on it, so {i,j}\{i, j\} is an edge of TT and jj is an inner node of the path. By assumption 1, {i,j}∈E\{i, j\} \in E. By assumption 2, Iik<(1−τ)IjkI_{ik} < (1 - \tau) I_{jk}, so Ijk>Iik/(1−τ)≥Iik>I0I_{jk} > I_{ik} / (1 - \tau) \ge I_{ik} > I_0, and {j,k}∈E\{j, k\} \in E. So {i,j,k}\{i, j, k\} is a triangle of EE, and assumption 2 says that Iik<(1−τ)IijI_{ik} < (1 - \tau) I_{ij} and Iik<(1−τ)IjkI_{ik} < (1 - \tau) I_{jk}. So {i,k}\{i, k\} is weak in it, and it is not in AA.

Steps 1 and 2 show that AA is the edge set of TT. ■\blacksquare

The normal case. Let the genes be jointly normal and Markov on TT, with correlation rer_e on each edge ee of TT, 0<∣re∣<10 < |r_e| < 1. Then the correlation of genes ii and kk is the product of rer_e over the path between them, so ∣ρik∣=∣ρij∣ ∣ρjk∣<min⁡(∣ρij∣,∣ρjk∣)|\rho_{ik}| = |\rho_{ij}| \, |\rho_{jk}| < \min(|\rho_{ij}|, |\rho_{jk}|) when jj is an inner node of the path. The map ρ↦−12ln⁡(1−ρ2)\rho \mapsto -\tfrac12 \ln(1 - \rho^2) is strictly increasing in ∣ρ∣|\rho|, so assumption 2 holds with τ=0\tau = 0, and assumption 1 holds with I0=0I_0 = 0. This is the case that the test checks on random trees.

Complexity

The model is the real RAM, with each logarithm and division as one step.

  • Estimates, lines L1 and L2. Ranking each gene costs O(nlog⁡n)O(n \log n), so O(mnlog⁡n)O(m n \log n) for all genes. Each of the m(m−1)/2m(m - 1)/2 pairs then costs O(n)O(n) to fill a b×bb \times b table of counts and O(b2)O(b^2) to sum it, so O(m2(n+b2))O(m^2 (n + b^2)) in all. The kernel estimator of the paper costs O(n2)O(n^2) per pair instead, which gives the term N2M2N^2 M^2 of the paper for NN genes and MM samples.
  • Pruning, lines L3 to L8. Line L3 is O(m2)O(m^2). The triangles are found by intersecting the neighbor sets of the two ends of each edge, which is O(m)O(m) per edge and O(m3)O(m^3) in all, and each triangle costs O(1)O(1). When all pairs pass the threshold there are (m3)\binom{m}{3} triangles, so the bound m3m^3 is reached.
  • Space. The matrix of estimates takes Θ(m2)\Theta(m^2) numbers and the bins take Θ(mn)\Theta(m n).

In practice the estimation term dominates for many samples. For the full genome (mm near 20000) the m3m^3 term is large too. A common remedy is to keep only the pairs that contain a known transcription factor.

Properties

  • Deterministic. For fixed estimates, the output does not depend on the gene order, by the two-phase marking.
  • Monotone in τ\tau. A larger tolerance marks a subset of the edges, so the output grows with τ\tau.
  • Undirected and unsigned. Mutual information is symmetric and ignores the sign of the dependence, so ARACNE cannot tell activation from repression or cause from effect.
  • Contains the Chow-Liu tree. The Chow-Liu tree is a maximum spanning tree of the complete graph weighted by mutual information. With τ=0\tau = 0 and I0=0I_0 = 0, every edge of positive weight of such a tree is in the output (Theorem 2 of the paper states this for exact values). The reason is the cycle property: line L7 marks only the strict minimum of a triangle, and the strict minimum of a cycle is in no maximum spanning tree.

Variants and improvements

  • Relevance network. Stop after line L3. This is the older method of Butte and Kohane, which keeps all indirect links.
  • Known regulators. Keep only pairs with at least one transcription factor, and apply the DPI only to triangles that contain a transcription factor. This cuts the work and the number of target to target edges.
  • ARACNe-AP. Lachmann et al. (2016) estimate the mutual information with adaptive partitioning, which is much faster than the kernel estimator, and run ARACNE on many bootstrap samples, keeping the edges that appear more often than chance.
  • Other uses of mutual information. CLR scores each pair against the background distribution of the mutual information of each gene, and MRNET picks edges by a minimum redundancy rule. DREAM5 (Marbach et al. 2012) compared several mutual information methods with regression, correlation and Bayesian network methods, and found that mutual information and correlation methods recovered feed-forward loops better than the regression methods.
  • Conditional independence instead of the DPI. A Gaussian graphical model removes an edge when the partial correlation, given all other genes, is zero. It handles loops, but needs more samples than genes or a sparsity penalty.

When to use it

Use ARACNE for many samples of one cell type, under many conditions, when you want a sparse, undirected list of candidate direct partners of each regulator, and you accept that true triangles are broken. The estimates need many samples: with a few dozen, the noise in the mutual information is of the same size as the gaps that line L7 compares. For directed links from regulators to targets, a regression method such as GENIE3 ranks the candidates; for time series, a dynamic Bayesian network can use the time order.

Pitfalls

  • Real loops are cut. Every triangle loses one edge with τ=0\tau = 0. A feed-forward loop, common in transcription networks, always loses one of its three links.
  • Ties. With τ=0\tau = 0 and the strict test of line L7, a triangle with two equal smallest values loses neither. Binned estimates on small samples give many ties; a small τ\tau or a finer estimator avoids surprises.
  • Estimator bias. The plug-in estimate on bb bins is biased upward by about (b−1)2/(2n)(b - 1)^2 / (2n) nats for independent genes, so the threshold must come from a null on the same nn and bb, not from a fixed number.
  • Order of removal. Deleting the weakest edge of each triangle at once, in a loop over triangles, gives a result that depends on the order. Mark first, then delete.
  • Not causal. An edge means strong dependence that the DPI step did not explain away. A hidden common regulator that is not measured makes two targets look directly linked.

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.

aracne.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/aracne/. The authors are listed in prov/VF2D8H.jsonl.
"""ARACNE: mutual information network with data processing inequality pruning.

The expression data is a list of m genes, and each gene is a list of n
samples (floats). Genes are numbered 0 .. m-1 in the code (the page numbers
them from 1). An edge is a pair (i, j) with i < j.

The original method of Margolin et al. (2006) estimates mutual information
with a Gaussian kernel estimator on rank (copula) transformed data, and picks
the threshold I0 from a permutation null. This file uses a plug-in estimate on
equal-frequency bins of the ranks, and takes I0 as a parameter. The pruning
step (lines L4 to L8 of the page) is the same as in the paper.
"""

from __future__ import annotations

import math
from typing import Dict, List, Sequence, Set, Tuple

Edge = Tuple[int, int]


def ranks(xs: Sequence[float]) -> List[int]:
    """Rank of each value, 0 .. n-1. Ties are broken by position (stable)."""
    order = sorted(range(len(xs)), key=lambda s: xs[s])
    r = [0] * len(xs)
    for pos, s in enumerate(order):
        r[s] = pos
    return r


def equal_frequency_bins(xs: Sequence[float], b: int) -> List[int]:
    """Bin index 0 .. b-1 of each value: rank r goes to bin floor(r b / n)."""
    n = len(xs)
    return [r * b // n for r in ranks(xs)]


def mutual_information_binned(x: Sequence[float], y: Sequence[float], b: int) -> float:
    """Plug-in mutual information, in nats, of two samples on b x b rank bins."""
    if len(x) != len(y) or len(x) == 0:
        raise ValueError("x and y must have the same positive length")
    return mi_from_bins(equal_frequency_bins(x, b), equal_frequency_bins(y, b), b)


def mi_from_bins(bx: Sequence[int], by: Sequence[int], b: int) -> float:
    """Plug-in mutual information, in nats, of two binned samples; O(n + b^2) time."""
    n = len(bx)
    joint: Dict[Tuple[int, int], int] = {}
    cx = [0] * b
    cy = [0] * b
    for s in range(n):
        joint[(bx[s], by[s])] = joint.get((bx[s], by[s]), 0) + 1
        cx[bx[s]] += 1
        cy[by[s]] += 1
    mi = 0.0
    for (u, v), c in joint.items():
        mi += c / n * math.log(c * n / (cx[u] * cy[v]))
    return mi


def gaussian_mutual_information(rho: float) -> float:
    """Mutual information, in nats, of two jointly normal variables with correlation rho."""
    return -0.5 * math.log(1.0 - rho * rho)


def mi_matrix(data: Sequence[Sequence[float]], b: int) -> List[List[float]]:
    """Symmetric m x m matrix of binned mutual information (diagonal 0)."""
    m = len(data)
    bins = [equal_frequency_bins(gene, b) for gene in data]  # one sort per gene
    mi = [[0.0] * m for _ in range(m)]
    for i in range(m):
        for j in range(i + 1, m):
            v = mi_from_bins(bins[i], bins[j], b)  # @line L2
            mi[i][j] = mi[j][i] = v
    return mi


def aracne_prune(mi: Sequence[Sequence[float]], threshold: float, tolerance: float = 0.0) -> Set[Edge]:
    """Lines L3 to L8: threshold the matrix, then apply the DPI to every triangle.

    An edge e of a triangle whose three edges all pass the threshold is removed
    when I(e) < (1 - tolerance) * I(f) for both other edges f of the triangle.
    All removals are decided on the thresholded graph and applied at the end,
    so the result does not depend on the order of the genes.
    """
    m = len(mi)
    if not 0.0 <= tolerance < 1.0:
        raise ValueError("tolerance must be in [0, 1)")
    keep = 1.0 - tolerance
    adj: List[Set[int]] = [set() for _ in range(m)]
    edges: Set[Edge] = set()
    for i in range(m):
        for j in range(i + 1, m):
            if mi[i][j] > threshold:  # @line L3
                edges.add((i, j))
                adj[i].add(j)
                adj[j].add(i)
    removed: Set[Edge] = set()  # @line L4
    for i, j in sorted(edges):
        for k in sorted(adj[i] & adj[j]):
            if k <= j:
                continue  # @line L5
            # the triangle i < j < k, visited once
            tri = ((i, j), (i, k), (j, k))  # @line L6
            for e in tri:
                others = [f for f in tri if f != e]
                ie = mi[e[0]][e[1]]
                if all(ie < keep * mi[f[0]][f[1]] for f in others):  # @line L7
                    removed.add(e)
    return edges - removed  # @line L8


def aracne(data: Sequence[Sequence[float]], threshold: float, tolerance: float = 0.0, b: int = 4) -> Set[Edge]:
    """Lines L1 to L8: estimate all pairwise MI values, then prune."""
    for gene in data:  # @line L1
        if len(gene) != len(data[0]):
            raise ValueError("every gene needs the same number of samples")
    return aracne_prune(mi_matrix(data, b), threshold, tolerance)


def tree_correlations(m: int, parent: Sequence[int], r: Sequence[float]) -> List[List[float]]:
    """Exact correlations of a Gaussian tree model.

    Gene 0 is the root, parent[c] < c is the parent of gene c >= 1, and r[c] is
    the correlation of gene c with its parent. The correlation of two genes is
    the product of r over the edges of the path between them.
    """
    path_to_root = []
    for c in range(m):
        p = [c]
        while p[-1] != 0:
            p.append(parent[p[-1]])
        path_to_root.append(p)
    rho = [[1.0] * m for _ in range(m)]
    for a in range(m):
        for b2 in range(a + 1, m):
            pa, pb = path_to_root[a], set(path_to_root[b2])
            lca = next(v for v in pa if v in pb)
            prod = 1.0
            for v in pa:
                if v == lca:
                    break
                prod *= r[v]
            for v in path_to_root[b2]:
                if v == lca:
                    break
                prod *= r[v]
            rho[a][b2] = rho[b2][a] = prod
    return rho


def simulate_tree(rng, m: int, parent: Sequence[int], r: Sequence[float], n: int) -> List[List[float]]:
    """n samples of the Gaussian tree model, gene by gene in index order per sample.

    Each sample draws gene 0 then genes 1 .. m-1 with rng.gauss(0, 1):
    x_c = r[c] x_parent + sqrt(1 - r[c]^2) z.
    """
    data = [[0.0] * n for _ in range(m)]
    for s in range(n):
        data[0][s] = rng.gauss(0.0, 1.0)
        for c in range(1, m):
            data[c][s] = r[c] * data[parent[c]][s] + math.sqrt(1.0 - r[c] * r[c]) * rng.gauss(0.0, 1.0)
    return data
test_aracne.py 186 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/aracne/. The authors are listed in prov/VF2D8H.jsonl.

import math
import random

from aracne import (
    aracne,
    aracne_prune,
    gaussian_mutual_information,
    mi_matrix,
    mutual_information_binned,
    simulate_tree,
    tree_correlations,
)


def brute_force_prune(mi, threshold, tolerance):
    """The definition: keep a passing edge unless some passing triangle has it as the weakest edge."""
    m = len(mi)
    passing = {(i, j) for i in range(m) for j in range(i + 1, m) if mi[i][j] > threshold}
    out = set()
    for i, j in passing:
        dropped = False
        for k in range(m):
            if k in (i, j):
                continue
            a, b = tuple(sorted((i, k))), tuple(sorted((j, k)))
            if a in passing and b in passing:
                if mi[i][j] < (1 - tolerance) * mi[a[0]][a[1]] and mi[i][j] < (1 - tolerance) * mi[b[0]][b[1]]:
                    dropped = True
        if not dropped:
            out.add((i, j))
    return out


def gaussian_mi_matrix(rho):
    m = len(rho)
    return [[0.0 if i == j else gaussian_mutual_information(rho[i][j]) for j in range(m)] for i in range(m)]


def random_tree(rng, m):
    parent = [0] + [rng.randrange(c) for c in range(1, m)]
    r = [1.0] + [rng.choice([-1, 1]) * rng.uniform(0.3, 0.95) for _ in range(1, m)]
    return parent, r


def test_binned_mi_identical_variables_is_log_b():
    rng = random.Random(1)
    x = [rng.random() for _ in range(120)]
    for b in (2, 3, 4, 5):
        assert abs(mutual_information_binned(x, x, b) - math.log(b)) < 1e-12
        y = [-v ** 3 for v in x]  # a decreasing map keeps the bins, in reverse
        assert abs(mutual_information_binned(x, y, b) - math.log(b)) < 1e-12


def test_binned_mi_balanced_grid_is_zero():
    b, c = 4, 5
    n = b * b * c
    x = list(range(n))
    # within each x bin, the y bins are filled in turn, so every cell gets c points
    y = [((s % (n // b)) % b) * (n // b) + s // b for s in range(n)]
    assert sorted(y) == list(range(n))
    assert abs(mutual_information_binned(x, y, b)) < 1e-12


def test_binned_mi_symmetric_and_nonnegative():
    rng = random.Random(2)
    for _ in range(20):
        x = [rng.gauss(0, 1) for _ in range(60)]
        y = [v + rng.gauss(0, 1) for v in x]
        a = mutual_information_binned(x, y, 3)
        assert a >= -1e-12
        assert abs(a - mutual_information_binned(y, x, 3)) < 1e-12


def test_worked_example_of_the_page():
    # genes A, B, C, D = 0, 1, 2, 3; B is the hub of a tree
    parent = [1, 0, 1, 1]
    rho = [[1.0] * 4 for _ in range(4)]
    edge = {(0, 1): 0.9, (1, 2): 0.8, (1, 3): 0.7}
    for (i, j), v in edge.items():
        rho[i][j] = rho[j][i] = v
    for i, j in ((0, 2), (0, 3), (2, 3)):
        rho[i][j] = rho[j][i] = rho[i][1] * rho[1][j]
    mi = gaussian_mi_matrix(rho)
    assert abs(mi[0][1] - 0.830366) < 1e-6
    assert abs(mi[2][3] - 0.188147) < 1e-6
    assert aracne_prune(mi, 0.1, 0.0) == {(0, 1), (1, 2), (1, 3)}
    assert aracne_prune(mi, 0.1, 0.15) == {(0, 1), (1, 2), (1, 3)}
    assert aracne_prune(mi, 0.1, 0.3) == {(0, 1), (1, 2), (1, 3), (0, 2), (0, 3)}
    assert aracne_prune(mi, 0.3, 0.0) == {(0, 1), (1, 2), (1, 3)}
    assert parent[0] == 1


def test_prune_matches_brute_force():
    rng = random.Random(3)
    for trial in range(200):
        m = rng.randint(3, 8)
        mi = [[0.0] * m for _ in range(m)]
        for i in range(m):
            for j in range(i + 1, m):
                mi[i][j] = mi[j][i] = rng.choice([rng.random(), round(rng.random(), 1)])
        th = rng.choice([0.0, 0.2, 0.5])
        tol = rng.choice([0.0, 0.1, 0.3])
        assert aracne_prune(mi, th, tol) == brute_force_prune(mi, th, tol)


def test_result_does_not_depend_on_gene_order():
    rng = random.Random(4)
    for _ in range(50):
        m = 7
        mi = [[0.0] * m for _ in range(m)]
        for i in range(m):
            for j in range(i + 1, m):
                mi[i][j] = mi[j][i] = rng.random()
        perm = list(range(m))
        rng.shuffle(perm)
        inv = [0] * m
        for a, p in enumerate(perm):
            inv[p] = a
        mi2 = [[mi[perm[a]][perm[b]] for b in range(m)] for a in range(m)]
        e1 = aracne_prune(mi, 0.1, 0.05)
        e2 = {tuple(sorted((perm[a], perm[b]))) for a, b in aracne_prune(mi2, 0.1, 0.05)}
        assert e1 == e2


def test_larger_tolerance_keeps_more_edges():
    rng = random.Random(5)
    for _ in range(50):
        m = 6
        mi = [[0.0] * m for _ in range(m)]
        for i in range(m):
            for j in range(i + 1, m):
                mi[i][j] = mi[j][i] = rng.random()
        prev = aracne_prune(mi, 0.0, 0.0)
        for tol in (0.05, 0.1, 0.2, 0.5, 0.9):
            cur = aracne_prune(mi, 0.0, tol)
            assert prev <= cur
            prev = cur


def test_exact_mi_on_a_tree_gives_the_tree():
    # Theorem 1 of Margolin et al. 2006: exact MI values of a tree network
    rng = random.Random(6)
    for _ in range(100):
        m = rng.randint(2, 12)
        parent, r = random_tree(rng, m)
        mi = gaussian_mi_matrix(tree_correlations(m, parent, r))
        truth = {tuple(sorted((c, parent[c]))) for c in range(1, m)}
        assert aracne_prune(mi, 0.0, 0.0) == truth


def test_tree_correlation_products():
    parent = [0, 0, 1, 1]
    r = [1.0, 0.5, -0.6, 0.8]
    rho = tree_correlations(4, parent, r)
    assert abs(rho[2][3] - (-0.6 * 0.8)) < 1e-15
    assert abs(rho[0][3] - 0.5 * 0.8) < 1e-15
    assert abs(rho[0][2] - 0.5 * -0.6) < 1e-15


def test_recovery_on_simulated_data_is_measured():
    # a measurement for one seed, not a guarantee: 8 genes, 250 samples, 4 bins
    rng = random.Random(7)
    m, n = 8, 250
    parent = [0, 0, 1, 1, 2, 2, 3, 0]
    r = [1.0, 0.85, 0.8, 0.75, 0.8, 0.7, 0.85, 0.8]
    data = simulate_tree(rng, m, parent, r, n)
    truth = {tuple(sorted((c, parent[c]))) for c in range(1, m)}
    mi = mi_matrix(data, 4)
    relevance = {(i, j) for i in range(m) for j in range(i + 1, m) if mi[i][j] > 0.05}
    pruned = aracne(data, 0.05, 0.0, 4)
    assert pruned <= relevance
    assert truth <= relevance
    fp_rel = len(relevance - truth)
    fp_ar = len(pruned - truth)
    tp_ar = len(pruned & truth)
    assert fp_ar < fp_rel
    assert tp_ar >= 6
    # the measured numbers quoted on the page
    assert (len(relevance), tp_ar, fp_ar) == MEASURED


# all 28 pairs pass the threshold; ARACNE keeps the 7 true edges and no other
MEASURED = (28, 7, 0)

History

Butte and Kohane proposed relevance networks of mutual information in 2000. Basso, Margolin, Stolovitzky, Klein, Dalla Favera and Califano used ARACNE in 2005 to reconstruct a regulatory network of human B cells. Margolin and coauthors gave the full description, the theorems and the tests on synthetic networks in BMC Bioinformatics in 2006. Lachmann, Giorgi, Lopez and Califano published the faster ARACNe-AP in 2016.

References

  1. Adam A. Margolin, Ilya Nemenman, Katia Basso, Chris Wiggins, Gustavo Stolovitzky, Riccardo Dalla Favera and Andrea Califano, ARACNE, an algorithm for the reconstruction of gene regulatory networks in a mammalian cellular context, BMC Bioinformatics 7 (Suppl 1), S7, 2006, the sections on the algorithm (MI estimation, the threshold and the DPI with tolerance), Theorems 1 to 3 on exact reconstruction, and the complexity O(N^3 + N^2 M^2)
  2. Thomas M. Cover and Joy A. Thomas, Elements of Information Theory, 2nd edition, Wiley, 2006, Section 2.8, the data-processing inequality (Theorem 2.8.1)
  3. Katia Basso, Adam A. Margolin, Gustavo Stolovitzky, Ulf Klein, Riccardo Dalla Favera and Andrea Califano, Reverse engineering of regulatory networks in human B cells, Nature Genetics 37(4), 2005, the application of ARACNE to B cell expression profiles
  4. Alexander Lachmann, Federico M. Giorgi, Gonzalo Lopez and Andrea Califano, ARACNe-AP, gene network reverse engineering through adaptive partitioning inference of mutual information, Bioinformatics 32(14), 2016, the adaptive partitioning estimator and the bootstrap consensus
  5. Atul J. Butte and Isaac S. Kohane, Mutual information relevance networks, 2000, the relevance network, all gene pairs with mutual information above a threshold
  6. Daniel Marbach et al., Wisdom of crowds for robust gene network inference, Nature Methods 9(8), 2012, the DREAM5 comparison, in which ARACNE is one of the mutual information methods

About this page

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

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