Algorithm Search⌘K

Algorithmresearch

LiNGAM

Also called linear non-Gaussian acyclic model.

Identifies the full causal DAG of a linear model with non-Gaussian noise, by independent component analysis or by DirectLiNGAM's search for exogenous variables.

Time
Θ(n^3 m + n^4) worst · best
Space
Θ(n m) extra
Where
m = the number of samples; n = the number of variables
Properties
deterministicnot exactofflineiterative
Origin
Shohei Shimizu, Patrik O. Hoyer, Aapo Hyvärinen, Antti Kerminen, 2006

LiNGAM, the linear non-Gaussian acyclic model, is a structural causal model in which each variable is a linear function of its causes plus an independent error, the causes form a directed acyclic graph, and the errors are not Gaussian. The same name is used for the methods that learn the graph from data. Methods such as the PC algorithm and greedy equivalence search use only conditional independences, so they can return only a Markov equivalence class, and they cannot orient X−YX - Y for two variables. LiNGAM uses the shape of the distribution, not only its covariances. Shimizu, Hoyer, Hyvärinen and Kerminen (2006) proved that this identifies the whole DAG and its weights, and found it with independent component analysis. DirectLiNGAM (Shimizu et al. 2011), the version on this page, finds the causes one at a time instead.

In plain words

Suppose one quantity causes another, and each also has its own random push from outside. If the pushes follow the bell curve, the data look the same in both directions, and no method can tell cause from effect. If the pushes have any other shape, the directions differ. When you predict the effect from the cause, what is left over is the effect's own push, and it has nothing to do with the cause. When you predict the cause from the effect, what is left over still depends on the effect, even if it is uncorrelated with it. DirectLiNGAM uses this to find a variable that nothing else causes, removes its influence from all other variables, and repeats. This gives an order from causes to effects. Regression along this order then gives the arrows and their strengths.

The problem

The data are mm samples of nn variables from the model

x=Bx+e,x = Bx + e,

where Bji≠0B_{ji} \ne 0 means the edge i→ji \to j, the graph of BB has no directed cycle, and the components of ee are independent, non-Gaussian, with mean 0 and finite positive variance. There are no hidden common causes: every dependence between errors would have to come from such a cause, and the model forbids it. A causal order is an order of the variables in which every edge points forward, a topological order of the graph. A variable is exogenous when it has no parent, so it equals its own error.

The task is to estimate a causal order and BB. Then x=(I−B)−1ex = (I - B)^{-1}e is a linear mixture of independent non-Gaussian sources, which is the model of independent component analysis, with the extra structure that I−BI - B is triangular up to a permutation.

The algorithm

For two centred variables, the residual of xix_i on xjx_j is ri(j)=xi−Cov⁡(xi,xj)Var⁡(xj)xjr_i^{(j)} = x_i - \frac{\operatorname{Cov}(x_i, x_j)}{\operatorname{Var}(x_j)}x_j, the error of the least-squares fit. Hyvärinen and Smith (2013) compare the two directions between standardized xix_i and xjx_j by the log-likelihood ratio

R(i,j)=H(xj)+H(ri(j))−H(xi)−H(rj(i)),R(i, j) = H(x_j) + H(r_i^{(j)}) - H(x_i) - H(r_j^{(i)}),

where HH is the differential entropy of a standardized variable, with rr standardized too. R(i,j)>0R(i, j) > 0 favours xi→xjx_i \to x_j. The implementation uses their approximation H(u)≈1+log⁡2π2−k1(Elog⁡cosh⁡u−γ)2−k2(E ue−u2/2)2H(u) \approx \frac{1 + \log 2\pi}{2} - k_1(\mathrm{E}\log\cosh u - \gamma)^2 - k_2(\mathrm{E}\,u e^{-u^2/2})^2 with k1=79.047k_1 = 79.047, k2=7.4129k_2 = 7.4129 and γ=0.37457\gamma = 0.37457; the first term is the entropy of a standard Gaussian, the largest entropy at unit variance.

  1. DirectLiNGAM(X)
  2. 1U ← the variables of X, sorted by name; K ← the empty list
  3. 2while U has more than one variable do
  4. 3S(i) ← 0 for each i in U
  5. 4for each i in U do
  6. 5for each j in U after i do compute R(i, j)
  7. 6S(i) ← S(i) + min(0, R(i, j))^2; S(j) ← S(j) + min(0, -R(i, j))^2
  8. 7m ← the i in U with the smallest S(i), ties by name; append m to K
  9. 8for each j in U other than m do x_j ← the standardized residual of x_j on x_m
  10. 9remove m from U
  11. 10append the last variable of U to K
  12. 11B ← least squares of each x_j on the variables before j in K, with the original data; set every |b| < τ to 0
  13. 12return K and B

The score S(i)S(i) is the total evidence against xix_i being a cause of the others: it grows only when some pair favours the direction into xix_i. An exogenous variable should have a score near 0. Line L8 removes the influence of the chosen variable, and the residuals follow a LiNGAM model with the same weights on the remaining variables, so the loop can repeat. The implementation uses τ=0.1\tau = 0.1. The original DirectLiNGAM measures the dependence between xix_i and its residuals with a kernel independence measure instead of RR; the structure of the loop is the same.

