Download src/axiom_effect/graph.py from liminalplanes/axiom-effect: direct link, hf CLI and curl.
- Browser
- Download file 5 kB
-
https://huggingface.co/liminalplanes/axiom-effect/resolve/main/src/axiom_effect/graph.py
- Command line
-
hf download hf://liminalplanes/axiom-effect/src/axiom_effect/graph.py
-
curl -L -o graph.py https://huggingface.co/liminalplanes/axiom-effect/resolve/main/src/axiom_effect/graph.py
5 kB
| """The graph logic of causal effects: which variables a DAG says to adjust for. | |
| A[i, j] = 1 means i -> j throughout.""" | |
| import numpy as np | |
| def descendants(A, t): | |
| """The variables t reaches along directed edges of A (t itself excluded), sorted. | |
| descendants(A.T, t) gives the ancestors.""" | |
| seen, stack = set(), [t] | |
| while stack: | |
| for c in np.flatnonzero(A[stack.pop()]): | |
| if c not in seen: | |
| seen.add(int(c)) | |
| stack.append(c) | |
| return sorted(seen) | |
| def is_dag(A): | |
| """Whether A has no directed cycle (Kahn's algorithm: peel off variables without parents | |
| until none are left, or a cycle blocks the rest).""" | |
| A = (np.asarray(A) != 0).astype(np.int64) | |
| indegree, ready, seen = A.sum(0), [v for v in range(len(A)) if A[:, v].sum() == 0], 0 | |
| while ready: | |
| v = ready.pop() | |
| seen += 1 | |
| for c in np.flatnonzero(A[v]): | |
| indegree[c] -= 1 | |
| if indegree[c] == 0: | |
| ready.append(int(c)) | |
| return seen == len(A) | |
| def causal_nodes(A, t, y): | |
| """The variables on directed paths from t to y: y and the mediators (t excluded).""" | |
| ancestors_of_y = set(descendants(A.T, y)) | |
| return {v for v in descendants(A, t) if v == y or v in ancestors_of_y} | |
| def optimal_adjustment(A, t, y): | |
| """The optimal adjustment set O(t, y) of a DAG without hidden variables (Henckel, | |
| Perkovic & Maathuis, 2022): the valid set with the smallest asymptotic variance. It is | |
| pa(cn) minus forb, with cn = causal_nodes(A, t, y) and forb = t, cn and everything | |
| downstream of cn; in effect, the parents of the outcome and of the mediators, minus | |
| anything t causes.""" | |
| cn = causal_nodes(A, t, y) | |
| forb = {t} | cn | {w for v in cn for w in descendants(A, v)} | |
| return sorted({int(p) for v in cn for p in np.flatnonzero(A[:, v])} - forb) | |
| # Covariate roles: what the model is told about each covariate, from a graph. Four indicators | |
| # relative to the treatment t and the outcome y, which together separate every role that | |
| # matters for adjustment: a confounder is (1, 0, 1, 0), an instrument (1, 0, 0, 0), a | |
| # precision variable (0, 0, 1, 0), a mediator (0, 1, 1, 0), a collider or other descendant of | |
| # t (0, 1, 0, *), a descendant of y (*, 1, 0, 1). Adjusting for a descendant of t biases the | |
| # effect; the rest are safe, and the confounders are the ones that must be adjusted for. | |
| ROLE_NAMES = ("ancestor of T", "descendant of T", "affects Y not via T", "descendant of Y") | |
| N_ROLES = len(ROLE_NAMES) | |
| # Pair classes of a discover() result, in its order (axiom.inference.KINDS): none, i -> j, | |
| # j -> i, undirected, confounded. Read by position: axiom-effect does not import axiom. | |
| NONE, FWD, BWD, UND, CONF = range(5) | |
| def roles(A, t, y): | |
| """(d, N_ROLES) 0/1 role indicators of every variable of the DAG A (rows t and y are | |
| meaningless): ancestor of t, descendant of t, ancestor of y once t's outgoing edges are | |
| removed (an effect on y not through t), descendant of y.""" | |
| A = (np.asarray(A) != 0).astype(np.int64) | |
| R = np.zeros((len(A), N_ROLES)) | |
| cut = A.copy() | |
| cut[t] = 0 | |
| for col, members in enumerate((descendants(A.T, t), descendants(A, t), descendants(cut.T, y), descendants(A, y))): | |
| R[members, col] = 1 | |
| return R | |
| def _reaches(adj, a, b): | |
| """Whether b is reachable from a along adj's directed edges (adj: list of child sets).""" | |
| seen, stack = {a}, [a] | |
| while stack: | |
| v = stack.pop() | |
| if v == b: | |
| return True | |
| for c in adj[v]: | |
| if c not in seen: | |
| seen.add(c) | |
| stack.append(c) | |
| return False | |
| def sample_dag(probs, rng): | |
| """One DAG from a discover() result's pair probabilities, probs (d, d, 5) read from (i, j): | |
| each pair draws its class; i -> j and j -> i become that edge, undirected a random | |
| direction, none and confounded no edge. Drawn edges are added in random order, and one | |
| that would close a cycle is dropped.""" | |
| d = probs.shape[0] | |
| i, j = np.triu_indices(d, 1) | |
| p = np.clip(probs[i, j], 0, None) | |
| p = p / np.maximum(p.sum(-1, keepdims=True), 1e-12) | |
| k = (rng.random(len(i))[:, None] > np.cumsum(p, -1)).sum(-1) | |
| k = np.where(k == UND, np.where(rng.random(len(i)) < 0.5, FWD, BWD), k) | |
| edges = [(a, b) if c == FWD else (b, a) for a, b, c in zip(i, j, k) if c in (FWD, BWD)] | |
| adj, A = [set() for _ in range(d)], np.zeros((d, d), dtype=np.int64) | |
| for e in rng.permutation(len(edges)): | |
| a, b = edges[e] | |
| if not _reaches(adj, b, a): | |
| adj[a].add(b) | |
| A[a, b] = 1 | |
| return A | |
| def discovered_roles(probs, t, y, samples=64, seed=0): | |
| """(d, N_ROLES) role probabilities from a discover() result's pair probabilities: the | |
| roles averaged over `samples` DAGs drawn by sample_dag.""" | |
| rng = np.random.default_rng(seed) | |
| probs = np.asarray(probs, dtype=np.float64) | |
| return np.mean([roles(sample_dag(probs, rng), t, y) for _ in range(samples)], 0) | |