whyflow 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
whyflow/__init__.py ADDED
@@ -0,0 +1,16 @@
1
+ """whyflow: workflows where every step carries its code and the reason it exists."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ from whyflow.adjustment import check_adjustment
6
+ from whyflow.bayes import summarize_samples
7
+ from whyflow.checks import check_recovery
8
+ from whyflow.dag import DAG
9
+ from whyflow.workflow import Workflow
10
+
11
+ try:
12
+ __version__ = version("whyflow")
13
+ except PackageNotFoundError: # running from a source folder that wasn't installed
14
+ __version__ = "0.0.0"
15
+
16
+ __all__ = ["DAG", "Workflow", "check_adjustment", "check_recovery", "summarize_samples", "__version__"]
whyflow/adjustment.py ADDED
@@ -0,0 +1,222 @@
1
+ """Good and bad controls: read the causal diagram and say whether an adjustment set gives the effect you want.
2
+
3
+ The rule is the adjustment criterion (Shpitser, VanderWeele and Robins 2010; Perković et al. 2018), for one cause
4
+ and one outcome. A set of variables gives an unbiased total effect when:
5
+ 1. it contains nothing the cause affects on its way to the outcome (mediators), nor anything downstream of
6
+ them or of the outcome, and
7
+ 2. it closes every non-causal path between cause and outcome (confounding, or a collider it opened).
8
+ """
9
+
10
+ from itertools import combinations
11
+
12
+ from whyflow.dag import DAG
13
+
14
+ MAX_SEARCH = 12 # look for adjustment sets among at most this many candidate variables
15
+
16
+ ROLE_TEXT = {
17
+ "cause": "the cause",
18
+ "outcome": "the outcome",
19
+ "confounder": "confounder: links cause and outcome through a back door, without being part of the effect",
20
+ "mediator": "mediator: on the way from the cause to the outcome",
21
+ "outcome_descendant": "caused by the outcome",
22
+ "mediator_descendant": "caused by a mediator",
23
+ "outcome_cause": "only causes the outcome: safe to adjust for, often sharpens the estimate",
24
+ "cause_cause": "only causes the cause: safe, but adjusting for it makes the estimate noisier",
25
+ "cause_effect": "only caused by the cause: not needed",
26
+ "collider": "collider: caused by both sides of a path, adjusting for it opens that path",
27
+ "other": "not connected to this question",
28
+ }
29
+
30
+
31
+ def _arrow(dag: DAG, a: str, b: str) -> str:
32
+ return f"{a} → {b}" if a in dag.parents(b) else f"{a} ← {b}"
33
+
34
+
35
+ def path_text(dag: DAG, path: list[str]) -> str:
36
+ """A path written out with its arrows, e.g. 'age ← U → weight'."""
37
+ text = path[0]
38
+ for a, b in zip(path, path[1:], strict=False):
39
+ text += _arrow(dag, a, b)[len(a):]
40
+ return text
41
+
42
+
43
+ def is_causal(dag: DAG, path: list[str]) -> bool:
44
+ """True if every arrow on the path points forward, from the cause toward the outcome."""
45
+ return all(a in dag.parents(b) for a, b in zip(path, path[1:], strict=False))
46
+
47
+
48
+ def colliders(dag: DAG, path: list[str]) -> list[str]:
49
+ """Variables on the path where both arrows point in (→ C ←)."""
50
+ return [
51
+ path[i] for i in range(1, len(path) - 1)
52
+ if path[i - 1] in dag.parents(path[i]) and path[i + 1] in dag.parents(path[i])
53
+ ]
54
+
55
+
56
+ def is_open(dag: DAG, path: list[str], adjusted: set[str]) -> bool:
57
+ """Does association flow along this path once we adjust for `adjusted`?
58
+
59
+ A collider blocks the path unless it, or something it causes, is adjusted for.
60
+ Anything else on the path blocks it only if it is adjusted for.
61
+ """
62
+ for node in path[1:-1]:
63
+ if node in colliders(dag, path):
64
+ if node not in adjusted and not (dag.descendants(node) & adjusted):
65
+ return False
66
+ elif node in adjusted:
67
+ return False
68
+ return True
69
+
70
+
71
+ def roles(dag: DAG, cause: str, outcome: str) -> dict[str, str]:
72
+ """What each variable is, relative to this cause and outcome."""
73
+ after_cause = dag.descendants(cause)
74
+ before_outcome = dag.ancestors(outcome)
75
+ before_cause = dag.ancestors(cause)
76
+ mediators = after_cause & before_outcome
77
+ after_mediators = set().union(*(dag.descendants(m) for m in mediators)) if mediators else set()
78
+ all_paths = dag.paths(cause, outcome)
79
+ path_colliders = {c for path in all_paths for c in colliders(dag, path)}
80
+ # on a back-door path that is open when nothing is adjusted for: these create confounding
81
+ back_door = {
82
+ node for path in all_paths if not is_causal(dag, path) and is_open(dag, path, set())
83
+ for node in path[1:-1]
84
+ }
85
+
86
+ found = {}
87
+ for name in dag.variables:
88
+ if name == cause:
89
+ role = "cause"
90
+ elif name == outcome:
91
+ role = "outcome"
92
+ elif name in mediators:
93
+ role = "mediator"
94
+ elif name in dag.descendants(outcome):
95
+ role = "outcome_descendant"
96
+ elif name in after_mediators:
97
+ role = "mediator_descendant"
98
+ elif name in back_door:
99
+ role = "confounder"
100
+ elif name in before_outcome and name not in after_cause and name not in before_cause:
101
+ role = "outcome_cause"
102
+ elif name in before_cause:
103
+ role = "cause_cause"
104
+ elif name in after_cause:
105
+ role = "cause_effect"
106
+ elif name in path_colliders:
107
+ role = "collider"
108
+ else:
109
+ role = "other"
110
+ found[name] = role
111
+ return found
112
+
113
+
114
+ def _forbidden(dag: DAG, cause: str, outcome: str) -> set[str]:
115
+ """Adjusting for any of these removes part of the effect or biases it, whatever else you do."""
116
+ mediators = dag.descendants(cause) & dag.ancestors(outcome)
117
+ forbidden = {outcome} | dag.descendants(outcome)
118
+ for mediator in mediators:
119
+ forbidden |= {mediator} | dag.descendants(mediator)
120
+ return forbidden
121
+
122
+
123
+ def is_valid(dag: DAG, cause: str, outcome: str, adjusted: set[str]) -> bool:
124
+ if adjusted & _forbidden(dag, cause, outcome):
125
+ return False
126
+ return not any(
127
+ is_open(dag, path, adjusted) for path in dag.paths(cause, outcome) if not is_causal(dag, path)
128
+ )
129
+
130
+
131
+ def minimal_sets(dag: DAG, cause: str, outcome: str, limit: int = 5) -> list[list[str]]:
132
+ """The smallest sets of measured variables that remove the bias (none if an unmeasured variable is in the way)."""
133
+ forbidden = _forbidden(dag, cause, outcome)
134
+ candidates = sorted(
135
+ name for name, var in dag.variables.items()
136
+ if var.observed and name not in forbidden and name != cause
137
+ and name in (dag.ancestors(cause) | dag.ancestors(outcome)) # only causes of either can close a path
138
+ )[:MAX_SEARCH]
139
+ found: list[set[str]] = []
140
+ for size in range(len(candidates) + 1):
141
+ for subset in combinations(candidates, size):
142
+ chosen = set(subset)
143
+ if any(smaller <= chosen for smaller in found):
144
+ continue # a smaller set inside this one already works
145
+ if is_valid(dag, cause, outcome, chosen):
146
+ found.append(chosen)
147
+ if len(found) == limit:
148
+ return [sorted(s) for s in found]
149
+ return [sorted(s) for s in found]
150
+
151
+
152
+ def check_adjustment(dag: DAG, cause: str, outcome: str, adjusts_for: list[str]) -> dict:
153
+ """Is adjusting for `adjusts_for` the right way to get the total effect of cause on outcome?"""
154
+ unknown = sorted(set(adjusts_for) - set(dag.variables))
155
+ if unknown:
156
+ raise ValueError(f"The estimator adjusts for {unknown}, which aren't in the causal diagram.")
157
+ adjusted = set(adjusts_for)
158
+ role_of = roles(dag, cause, outcome)
159
+ problems = []
160
+ flagged = adjusted & _forbidden(dag, cause, outcome) # already explained, don't repeat for their paths
161
+ bad = set(flagged) | {n for n in adjusted if n == cause or not dag.variables[n].observed}
162
+
163
+ for name in sorted(adjusted):
164
+ role = role_of[name]
165
+ if name == cause:
166
+ problems.append(f"{name} is the cause itself; leave it out of the adjustment list.")
167
+ elif role == "mediator":
168
+ problems.append(
169
+ f"{name} is a mediator: part of {cause}'s effect on {outcome} flows through it. "
170
+ f"Adjusting for it removes that part, so you'd get less than the total effect."
171
+ )
172
+ elif role in ("outcome_descendant", "mediator_descendant"):
173
+ problems.append(
174
+ f"{name} is {ROLE_TEXT[role]}. Adjusting for something downstream like this biases the estimate."
175
+ )
176
+ if not dag.variables[name].observed:
177
+ problems.append(f"{name} is not measured, so it can't be adjusted for: it won't be in the data.")
178
+
179
+ causal, open_paths, blocked = [], [], []
180
+ for path in dag.paths(cause, outcome):
181
+ if is_causal(dag, path):
182
+ causal.append(path)
183
+ elif is_open(dag, path, adjusted):
184
+ open_paths.append(path)
185
+ opened = [c for c in colliders(dag, path) if c in adjusted or dag.descendants(c) & adjusted]
186
+ if opened and all(c in flagged for c in opened):
187
+ pass
188
+ elif opened:
189
+ culprits = sorted(n for n in adjusted if n in opened or any(n in dag.descendants(c) for c in opened))
190
+ bad |= set(culprits)
191
+ problems.append(
192
+ f"Adjusting for {' and '.join(culprits)} opens the path {path_text(dag, path)}: "
193
+ f"{' and '.join(opened)} is a collider there, so its causes start to look linked even if "
194
+ "they aren't."
195
+ )
196
+ else:
197
+ closers = [n for n in path[1:-1] if dag.variables[n].observed]
198
+ fix = f" Adjusting for {' or '.join(closers)} would close it." if closers else (
199
+ " Nothing measured on it can close it."
200
+ )
201
+ problems.append(
202
+ f"The path {path_text(dag, path)} is still open: it mixes a non-causal link into the estimate."
203
+ + fix
204
+ )
205
+ else:
206
+ blocked.append(path)
207
+
208
+ suggestions = minimal_sets(dag, cause, outcome)
209
+ return {
210
+ "passed": not problems,
211
+ "cause": cause,
212
+ "outcome": outcome,
213
+ "adjusts_for": sorted(adjusted),
214
+ "problems": problems,
215
+ "bad_adjustments": sorted(bad),
216
+ "suggested_sets": suggestions,
217
+ "roles": {name: role for name, role in role_of.items()},
218
+ "causal_paths": causal,
219
+ "open_paths": open_paths,
220
+ "blocked_paths": blocked,
221
+ "dag": dag, # kept for drawing the diagram in the report
222
+ }
whyflow/bayes.py ADDED
@@ -0,0 +1,32 @@
1
+ """Bayesian estimators: turn posterior samples into an estimate and an interval.
2
+
3
+ whyflow doesn't need any Bayesian library itself. Fit your model with whatever you like
4
+ (PyMC, NumPyro, Stan...), then pass the posterior samples of the effect you care about
5
+ to summarize_samples(), and return its result from your estimator.
6
+ """
7
+
8
+ import numpy as np
9
+
10
+ DEFAULT_PROB = 0.89 # McElreath's habit: 89% intervals, a reminder that 95% isn't magic
11
+
12
+
13
+ def summarize_samples(samples, prob: float = DEFAULT_PROB) -> dict:
14
+ """Posterior samples -> {'estimate', 'low', 'high', 'interval'}.
15
+
16
+ The estimate is the posterior mean; low and high bound the central `prob` share of the samples
17
+ (a percentile interval). Works with lists, numpy arrays and PyMC/ArviZ posteriors (chains x draws).
18
+ """
19
+ if not 0 < prob < 1:
20
+ raise ValueError(f"prob must be between 0 and 1, not {prob}")
21
+ values = np.asarray(samples, dtype=float).ravel()
22
+ if values.size == 0:
23
+ raise ValueError("No samples to summarize.")
24
+ tail = (1 - prob) / 2
25
+ low, high = np.quantile(values, [tail, 1 - tail])
26
+ return {
27
+ "estimate": float(values.mean()),
28
+ "low": float(low),
29
+ "high": float(high),
30
+ "interval": f"{prob:.0%} posterior interval",
31
+ "prob": prob,
32
+ }
whyflow/charts.py ADDED
@@ -0,0 +1,148 @@
1
+ """Small SVG charts for the report, drawn directly so the report needs no plotting library."""
2
+
3
+ import math
4
+
5
+ GREEN = "#16a34a"
6
+ RED = "#dc2626"
7
+ ORANGE = "#ea580c"
8
+ BAR = "#94a3b8"
9
+ TEXT = "#374151"
10
+ FONT = "font-family='system-ui, sans-serif' font-size='12'"
11
+ MARGIN = 28 # room at the sides for the axis numbers
12
+
13
+
14
+ def _domain(values: list[float], truth: float) -> tuple[float, float]:
15
+ low, high = min(*values, truth), max(*values, truth)
16
+ pad = (high - low) * 0.06 or 1.0
17
+ return low - pad, high + pad
18
+
19
+
20
+ def _ticks(low: float, high: float, count: int = 5) -> list[float]:
21
+ step = (high - low) / (count - 1)
22
+ return [low + i * step for i in range(count)]
23
+
24
+
25
+ def _label(value: float) -> str:
26
+ return f"{value:.3g}" if abs(value) >= 1 else f"{value:.2g}"
27
+
28
+
29
+ def _axis(scale, low: float, high: float, y: float, width: float) -> str:
30
+ parts = [f"<line x1='{MARGIN}' y1='{y}' x2='{width - MARGIN}' y2='{y}' stroke='#d1d5db'/>"]
31
+ for tick in _ticks(low, high):
32
+ x = scale(tick)
33
+ parts.append(f"<line x1='{x:.1f}' y1='{y}' x2='{x:.1f}' y2='{y + 4}' stroke='#9ca3af'/>")
34
+ parts.append(f"<text x='{x:.1f}' y='{y + 17}' text-anchor='middle' fill='{TEXT}' {FONT}>{_label(tick)}</text>")
35
+ return "".join(parts)
36
+
37
+
38
+ def estimate_histogram(estimates: list[float], truth: float, width: int = 640, height: int = 190) -> str:
39
+ """Where the estimates landed across all simulations, with the true value and their average marked."""
40
+ low, high = _domain(estimates, truth)
41
+ plot_height = height - 50
42
+
43
+ def scale(value: float) -> float:
44
+ return MARGIN + (value - low) / (high - low) * (width - 2 * MARGIN)
45
+
46
+ bins = 24
47
+ counts = [0] * bins
48
+ for value in estimates:
49
+ index = min(int((value - low) / (high - low) * bins), bins - 1)
50
+ counts[index] += 1
51
+ tallest = max(counts) or 1
52
+ bar_width = (width - 2 * MARGIN) / bins
53
+
54
+ parts = [f"<svg viewBox='0 -18 {width} {height + 18}' width='100%' role='img' xmlns='http://www.w3.org/2000/svg'>"]
55
+ for index, count in enumerate(counts):
56
+ bar_height = count / tallest * (plot_height - 10)
57
+ x = MARGIN + index * bar_width
58
+ parts.append(
59
+ f"<rect x='{x + 1:.1f}' y='{plot_height - bar_height:.1f}' width='{bar_width - 2:.1f}' "
60
+ f"height='{bar_height:.1f}' fill='{BAR}' rx='2'/>"
61
+ )
62
+ mean = sum(estimates) / len(estimates)
63
+ for value, color, dash in ((truth, GREEN, ""), (mean, ORANGE, "stroke-dasharray='5 4'")):
64
+ x = scale(value)
65
+ parts.append(
66
+ f"<line x1='{x:.1f}' y1='0' x2='{x:.1f}' y2='{plot_height}' stroke='{color}' stroke-width='2' {dash}/>"
67
+ )
68
+ # a legend instead of labels on the lines, which collide when the estimator is good (average ≈ truth)
69
+ parts.append(f"<line x1='{MARGIN}' y1='-10' x2='{MARGIN + 18}' y2='-10' stroke='{GREEN}' stroke-width='2'/>")
70
+ parts.append(f"<text x='{MARGIN + 24}' y='-6' fill='{TEXT}' {FONT}>true value {_label(truth)}</text>")
71
+ parts.append(
72
+ f"<line x1='{MARGIN + 160}' y1='-10' x2='{MARGIN + 178}' y2='-10' stroke='{ORANGE}' stroke-width='2' "
73
+ "stroke-dasharray='5 4'/>"
74
+ )
75
+ parts.append(f"<text x='{MARGIN + 184}' y='-6' fill='{TEXT}' {FONT}>average estimate {_label(mean)}</text>")
76
+ parts.append(_axis(scale, low, high, plot_height, width))
77
+ parts.append("</svg>")
78
+ return "".join(parts)
79
+
80
+
81
+ def interval_strip(
82
+ estimates: list[float], lows: list[float], highs: list[float], truth: float, width: int = 640, rows: int = 60
83
+ ) -> str:
84
+ """Each simulation's range as a line: green if it caught the true value, red if it missed."""
85
+ order = sorted(range(len(estimates)), key=lambda i: estimates[i])
86
+ if len(order) > rows: # spread the shown rows evenly across all simulations
87
+ order = [order[math.floor(i * len(order) / rows)] for i in range(rows)]
88
+ low, high = _domain(lows + highs, truth)
89
+ row_height = 5
90
+ plot_height = len(order) * row_height + 6
91
+
92
+ def scale(value: float) -> float:
93
+ return MARGIN + (value - low) / (high - low) * (width - 2 * MARGIN)
94
+
95
+ parts = [f"<svg viewBox='0 0 {width} {plot_height + 26}' width='100%' role='img' xmlns='http://www.w3.org/2000/svg'>"]
96
+ for row, i in enumerate(order):
97
+ y = 3 + row * row_height + row_height / 2
98
+ color = GREEN if lows[i] <= truth <= highs[i] else RED
99
+ parts.append(
100
+ f"<line x1='{scale(lows[i]):.1f}' y1='{y:.1f}' x2='{scale(highs[i]):.1f}' y2='{y:.1f}' "
101
+ f"stroke='{color}' stroke-width='2' stroke-linecap='round'/>"
102
+ )
103
+ parts.append(f"<circle cx='{scale(estimates[i]):.1f}' cy='{y:.1f}' r='1.6' fill='{TEXT}'/>")
104
+ x = scale(truth)
105
+ parts.append(f"<line x1='{x:.1f}' y1='0' x2='{x:.1f}' y2='{plot_height}' stroke='{TEXT}' stroke-width='1.5'/>")
106
+ parts.append(_axis(scale, low, high, plot_height, width))
107
+ parts.append("</svg>")
108
+ return "".join(parts)
109
+
110
+
111
+ def sensitivity_chart(sweep: list[dict], truth: float, tipping: float | None, chart_id: str,
112
+ width: int = 640, height: int = 240) -> str:
113
+ """Estimate against hidden-confounder strength: the average range as a band, the truth as a line."""
114
+ xs = [row["strength"] for row in sweep]
115
+ values = [row["mean_low"] for row in sweep] + [row["mean_high"] for row in sweep] + [truth]
116
+ low, high = _domain(values, truth)
117
+ x_low, x_high = min(xs), max(xs) if max(xs) > min(xs) else min(xs) + 1
118
+ top, bottom = 22, height - 34
119
+
120
+ def sx(value: float) -> float:
121
+ return MARGIN + 18 + (value - x_low) / (x_high - x_low) * (width - 2 * MARGIN - 18)
122
+
123
+ def sy(value: float) -> float:
124
+ return bottom - (value - low) / (high - low) * (bottom - top)
125
+
126
+ band = " ".join(f"{sx(r['strength']):.1f},{sy(r['mean_high']):.1f}" for r in sweep)
127
+ band += " " + " ".join(f"{sx(r['strength']):.1f},{sy(r['mean_low']):.1f}" for r in reversed(sweep))
128
+ line = " ".join(f"{sx(r['strength']):.1f},{sy(r['mean_estimate']):.1f}" for r in sweep)
129
+ parts = [f"<svg id='{chart_id}' viewBox='0 0 {width} {height}' width='100%' role='img' xmlns='http://www.w3.org/2000/svg'>"]
130
+ parts.append(f"<polygon points='{band}' fill='{ORANGE}' fill-opacity='0.15'/>")
131
+ parts.append(f"<line x1='{MARGIN + 18}' y1='{sy(truth):.1f}' x2='{width - MARGIN}' y2='{sy(truth):.1f}' stroke='{GREEN}' stroke-width='2'/>")
132
+ parts.append(f"<text x='{width - MARGIN}' y='{sy(truth) - 6:.1f}' text-anchor='end' fill='{GREEN}' {FONT}>true value {_label(truth)}</text>")
133
+ if tipping is not None:
134
+ x = sx(tipping)
135
+ parts.append(f"<line x1='{x:.1f}' y1='{top - 8}' x2='{x:.1f}' y2='{bottom}' stroke='{RED}' stroke-width='1.5' stroke-dasharray='5 4'/>")
136
+ parts.append(f"<text x='{x + 5:.1f}' y='{top}' fill='{RED}' {FONT}>tipping point {_label(tipping)}</text>")
137
+ parts.append(f"<polyline points='{line}' fill='none' stroke='{ORANGE}' stroke-width='2.5'/>")
138
+ for i, r in enumerate(sweep):
139
+ parts.append(f"<circle class='pt' data-i='{i}' cx='{sx(r['strength']):.1f}' cy='{sy(r['mean_estimate']):.1f}' r='3.5' fill='{ORANGE}' stroke='#fff' stroke-width='1.5'/>")
140
+ # axes: strength along the bottom, estimate up the side
141
+ parts.append(f"<line x1='{MARGIN + 18}' y1='{bottom}' x2='{width - MARGIN}' y2='{bottom}' stroke='#d1d5db'/>")
142
+ for r in sweep:
143
+ parts.append(f"<text x='{sx(r['strength']):.1f}' y='{bottom + 16}' text-anchor='middle' fill='{TEXT}' {FONT}>{_label(r['strength'])}</text>")
144
+ parts.append(f"<text x='{width / 2:.0f}' y='{height - 2}' text-anchor='middle' fill='#6b7280' {FONT}>strength of the hidden confounder</text>")
145
+ for tick in _ticks(low, high, 4):
146
+ parts.append(f"<text x='{MARGIN + 12}' y='{sy(tick) + 4:.1f}' text-anchor='end' fill='{TEXT}' {FONT}>{_label(tick)}</text>")
147
+ parts.append("</svg>")
148
+ return "".join(parts)
whyflow/checks.py ADDED
@@ -0,0 +1,92 @@
1
+ """Check that an estimator gets the right answer on data where the truth is known."""
2
+
3
+ import math
4
+ from collections.abc import Callable
5
+
6
+ import numpy as np
7
+
8
+ from whyflow.dag import DAG
9
+
10
+ REQUIRED = ("estimate", "low", "high")
11
+ DEFAULT_COVERAGE = 0.95 # what a regression's confidence interval aims for
12
+
13
+
14
+ def true_value_of(dag: DAG, target: dict) -> float:
15
+ """The answer the estimator should find: the estimand's own value, or the diagram's total effect."""
16
+ value = target.get("true_value")
17
+ if value is None:
18
+ value = dag.total_effect(target["cause"], target["outcome"])
19
+ return float(value)
20
+
21
+
22
+ def _fit_once(fit: Callable, data) -> dict:
23
+ found = fit(data)
24
+ missing = set(REQUIRED) - set(found)
25
+ if missing:
26
+ raise ValueError(f"The estimator must return estimate, low and high. Missing: {sorted(missing)}")
27
+ return found
28
+
29
+
30
+ def check_recovery(
31
+ dag: DAG,
32
+ target: dict,
33
+ fit: Callable,
34
+ n: int = 5000,
35
+ seed: int = 0,
36
+ repeats: int = 1,
37
+ expected_coverage: float | None = None,
38
+ ) -> dict:
39
+ """Simulate data from the generative model, run the estimator, and see if it finds the truth.
40
+
41
+ target says what we want: 'cause' and 'outcome' (and optionally 'true_value').
42
+ fit(data) is the estimator: it must return 'estimate', 'low' and 'high'.
43
+
44
+ With repeats=1, it's one simulation: passed means the truth is inside the range.
45
+ With more repeats, it's the reliable version: passed means the ranges caught the truth about as often
46
+ as they promise (their coverage), allowing for the luck of a finite number of simulations.
47
+ """
48
+ if repeats < 1:
49
+ raise ValueError("repeats must be at least 1")
50
+ truth = true_value_of(dag, target)
51
+
52
+ if repeats == 1:
53
+ found = _fit_once(fit, dag.simulate(n=n, seed=seed))
54
+ low, high = float(found["low"]), float(found["high"])
55
+ return {
56
+ "estimate": float(found["estimate"]),
57
+ "low": low,
58
+ "high": high,
59
+ "true_value": truth,
60
+ "passed": low <= truth <= high,
61
+ "simulated_rows": n,
62
+ # anything else the estimator reports (e.g. which kind of interval) is kept too
63
+ **{key: value for key, value in found.items() if key not in REQUIRED},
64
+ }
65
+
66
+ runs = [_fit_once(fit, dag.simulate(n=n, seed=seed + i)) for i in range(repeats)]
67
+ estimates = np.array([float(run["estimate"]) for run in runs])
68
+ lows = np.array([float(run["low"]) for run in runs])
69
+ highs = np.array([float(run["high"]) for run in runs])
70
+
71
+ expected = expected_coverage or runs[0].get("prob") or DEFAULT_COVERAGE
72
+ coverage = float(np.mean((lows <= truth) & (truth <= highs)))
73
+ # A perfect estimator still misses sometimes; allow three standard errors of that luck.
74
+ lowest_acceptable = expected - 3 * math.sqrt(expected * (1 - expected) / repeats)
75
+
76
+ return {
77
+ "true_value": truth,
78
+ "repeats": repeats,
79
+ "simulated_rows": n,
80
+ "coverage": coverage,
81
+ "expected_coverage": float(expected),
82
+ "lowest_acceptable_coverage": round(lowest_acceptable, 3),
83
+ "mean_estimate": float(estimates.mean()),
84
+ "bias": float(estimates.mean() - truth),
85
+ "rmse": float(math.sqrt(np.mean((estimates - truth) ** 2))),
86
+ "passed": coverage >= lowest_acceptable,
87
+ **{key: value for key, value in runs[0].items() if key not in (*REQUIRED, "prob")},
88
+ # every simulation's result, for the report's charts
89
+ "estimates": estimates.tolist(),
90
+ "lows": lows.tolist(),
91
+ "highs": highs.tolist(),
92
+ }
whyflow/dag.py ADDED
@@ -0,0 +1,122 @@
1
+ """Describe a causal diagram, simulate data from it, and know the true effects."""
2
+
3
+ from dataclasses import dataclass, field
4
+
5
+ import numpy as np
6
+ import pandas as pd
7
+
8
+
9
+ @dataclass
10
+ class Variable:
11
+ name: str
12
+ causes: dict[str, float] = field(default_factory=dict) # cause name -> effect size
13
+ noise: float = 1.0 # how much randomness this variable has on its own
14
+ intercept: float = 0.0 # its typical value when all causes are zero (for realistic units)
15
+ observed: bool = True # False for things that exist but you can't measure (they won't be in the data)
16
+
17
+
18
+ class DAG:
19
+ """A causal diagram. Add variables causes-first; that keeps the order right and rules out loops."""
20
+
21
+ def __init__(self):
22
+ self.variables: dict[str, Variable] = {}
23
+
24
+ def add(
25
+ self,
26
+ name: str,
27
+ causes: dict[str, float] | None = None,
28
+ noise: float = 1.0,
29
+ intercept: float = 0.0,
30
+ observed: bool = True,
31
+ ) -> "DAG":
32
+ causes = causes or {}
33
+ for cause in causes:
34
+ if cause not in self.variables:
35
+ raise ValueError(f"Add '{cause}' before '{name}': causes must exist first.")
36
+ self.variables[name] = Variable(name, causes, noise, intercept, observed)
37
+ return self
38
+
39
+ def parents(self, name: str) -> set[str]:
40
+ return set(self.variables[name].causes)
41
+
42
+ def children(self, name: str) -> set[str]:
43
+ return {var.name for var in self.variables.values() if name in var.causes}
44
+
45
+ def ancestors(self, name: str) -> set[str]:
46
+ """Everything that causes this variable, directly or through others."""
47
+ found: set[str] = set()
48
+ todo = list(self.parents(name))
49
+ while todo:
50
+ node = todo.pop()
51
+ if node not in found:
52
+ found.add(node)
53
+ todo.extend(self.parents(node))
54
+ return found
55
+
56
+ def descendants(self, name: str) -> set[str]:
57
+ """Everything this variable causes, directly or through others."""
58
+ found: set[str] = set()
59
+ todo = list(self.children(name))
60
+ while todo:
61
+ node = todo.pop()
62
+ if node not in found:
63
+ found.add(node)
64
+ todo.extend(self.children(node))
65
+ return found
66
+
67
+ def paths(self, start: str, end: str) -> list[list[str]]:
68
+ """Every route from start to end along the arrows, ignoring which way they point."""
69
+ neighbours = {name: self.parents(name) | self.children(name) for name in self.variables}
70
+ found = []
71
+
72
+ def walk(path: list[str]) -> None:
73
+ if path[-1] == end:
74
+ found.append(path)
75
+ return
76
+ for node in sorted(neighbours[path[-1]]):
77
+ if node not in path:
78
+ walk([*path, node])
79
+
80
+ walk([start])
81
+ return found
82
+
83
+ def with_hidden_confounder(self, cause: str, outcome: str, strength: float, name: str = "U") -> "DAG":
84
+ """A copy of this diagram with one extra unmeasured variable that pushes both cause and outcome.
85
+
86
+ `strength` is the size of both of its arrows, in the same units as the diagram's other arrows
87
+ (the hidden variable itself has a spread of 1). The true effect of cause on outcome doesn't change:
88
+ only how hard it is to see.
89
+ """
90
+ while name in self.variables:
91
+ name += "_"
92
+ copy = DAG().add(name, observed=False)
93
+ for var in self.variables.values():
94
+ causes = dict(var.causes)
95
+ if var.name in (cause, outcome):
96
+ causes[name] = strength
97
+ copy.add(var.name, causes, var.noise, var.intercept, var.observed)
98
+ return copy
99
+
100
+ def simulate(self, n: int = 1000, seed: int = 0, include_unobserved: bool = False) -> pd.DataFrame:
101
+ """Fake data where we know exactly how every variable was made.
102
+
103
+ Unobserved variables still shape the others, but are left out of the data, just like in real life.
104
+ """
105
+ rng = np.random.default_rng(seed)
106
+ data = {}
107
+ for var in self.variables.values():
108
+ value = var.intercept + rng.normal(0, var.noise, n)
109
+ for cause, effect in var.causes.items():
110
+ value = value + effect * data[cause]
111
+ data[var.name] = value
112
+ hidden = [] if include_unobserved else [v.name for v in self.variables.values() if not v.observed]
113
+ return pd.DataFrame(data).drop(columns=hidden)
114
+
115
+ def total_effect(self, cause: str, outcome: str) -> float:
116
+ """The true total effect: the direct arrow plus every path through other variables."""
117
+ if cause == outcome:
118
+ return 1.0
119
+ return sum(
120
+ effect * self.total_effect(cause, parent)
121
+ for parent, effect in self.variables[outcome].causes.items()
122
+ )