Example

Take A→BA \to B, A→CA \to C, B→DB \to D, C→DC \to D, D→ED \to E with B=0.8A+eBB = 0.8A + e_B, C=0.7A+eCC = 0.7A + e_C, D=0.6B+0.6C+eDD = 0.6B + 0.6C + e_D, E=0.9D+eEE = 0.9D + e_E, and errors uniform on [−3,3][-\sqrt3, \sqrt3], so of unit variance. The implementation draws m=1000m = 1000 samples with seed 1 and gives the columns in the order E,C,A,D,BE, C, A, D, B, so the input order tells nothing.

In round 1, all four ratios of AA are positive: R(A,B)=0.103R(A, B) = 0.103, R(A,C)=0.0935R(A, C) = 0.0935, R(A,D)=0.045R(A, D) = 0.045, R(A,E)=0.035R(A, E) = 0.035. So S(A)=0S(A) = 0, while every other variable loses at least one pair, for example S(B)=0.0106S(B) = 0.0106 and S(D)=0.0023S(D) = 0.0023. DirectLiNGAM takes AA and replaces B,C,D,EB, C, D, E by their residuals on AA.

round scores chosen
1 AA: 0, BB: 0.0106, CC: 0.0088, DD: 0.0023, EE: 0.0032 AA
2 BB, CC: both below 0.00001, DD: 0.0051, EE: 0.0043 CC
3 BB: below 0.00001, DD: 0.0071, EE: 0.0042 BB
4 DD: below 0.00001, EE: 0.0076 DD

The order is A,C,B,D,EA, C, B, D, E. After round 1, BB and CC are both exogenous in the residual model, so the order of CC and BB is free, and both orders are causal orders. Line L11 gives the weights A→BA \to B: 0.83, A→CA \to C: 0.71, B→DB \to D: 0.61, C→DC \to D: 0.63, D→ED \to E: 0.91, and sets the five other coefficients, all below 0.1 in size, to 0. This is the true graph with all five edges oriented. On the same data, PC or GES could orient only B→D←CB \to D \leftarrow C and D→ED \to E.

Why the direction shows. Take x=e1x = e_1 and y=x+e2y = x + e_2, where e1e_1 and e2e_2 are independent and each is −1-1 or 11 with probability 1/21/2. The forward residual y−x=e2y - x = e_2 is independent of xx. The backward regression of xx on yy has slope 1/21/2, and its residual r=(e1−e2)/2r = (e_1 - e_2)/2 is uncorrelated with yy. But r=0r = 0 and y=0y = 0 never happen together, while each has probability 1/21/2, so rr and yy are dependent. The tests check this with exact fractions.

Why Gaussian errors fail. With Gaussian errors, uncorrelated means independent. Then every order of the variables gives a linear model with independent errors and the same covariance matrix, so all orders fit equally well. The tests check this exactly for all 6 orders of a model on three variables.

Correctness

The proof is in proofs/correctness.md. It is partial. It cites the Darmois-Skitovich theorem (Darmois 1953, Skitovich 1953): if two linear combinations of independent variables are independent, then every variable that appears in both is Gaussian. From it the proof shows:

  1. Identifiability. If x=Bx+e=B′x+e′x = Bx + e = B'x + e', both with acyclic graphs and independent errors, and at most one component of ee is Gaussian, then B′=BB' = B. The matrix M=(I−B′)(I−B)−1M = (I - B')(I - B)^{-1} maps ee to e′e'; Darmois-Skitovich makes it a scaled permutation, and acyclicity with the unit diagonal makes it the identity.
  2. Exogenous variables. An exogenous variable is independent of all its residuals, and a variable with a parent has a dependent residual: the one of its last parent in a causal order.
  3. Residual model. Regressing out an exogenous variable leaves a model with the same weights and errors on the other variables.
  4. DirectLiNGAM with an exact test. If line L7 chooses a variable that is independent of its residuals, the loop runs n−1n - 1 rounds, KK is a causal order, and line L11 without the threshold returns BB in the population.

Not proved: that the approximate score of line L6 picks an exogenous variable. Hyvärinen and Smith (2013) show that the exact likelihood ratio has the right sign for two variables in the population (cited). For the approximation and for finite samples the rates are measured, see Pitfalls.

Proof: A linear acyclic model with independent non-Gaussian errors is identified by the distribution of x, and DirectLiNGAM with an exact independence test returns a causal order and the weights; the Darmois-Skitovich theorem is citedpartial

What is proved and what is cited. This file proves that the weight matrix BB is identified (two such models with the same distribution of xx have the same BB), and that DirectLiNGAM finds a causal order and BB when it can decide exactly whether two variables are independent. It cites the Darmois-Skitovich theorem. It does not prove that the implementation's choice step, which compares approximate entropies instead of testing independence, picks an exogenous variable; Hyvärinen and Smith (2013) show this for the exact likelihood ratio of two variables, and the tests measure it for the approximation.

Setting. The model is x=Bx+ex = Bx + e on nn variables. BB is the weight matrix of a DAG: Bji≠0B_{ji} \ne 0 means the edge i→ji \to j, and the graph has no directed cycle, so some ordering of the variables (a causal order) makes BB strictly lower triangular. The errors e1,…,ene_1, \dots, e_n are independent, with mean 0 and finite positive variances. Then I−BI - B is invertible (it is unit triangular in a causal order), and x=Aex = Ae with A=(I−B)−1A = (I - B)^{-1}. The entry AjkA_{jk} is the total effect of eke_k on xjx_j; Ajj=1A_{jj} = 1, and Ajk=0A_{jk} = 0 unless kk is an ancestor of jj or k=jk = j.

Theorem (Darmois 1953, Skitovich 1953; cited). Let e1,…,ene_1, \dots, e_n be independent random variables and y1=∑kakeky_1 = \sum_k a_k e_k, y2=∑kckeky_2 = \sum_k c_k e_k. If y1y_1 and y2y_2 are independent, then every eke_k with akck≠0a_k c_k \ne 0 is Gaussian.

Theorem 1 (identifiability). Let x=Bx+e=B′x+e′x = Bx + e = B'x + e', where both BB and B′B' are weight matrices of DAGs, ee and e′e' both have independent components with finite positive variances, and at most one component of ee is Gaussian. Then B′=BB' = B and e′=ee' = e.

Proof. From x=(I−B)−1ex = (I - B)^{-1}e and e′=(I−B′)xe' = (I - B')x we get e′=Mee' = Me with M=(I−B′)(I−B)−1M = (I - B')(I - B)^{-1}, an invertible matrix. Take two rows r≠sr \ne s. The components er′=∑kMrkeke'_r = \sum_k M_{rk}e_k and es′=∑kMskeke'_s = \sum_k M_{sk}e_k are independent, so by Darmois-Skitovich MrkMsk=0M_{rk}M_{sk} = 0 for every kk with eke_k non-Gaussian. So each column kk of a non-Gaussian eke_k has at most one non-zero entry, and since MM is invertible, exactly one, in a row ρ(k)\rho(k). Two such columns cannot share a row: they would both be multiples of the same unit vector, and MM would be singular.

If all eke_k are non-Gaussian, ρ\rho is a bijection and M=PDM = PD for a permutation matrix PP and an invertible diagonal DD. If exactly one ek0e_{k_0} is Gaussian, the n−1n - 1 other columns fill n−1n - 1 distinct rows, and the remaining row r0r_0 has its only non-zero entry in column k0k_0. Suppose Mrk0≠0M_{r k_0} \ne 0 for some r≠r0r \ne r_0. Independent components with finite variances are uncorrelated, but Cov⁡(er′,er0′)=Mrk0Mr0k0Var⁡(ek0)≠0\operatorname{Cov}(e'_r, e'_{r_0}) = M_{rk_0}M_{r_0k_0}\operatorname{Var}(e_{k_0}) \ne 0, since the other terms vanish. This contradiction shows that column k0k_0 also has one non-zero entry, and again M=PDM = PD.

So every row ii of I−B′=PD(I−B)I - B' = PD(I - B) is a non-zero multiple did_i of a row σ(i)\sigma(i) of I−BI - B, for a permutation σ\sigma. The diagonal entry gives 1=(I−B′)ii=di(I−B)σ(i)i1 = (I - B')_{ii} = d_i(I - B)_{\sigma(i)i}, so (I−B)σ(i)i≠0(I - B)_{\sigma(i)i} \ne 0 for every ii. If σ(i)≠i\sigma(i) \ne i, this entry is −Bσ(i)i-B_{\sigma(i)i}, an edge i→σ(i)i \to \sigma(i). If σ\sigma were not the identity, it would have a cycle i,σ(i),σ2(i),…,ii, \sigma(i), \sigma^2(i), \dots, i of length at least 2, and these edges would form a directed cycle in the graph of BB. So σ\sigma is the identity, di=1d_i = 1 for all ii, I−B′=I−BI - B' = I - B, and e′=ee' = e. □\square

With two or more Gaussian errors the theorem fails: the tests show that every order of three Gaussian variables gives a linear model with independent errors and the same covariance.

For the rest of the file, every eke_k is non-Gaussian. For variables i≠ji \ne j, the residual of xix_i on xjx_j is ri(j)=xi−Cov⁡(xi,xj)Var⁡(xj)xjr_i^{(j)} = x_i - \frac{\operatorname{Cov}(x_i, x_j)}{\operatorname{Var}(x_j)}x_j. A variable is exogenous when it has no parent.

Lemma 2 (an exogenous variable is independent of its residuals). If xmx_m is exogenous, then xmx_m is independent of ri(m)r_i^{(m)} for every i≠mi \ne m.

Proof. xm=emx_m = e_m. Write xi=∑kAikekx_i = \sum_k A_{ik}e_k. Then Cov⁡(xi,xm)=AimVar⁡(em)\operatorname{Cov}(x_i, x_m) = A_{im}\operatorname{Var}(e_m), so ri(m)=xi−Aimem=∑k≠mAikekr_i^{(m)} = x_i - A_{im}e_m = \sum_{k \ne m}A_{ik}e_k, a function of errors other than eme_m, and so independent of eme_m. □\square

Lemma 3 (a variable with a parent has a dependent residual). If xjx_j has a parent, then xjx_j and ri(j)r_i^{(j)} are dependent for some i≠ji \ne j.

Proof. Fix a causal order and let pp be the parent of jj that comes last in it. The other parents of jj come before pp, so they are not descendants of pp, and epe_p does not appear in them. In xj=∑qBjqxq+ejx_j = \sum_q B_{jq}x_q + e_j the error epe_p appears only through BjpxpB_{jp}x_p, so Ajp=Bjp≠0A_{jp} = B_{jp} \ne 0. Take i=pi = p and c=Cov⁡(xp,xj)/Var⁡(xj)c = \operatorname{Cov}(x_p, x_j)/\operatorname{Var}(x_j), so rp(j)=xp−cxjr_p^{(j)} = x_p - cx_j. The variable xpx_p does not contain eje_j, because pp is not a descendant of jj. If c≠0c \ne 0, then eje_j has the coefficient 11 in xjx_j and −c-c in rp(j)r_p^{(j)}. If c=0c = 0, then rp(j)=xpr_p^{(j)} = x_p, and epe_p has the coefficient 11 in xpx_p and BjpB_{jp} in xjx_j. In both cases one non-Gaussian error has non-zero coefficients in both variables, so by Darmois-Skitovich they are dependent. □\square

Lemma 4 (removing an exogenous variable). Let xmx_m be exogenous and rj=rj(m)r_j = r_j^{(m)} for j≠mj \ne m. Then rj=∑q≠mBjqrq+ejr_j = \sum_{q \ne m}B_{jq}r_q + e_j. So the residuals follow the same kind of model on the other variables, with the same weights and errors.

Proof. By Lemma 2, rj=xj−Ajmxmr_j = x_j - A_{jm}x_m. The total effects satisfy Ajm=Bjm+∑q≠mBjqAqmA_{jm} = B_{jm} + \sum_{q \ne m}B_{jq}A_{qm}, because every directed path from mm to jj ends with one edge into jj (and Amm=1A_{mm} = 1). So

xj=∑q≠mBjq(rq+Aqmxm)+Bjmxm+ej=∑q≠mBjqrq+Ajmxm+ej,x_j = \sum_{q \ne m}B_{jq}(r_q + A_{qm}x_m) + B_{jm}x_m + e_j = \sum_{q \ne m}B_{jq}r_q + A_{jm}x_m + e_j,

and subtracting AjmxmA_{jm}x_m gives the claim. □\square

Theorem 5 (DirectLiNGAM with an exact test). Replace the choice of line L7 by: choose a variable mm in UU that is independent of all its residuals rj(m)r_j^{(m)}, j∈U∖{m}j \in U \setminus \{m\}. Then such an mm always exists, the loop ends after n−1n - 1 rounds, KK is a causal order, and the regressions of line L11 without the threshold return BB.

Proof. By induction on the rounds, the current variables follow a model of the theorem's kind on UU, with the weights of BB restricted to UU: this holds at the start, and Lemma 4 keeps it after line L8. A DAG has a node with no parent, so by Lemma 2 a valid choice exists, and by Lemma 3 every valid choice has no parent among the current variables. In the restricted model, mm has no parent in UU, so every edge of BB into mm starts at a variable that left UU earlier, and no edge goes from a later variable into mm. Each round removes one variable, so there are n−1n - 1 rounds, and KK is a causal order. In line L11, the regression of xjx_j on the variables before it is xj=∑qBjqxq+ejx_j = \sum_q B_{jq}x_q + e_j with eje_j independent of those variables, which are not descendants of jj. As the covariance matrix of the variables before jj is positive definite, the least-squares coefficients are unique and equal the BjqB_{jq}. □\square

What the implementation does instead. Line L7 of the implementation chooses the mm that minimizes ∑jmin⁡(0,R(m,j))2\sum_j \min(0, R(m, j))^2, where R(m,j)R(m, j) is the log-likelihood ratio of the models xm→xjx_m \to x_j and xj→xmx_j \to x_m, computed with an approximation of the differential entropy. Hyvärinen and Smith (2013) show that with exact entropies R(m,j)>0R(m, j) > 0 in the population when xm→xjx_m \to x_j is the true model of two variables (cited). The approximation has no such guarantee, and the threshold of line L11 drops small weights. The tests measure the result: with uniform errors the order was right in all 50 random models on five variables with 1000 samples.

Complexity

Round kk has n−k+1n - k + 1 variables and computes one ratio RR for each pair, and each ratio costs Θ(m)\Theta(m) for two regressions and four entropies. Summed over the rounds this is Θ(n3m)\Theta(n^3 m). Line L8 adds Θ(n2m)\Theta(n^2 m) in total. In line L11, the regression of the tt-th variable needs Θ(t2m)\Theta(t^2 m) for its covariances and Θ(t3)\Theta(t^3) to solve the system, so Θ(n3m+n4)\Theta(n^3 m + n^4) in total. The work does not depend on the data, so the best and worst cases agree. The standardized copies of the data take Θ(nm)\Theta(nm) space. A kernel independence measure, as in the original DirectLiNGAM, costs far more per pair than the entropy approximation.

Properties

  • Full orientation. The output is one DAG, not an equivalence class. This is possible only because the errors are not Gaussian.
  • Weights included. Line L11 gives the strength of each edge, so total effects follow from (I−B)−1(I - B)^{-1}.
  • Deterministic. Ties in line L7 are broken by name, and the result does not depend on the order of the input columns.
  • Consistent, not exact. The identifiability theorem holds for the population. On a finite sample the order can be wrong, and the threshold can drop weak edges.
  • No conditional independence tests. Unlike PC, it never tests conditional independence, and it needs no faithfulness assumption for the order.

Variants and improvements

  • ICA-LiNGAM. The first method (Shimizu et al. 2006) runs ICA, for example FastICA, to estimate W=I−BW = I - B up to the order and scale of its rows. It permutes the rows so that no diagonal entry is near 0, divides each row by its diagonal entry, sets B=I−WB = I - W, and permutes the variables to make BB as near to strictly lower triangular as possible. Comon (1994) showed that ICA identifies the mixing matrix up to permutation and scale when at most one source is Gaussian. ICA can stop at a local optimum and depends on its start; DirectLiNGAM avoids this.
  • Kernel measure. DirectLiNGAM as published measures independence with a kernel method, which is slower but uses no entropy approximation.
  • Pairwise measures. Hyvärinen and Smith (2013) give the likelihood ratio used here, and other approximations of it.
  • Pruning. Instead of a fixed threshold, use the adaptive lasso or tests of the coefficients along the order.
  • Extensions. Later work extends LiNGAM to hidden common causes, to time series, and to cyclic models, each with weaker identification results.

When to use it

Use LiNGAM when the relations are close to linear, all common causes are measured, and the errors are clearly not Gaussian, for example skewed, heavy-tailed or bounded. It gives a full DAG where PC or GES leave edges undirected. If the errors look Gaussian, or the data come from sums of many small effects (the central limit theorem makes such errors near Gaussian), use PC or GES and accept the equivalence class. If hidden common causes are likely, use the FCI algorithm or a LiNGAM variant made for them.

Pitfalls

  • Gaussian errors. With Gaussian errors the direction is not identified. On two variables X→YX \to Y with 1000 samples, the implementation found XX first in 24 of 50 runs, close to a coin flip, against 50 of 50 with uniform errors. On 50 random models with five variables, the order was a causal order in 3 of 50 runs with Gaussian errors, and in 50 of 50 with uniform errors.
  • Weak edges. The threshold drops small weights, and sampling noise can keep a spurious one. In the 50 uniform runs, all orders were right, but the set of edges was exactly right in 43. These rates are measured on the implementation, not proved.
  • Hidden common causes. A hidden cause of two variables makes their errors dependent, and the model fails. The method still returns a DAG, with no warning.
  • Non-linear relations. A non-linear effect leaves residuals that depend on the cause, which can point the arrow the wrong way.
  • Weak non-Gaussianity. The signal is in the higher moments. When the errors are nearly Gaussian, many more samples are needed, and the approximate entropy can rank the directions wrongly.
  • Measurement error. Noise added to a cause after it acts makes the cause look like an effect, so the order can reverse.

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.

lingam.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lingam/. The authors are listed in prov/YZF859.jsonl.
"""DirectLiNGAM: the causal order of a linear non-Gaussian acyclic model.

The model is x = B x + e, where B is the weight matrix of a DAG and the
components of e are independent and non-Gaussian. DirectLiNGAM (Shimizu et
al. 2011) finds an exogenous variable, regresses it out of the others, and
repeats. To find the exogenous variable this module uses the pairwise
likelihood ratio of Hyvarinen and Smith (2013) with their entropy
approximation, as many implementations do. After the order is known, each
variable is regressed on the earlier ones and small coefficients are set to 0.

Data are given as a dict: variable name -> list of floats (one per sample).
"""

import math
from typing import NamedTuple

K1, K2, GAMMA = 79.047, 7.4129, 0.37457


class LiNGAMResult(NamedTuple):
    order: list   # causal order, causes first
    b: dict       # (cause, effect) -> estimated weight, only kept weights


def mean(u):
    return sum(u) / len(u)


def standardize(u):
    m = mean(u)
    c = [x - m for x in u]
    s = math.sqrt(sum(x * x for x in c) / len(c))
    return [x / s for x in c]


def residual(xi, xj):
    """Residual of xi after least-squares regression on xj (both centred)."""
    b = sum(a * c for a, c in zip(xi, xj)) / sum(c * c for c in xj)
    return [a - b * c for a, c in zip(xi, xj)]


def entropy(u):
    """Approximate differential entropy of a standardized sample (Hyvarinen 1998
    maximum entropy approximation, constants as in Hyvarinen and Smith 2013)."""
    n = len(u)
    lc = sum(abs(x) + math.log1p(math.exp(-2 * abs(x))) - math.log(2) for x in u) / n  # log cosh
    ge = sum(x * math.exp(-x * x / 2) for x in u) / n
    return (1 + math.log(2 * math.pi)) / 2 - K1 * (lc - GAMMA) ** 2 - K2 * ge ** 2


def likelihood_ratio(xi, xj):
    """R(i, j): positive when the model xi -> xj fits better than xj -> xi."""
    ri_j = standardize(residual(xi, xj))
    rj_i = standardize(residual(xj, xi))
    return entropy(xj) + entropy(ri_j) - entropy(xi) - entropy(rj_i)


def causal_order(data):
    """The DirectLiNGAM search for a causal order."""
    x = {v: standardize(col) for v, col in data.items()}
    left = sorted(x)  # @line L1
    order = []
    while len(left) > 1:  # @line L2
        score = {i: 0.0 for i in left}  # @line L3
        for a in range(len(left)):  # @line L4
            for c in range(a + 1, len(left)):  # @line L5
                i, j = left[a], left[c]
                r = likelihood_ratio(x[i], x[j])
                score[i] += min(0.0, r) ** 2  # @line L6
                score[j] += min(0.0, -r) ** 2
        m = min(left, key=lambda v: (score[v], v))  # @line L7
        order.append(m)
        for j in left:
            if j != m:
                x[j] = standardize(residual(x[j], x[m]))  # @line L8
        left.remove(m)  # @line L9
    order.extend(left)  # @line L10
    return order


def solve(a, rhs):
    """Solve a small linear system by Gaussian elimination with pivoting."""
    k = len(rhs)
    m = [row[:] + [r] for row, r in zip(a, rhs)]
    for i in range(k):
        p = max(range(i, k), key=lambda r: abs(m[r][i]))
        m[i], m[p] = m[p], m[i]
        for r in range(i + 1, k):
            f = m[r][i] / m[i][i]
            for c in range(i, k + 1):
                m[r][c] -= f * m[i][c]
    out = [0.0] * k
    for i in reversed(range(k)):
        out[i] = (m[i][k] - sum(m[i][j] * out[j] for j in range(i + 1, k))) / m[i][i]
    return out


def fit_weights(data, order, threshold=0.1):
    """Least squares of each variable on the earlier ones; drop |b| < threshold."""
    cen = {v: [x - mean(col) for x in col] for v, col in data.items()}

    def dot(u, w):
        return sum(p * q for p, q in zip(u, w)) / len(u)

    b = {}
    for t, y in enumerate(order):
        preds = order[:t]
        if not preds:
            continue
        coef = solve([[dot(cen[p], cen[q]) for q in preds] for p in preds], [dot(cen[p], cen[y]) for p in preds])
        for p, c in zip(preds, coef):
            if abs(c) >= threshold:
                b[(p, y)] = c
    return b


def direct_lingam(data, threshold=0.1):
    order = causal_order(data)
    b = fit_weights(data, order, threshold)  # @line L11
    return LiNGAMResult(order, b)  # @line L12


def simulate(order, weights, n, rng, noise):
    """Samples of x = B x + e; weights maps (cause, effect) -> float, order is
    a causal order, noise(rng) draws one error with mean 0 and variance 1."""
    data = {v: [] for v in order}
    for _ in range(n):
        x = {}
        for v in order:
            x[v] = noise(rng) + sum(w * x[p] for (p, c), w in weights.items() if c == v)
            data[v].append(x[v])
    return data


def uniform_noise(rng):
    return rng.uniform(-math.sqrt(3), math.sqrt(3))


def gaussian_noise(rng):
    return rng.gauss(0.0, 1.0)


if __name__ == "__main__":
    import random
    rng = random.Random(1)
    w = {("A", "B"): 0.8, ("A", "C"): 0.7, ("B", "D"): 0.6, ("C", "D"): 0.6, ("D", "E"): 0.9}
    data = simulate(["A", "B", "C", "D", "E"], w, 1000, rng, uniform_noise)
    # Present the variables in a scrambled order to show the order is found from data.
    data = {v: data[v] for v in ["E", "C", "A", "D", "B"]}
    res = direct_lingam(data)
    print(res.order, {k: round(v, 2) for k, v in sorted(res.b.items())})
test_lingam.py 174 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lingam/. The authors are listed in prov/YZF859.jsonl.

import itertools
import random
from fractions import Fraction

from lingam import direct_lingam, gaussian_noise, simulate, uniform_noise

EX_ORDER = ["A", "B", "C", "D", "E"]
EX_WEIGHTS = {("A", "B"): 0.8, ("A", "C"): 0.7, ("B", "D"): 0.6, ("C", "D"): 0.6, ("D", "E"): 0.9}


def consistent(order, weights):
    pos = {v: k for k, v in enumerate(order)}
    return all(pos[a] < pos[b] for (a, b) in weights)


def random_model(rng, n, p):
    order = [chr(65 + i) for i in range(n)]
    rng.shuffle(order)
    w = {}
    for i, j in itertools.combinations(range(n), 2):
        if rng.random() < p:
            w[(order[i], order[j])] = rng.uniform(0.5, 1.5) * rng.choice((1, -1))
    return order, w


def test_worked_example():
    rng = random.Random(1)
    data = simulate(EX_ORDER, EX_WEIGHTS, 1000, rng, uniform_noise)
    data = {v: data[v] for v in ["E", "C", "A", "D", "B"]}
    res = direct_lingam(data)
    assert res.order == ["A", "C", "B", "D", "E"]
    assert set(res.b) == set(EX_WEIGHTS)
    assert all(abs(res.b[k] - w) < 0.05 for k, w in EX_WEIGHTS.items())


def test_two_point_noise_exact():
    # x = e1, y = x + e2 with e1, e2 independent and equal to -1 or 1.
    # Forward residual e2 is independent of x. The backward regression of x
    # on y has slope 1/2; its residual is uncorrelated with y but dependent.
    outcomes = [(e1, e2) for e1 in (-1, 1) for e2 in (-1, 1)]  # each with probability 1/4
    p = Fraction(1, 4)
    xs = [(e1, e1 + e2) for e1, e2 in outcomes]
    slope = sum(p * x * y for x, y in xs) / sum(p * y * y for x, y in xs)
    assert slope == Fraction(1, 2)
    pairs = [(x - slope * y, y) for x, y in xs]
    assert sum(p * r * y for r, y in pairs) == 0  # uncorrelated

    def prob(event):
        return sum(p for pr in pairs if event(pr))

    joint = prob(lambda t: t[0] == 0 and t[1] == 0)
    assert joint == 0 and prob(lambda t: t[0] == 0) * prob(lambda t: t[1] == 0) == Fraction(1, 4)
    # Forward: residual y - x = e2 and x = e1 factorize exactly.
    for a in (-1, 1):
        for b in (-1, 1):
            j = sum(p for e1, e2 in outcomes if e1 == a and e2 == b)
            assert j == Fraction(1, 2) * Fraction(1, 2)


def test_gaussian_every_order_fits_exactly():
    # For a Gaussian model, every order of the variables gives a linear model with
    # uncorrelated (so independent) errors and the same covariance.
    nodes = ["A", "B", "C"]
    w = {("A", "B"): Fraction(4, 5), ("A", "C"): Fraction(-1, 2), ("B", "C"): Fraction(3, 4)}
    cov = covariance(nodes, w, {v: Fraction(1) for v in nodes})
    for order in itertools.permutations(nodes):
        b, var = {}, {}
        for t, y in enumerate(order):
            preds = list(order[:t])
            coef = solve_exact([[cov[p][q] for q in preds] for p in preds], [cov[p][y] for p in preds])
            for p, c in zip(preds, coef):
                b[(p, y)] = c
            var[y] = cov[y][y] - sum(c * cov[p][y] for p, c in zip(preds, coef))
        assert covariance(list(order), b, var) == cov


def covariance(order, w, noise_var):
    cov = {u: {} for u in order}
    for i, v in enumerate(order):
        pas = [(p, x) for (p, c), x in w.items() if c == v]
        for u in order[:i]:
            cov[u][v] = cov[v][u] = sum((x * cov[p][u] for p, x in pas), Fraction(0))
        cov[v][v] = noise_var[v] + sum((x1 * x2 * cov[p1][p2] for p1, x1 in pas for p2, x2 in pas), Fraction(0))
    return cov


def solve_exact(a, rhs):
    k = len(rhs)
    m = [row[:] + [r] for row, r in zip(a, rhs)]
    for i in range(k):
        p = next(r for r in range(i, k) if m[r][i] != 0)
        m[i], m[p] = m[p], m[i]
        for r in range(i + 1, k):
            f = m[r][i] / m[i][i]
            for c in range(i, k + 1):
                m[r][c] -= f * m[i][c]
    out = [Fraction(0)] * k
    for i in reversed(range(k)):
        out[i] = (m[i][k] - sum(m[i][j] * out[j] for j in range(i + 1, k))) / m[i][i]
    return out


def test_residuals_of_a_source_follow_the_same_model():
    # Lemma: regress a source m out of every variable; the residuals satisfy
    # r_j = sum_{p != m} b_pj r_p + e_j. Checked exactly on coefficient vectors over e.
    rng = random.Random(2)
    for _ in range(30):
        order, wf = random_model(rng, 5, 0.6)
        w = {k: Fraction(round(v * 8), 8) or Fraction(1, 8) for k, v in wf.items()}
        coef = {}
        for v in order:
            vec = {v: Fraction(1)}
            for (p, c), x in w.items():
                if c == v:
                    for k, a in coef[p].items():
                        vec[k] = vec.get(k, 0) + x * a
            coef[v] = vec
        m = order[0]
        r = {}
        for j in order[1:]:
            cjm = coef[j].get(m, 0)  # Cov(x_j, x_m) / Var(x_m), unit noise variances
            r[j] = {k: a - cjm * coef[m].get(k, 0) for k, a in coef[j].items()}
            want = {j: Fraction(1)}
            for (p, c), x in w.items():
                if c == j and p != m:
                    for k, a in r[p].items():
                        want[k] = want.get(k, 0) + x * a
            assert {k: a for k, a in r[j].items() if a} == {k: a for k, a in want.items() if a}


def test_two_variables_uniform_noise():
    ok = 0
    for seed in range(50):
        rng = random.Random(seed)
        data = simulate(["X", "Y"], {("X", "Y"): 0.8}, 1000, rng, uniform_noise)
        ok += direct_lingam({"Y": data["Y"], "X": data["X"]}).order == ["X", "Y"]
    assert ok == 50


def test_two_variables_gaussian_noise():
    # With Gaussian noise the direction is not identified: about half right.
    ok = 0
    for seed in range(50):
        rng = random.Random(seed)
        data = simulate(["X", "Y"], {("X", "Y"): 0.8}, 1000, rng, gaussian_noise)
        ok += direct_lingam({"Y": data["Y"], "X": data["X"]}).order == ["X", "Y"]
    assert ok == 24  # measured: 24 of 50, close to a coin flip


def test_random_models_uniform_noise():
    order_ok = support_ok = 0
    for seed in range(50):
        rng = random.Random(seed)
        order, w = random_model(rng, 5, 0.5)
        data = simulate(order, w, 1000, rng, uniform_noise)
        res = direct_lingam({v: data[v] for v in sorted(data)})
        order_ok += consistent(res.order, w)
        support_ok += set(res.b) == set(w)
    assert order_ok == 50
    assert support_ok == 43


def test_random_models_gaussian_noise():
    order_ok = 0
    for seed in range(50):
        rng = random.Random(seed)
        order, w = random_model(rng, 5, 0.5)
        data = simulate(order, w, 1000, rng, gaussian_noise)
        res = direct_lingam({v: data[v] for v in sorted(data)})
        order_ok += consistent(res.order, w)
    assert order_ok == 3

History

Darmois (1953) and Skitovich (1953) proved, independently, that two independent linear combinations of independent variables can share only Gaussian variables. Comon (1994) used this to show that independent component analysis identifies its mixing matrix up to permutation and scale when the sources are not Gaussian. In 2006 Shimizu, Hoyer, Hyvärinen and Kerminen applied this to causal discovery: in a linear acyclic model with non-Gaussian errors, the triangular structure of I−BI - B fixes the permutation and scale, so the whole DAG is identified. Their ICA-LiNGAM found it with FastICA. Shimizu and co-authors gave DirectLiNGAM in 2011, which finds exogenous variables one at a time and needs no iterative ICA, and Hyvärinen and Smith (2013) gave the pairwise likelihood ratios that many implementations use.

References

  1. Shohei Shimizu, Patrik O. Hoyer, Aapo Hyvärinen and Antti Kerminen, A linear non-Gaussian acyclic model for causal discovery, Journal of Machine Learning Research 7, 2006, pp. 2003 to 2030, The whole paper (the model, its identifiability through independent component analysis, and the ICA-LiNGAM algorithm with its permutation and pruning steps)
  2. Shohei Shimizu, Takanori Inazumi, Yasuhiro Sogawa, Aapo Hyvärinen, Yoshinobu Kawahara, Takashi Washio, Patrik O. Hoyer and Kenneth Bollen, DirectLiNGAM: A direct method for learning a linear non-Gaussian structural equation model, Journal of Machine Learning Research 12, 2011, pp. 1225 to 1248, The whole paper (the lemmas on exogenous variables and residuals, and the DirectLiNGAM algorithm)
  3. Aapo Hyvärinen and Stephen M. Smith, Pairwise likelihood ratios for estimation of non-Gaussian structural equation models, Journal of Machine Learning Research 14, 2013, pp. 111 to 152, The whole paper (the likelihood ratio of two causal directions and its entropy approximation, used in line L5)
  4. Pierre Comon, Independent component analysis, a new concept?, Signal Processing 36(3), 1994, pp. 287 to 314, The whole paper (identifiability of the mixing matrix up to permutation and scale when at most one source is Gaussian)
  5. Georges Darmois, Analyse générale des liaisons stochastiques: étude particulière de l'analyse factorielle linéaire, Revue de l'Institut International de Statistique 21, 1953, pp. 2 to 8, The whole paper (the Darmois half of the Darmois-Skitovich theorem)
  6. V. P. Skitovich, On a property of the normal distribution, Doklady Akademii Nauk SSSR 89, 1953, pp. 217 to 219 (in Russian), The whole paper (the Skitovich half of the Darmois-Skitovich theorem)

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 correctness
  • 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