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 +16 -0
- whyflow/adjustment.py +222 -0
- whyflow/bayes.py +32 -0
- whyflow/charts.py +148 -0
- whyflow/checks.py +92 -0
- whyflow/dag.py +122 -0
- whyflow/report.py +365 -0
- whyflow/sensitivity.py +70 -0
- whyflow/workflow.py +240 -0
- whyflow-0.2.0.dist-info/METADATA +229 -0
- whyflow-0.2.0.dist-info/RECORD +13 -0
- whyflow-0.2.0.dist-info/WHEEL +4 -0
- whyflow-0.2.0.dist-info/licenses/LICENSE +21 -0
whyflow/report.py
ADDED
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
"""Turn a workflow into one HTML page: the diagram, and each step's reason, code and result."""
|
|
2
|
+
|
|
3
|
+
import html
|
|
4
|
+
import json
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
import pandas as pd
|
|
8
|
+
|
|
9
|
+
from whyflow.adjustment import ROLE_TEXT
|
|
10
|
+
from whyflow.charts import estimate_histogram, interval_strip, sensitivity_chart
|
|
11
|
+
from whyflow.dag import DAG
|
|
12
|
+
|
|
13
|
+
KIND_LABELS = {
|
|
14
|
+
"generative_model": "Generative model",
|
|
15
|
+
"estimand": "Estimand",
|
|
16
|
+
"estimator": "Estimator",
|
|
17
|
+
"test": "Test on simulated data",
|
|
18
|
+
"sensitivity": "Sensitivity analysis",
|
|
19
|
+
"data": "Data",
|
|
20
|
+
"analysis": "Real-data analysis",
|
|
21
|
+
}
|
|
22
|
+
KIND_COLORS = {
|
|
23
|
+
"generative_model": "#6366f1",
|
|
24
|
+
"estimand": "#0ea5e9",
|
|
25
|
+
"estimator": "#f59e0b",
|
|
26
|
+
"test": "#22c55e",
|
|
27
|
+
"sensitivity": "#0d9488",
|
|
28
|
+
"data": "#64748b",
|
|
29
|
+
"analysis": "#ef4444",
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
PAGE = """<!DOCTYPE html>
|
|
33
|
+
<html lang="en">
|
|
34
|
+
<head>
|
|
35
|
+
<meta charset="utf-8">
|
|
36
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
37
|
+
<title>__TITLE__</title>
|
|
38
|
+
<link rel="icon" href="data:image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCA2NCA2NCcgd2lkdGg9JzY0JyBoZWlnaHQ9JzY0Jz48cmVjdCB3aWR0aD0nNjQnIGhlaWdodD0nNjQnIHJ4PScxNCcgZmlsbD0nIzExMTgyNycvPjxsaW5lIHgxPScxOS41JyB5MT0nMzAuMycgeDI9JzMyLjknIHkyPScyMC40JyBzdHJva2U9JyM5Y2EzYWYnIHN0cm9rZS13aWR0aD0nMy4wJyBzdHJva2UtbGluZWNhcD0ncm91bmQnLz48cGF0aCBkPSdNMzcuMCwxNy40IEwzMy44LDI1LjAgTDI4LjgsMTguMiBaJyBmaWxsPScjOWNhM2FmJy8+PGxpbmUgeDE9JzIwLjInIHkxPSczOC40JyB4Mj0nMzMuMCcgeTI9JzQ0LjQnIHN0cm9rZT0nIzljYTNhZicgc3Ryb2tlLXdpZHRoPSczLjAnIHN0cm9rZS1saW5lY2FwPSdyb3VuZCcvPjxwYXRoIGQ9J00zNy41LDQ2LjUgTDI5LjQsNDcuMyBMMzMuMCwzOS43IFonIGZpbGw9JyM5Y2EzYWYnLz48bGluZSB4MT0nNDMuOCcgeTE9JzIxLjAnIHgyPSc0NS40JyB5Mj0nMzUuNicgc3Ryb2tlPScjOWNhM2FmJyBzdHJva2Utd2lkdGg9JzMuMCcgc3Ryb2tlLWxpbmVjYXA9J3JvdW5kJy8+PHBhdGggZD0nTTQ1LjksNDAuNiBMNDEuMCwzNC4wIEw0OS4zLDMzLjIgWicgZmlsbD0nIzljYTNhZicvPjxjaXJjbGUgY3g9JzEzLjAnIGN5PSczNS4wJyByPSc3LjAnIGZpbGw9JyM2MzY2ZjEnLz48Y2lyY2xlIGN4PSc0My4wJyBjeT0nMTMuMCcgcj0nNy4wJyBmaWxsPScjMGVhNWU5Jy8+PGNpcmNsZSBjeD0nNDcuMCcgY3k9JzUxLjAnIHI9JzEwLjAnIGZpbGw9JyMwZDk0ODgnLz48cGF0aCBkPSdNNDUuNjYxNTIzNDM3NSA1My4xODQ2Njc5Njg3NUg0Ny42MDI0NDE0MDYyNVY1Mi43MjMyNDIxODc1QzQ3LjYwMjQ0MTQwNjI1IDUxLjg3MzYzMjgxMjUgNDguMTA3ODEyNSA1MS41MDc0MjE4NzUgNDkuMDIzMzM5ODQzNzUgNTAuODk5NTExNzE4NzVDNDkuOTk3NDYwOTM3NSA1MC4yNDc2NTYyNSA1MC40OTU1MDc4MTI1IDQ5LjM1NDEwMTU2MjUgNTAuNDk1NTA3ODEyNSA0OC4yNTU0Njg3NUM1MC40OTU1MDc4MTI1IDQ2LjU0MTYwMTU2MjUgNDkuMDAxMzY3MTg3NSA0NS4zMjU3ODEyNSA0Ni44NTUzNzEwOTM3NSA0NS4zMjU3ODEyNUM0NC41ODQ4NjMyODEyNSA0NS4zMjU3ODEyNSA0My4wNjg3NSA0Ni43NzU5NzY1NjI1IDQzLjA2ODc1IDQ4LjgzNDA4MjAzMTI1SDQ1LjE0MTUwMzkwNjI1QzQ1LjE0MTUwMzkwNjI1IDQ3Ljc1NzQyMTg3NSA0NS43ODYwMzUxNTYyNSA0Ny4wOTA5MTc5Njg3NSA0Ni44MzMzOTg0Mzc1IDQ3LjA5MDkxNzk2ODc1QzQ3Ljc4NTU0Njg3NSA0Ny4wOTA5MTc5Njg3NSA0OC4zOTM0NTcwMzEyNSA0Ny42MjU1ODU5Mzc1IDQ4LjM5MzQ1NzAzMTI1IDQ4LjQ0NTg5ODQzNzVDNDguMzkzNDU3MDMxMjUgNDkuMDE3MTg3NSA0OC4wOTMxNjQwNjI1IDQ5LjU1OTE3OTY4NzUgNDcuMzQ2MDkzNzUgNTAuMDEzMjgxMjVDNDYuMjAzNTE1NjI1IDUwLjY3OTc4NTE1NjI1IDQ1LjY2MTUyMzQzNzUgNTEuMTE5MjM4MjgxMjUgNDUuNjYxNTIzNDM3NSA1Mi41NzY3NTc4MTI1Wk00Ni42NTc2MTcxODc1IDU2LjUzMTgzNTkzNzVDNDcuMzQ2MDkzNzUgNTYuNTMxODM1OTM3NSA0Ny45MDI3MzQzNzUgNTUuOTgyNTE5NTMxMjUgNDcuOTAyNzM0Mzc1IDU1LjI4NjcxODc1QzQ3LjkwMjczNDM3NSA1NC41OTgyNDIxODc1IDQ3LjM0NjA5Mzc1IDU0LjA0MTYwMTU2MjUgNDYuNjU3NjE3MTg3NSA1NC4wNDE2MDE1NjI1QzQ1Ljk2OTE0MDYyNSA1NC4wNDE2MDE1NjI1IDQ1LjQxMjUgNTQuNTk4MjQyMTg3NSA0NS40MTI1IDU1LjI4NjcxODc1QzQ1LjQxMjUgNTUuOTgyNTE5NTMxMjUgNDUuOTY5MTQwNjI1IDU2LjUzMTgzNTkzNzUgNDYuNjU3NjE3MTg3NSA1Ni41MzE4MzU5Mzc1WicgZmlsbD0nI2ZmZmZmZicvPjwvc3ZnPg==">
|
|
39
|
+
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.9.0/build/styles/github.min.css">
|
|
40
|
+
<style>
|
|
41
|
+
body { font-family: system-ui, sans-serif; max-width: 900px; margin: 2rem auto; padding: 0 1rem; color: #1f2937; }
|
|
42
|
+
h1 { margin-bottom: 0.2rem; }
|
|
43
|
+
.subtitle { color: #6b7280; margin-top: 0; }
|
|
44
|
+
.diagram { background: #f9fafb; border-radius: 12px; padding: 1rem; margin: 1.5rem 0; text-align: center; }
|
|
45
|
+
.card { border: 1px solid #e5e7eb; border-left: 6px solid; border-radius: 10px; padding: 1rem 1.25rem; margin: 1.25rem 0; }
|
|
46
|
+
.kind { font-size: 0.8rem; text-transform: uppercase; letter-spacing: 0.05em; color: #6b7280; }
|
|
47
|
+
.card h2 { margin: 0.2rem 0 0.6rem; font-family: ui-monospace, monospace; font-size: 1.15rem; }
|
|
48
|
+
.why { background: #fffbeb; border-radius: 8px; padding: 0.6rem 0.8rem; }
|
|
49
|
+
pre { overflow-x: auto; }
|
|
50
|
+
pre code { border-radius: 8px; font-size: 0.85rem; }
|
|
51
|
+
table { border-collapse: collapse; }
|
|
52
|
+
th, td { text-align: left; padding: 0.25rem 1rem 0.25rem 0; }
|
|
53
|
+
th { color: #6b7280; font-weight: 500; }
|
|
54
|
+
.muted { color: #9ca3af; }
|
|
55
|
+
.verdict { background: #f0fdf4; border-radius: 8px; padding: 0.6rem 0.8rem; }
|
|
56
|
+
.verdict.bad { background: #fef2f2; }
|
|
57
|
+
.chart { margin: 1rem 0; }
|
|
58
|
+
.chart h4 { margin: 0 0 0.3rem; font-weight: 500; color: #4b5563; }
|
|
59
|
+
.verdict ul { margin: 0.4rem 0 0; padding-left: 1.2rem; }
|
|
60
|
+
.legend { display: flex; flex-wrap: wrap; gap: 0.4rem 1.2rem; font-size: 0.85rem; color: #4b5563; margin: 0.4rem 0 1rem; }
|
|
61
|
+
.legend span::before { content: ""; display: inline-block; width: 0.9rem; height: 0.9rem; border-radius: 3px;
|
|
62
|
+
margin-right: 0.35rem; vertical-align: -0.15rem; background: var(--swatch); border: 2px solid var(--edge); }
|
|
63
|
+
.adjusts { color: #4b5563; }
|
|
64
|
+
.slider { width: 100%; accent-color: #0d9488; }
|
|
65
|
+
.readout { border-radius: 8px; padding: 0.5rem 0.8rem; margin: 0.4rem 0; }
|
|
66
|
+
.readout.ok { background: #f0fdf4; }
|
|
67
|
+
.readout.bad { background: #fef2f2; }
|
|
68
|
+
.warn { background: #fef3c7; color: #92400e; border-radius: 8px; padding: 0.6rem 0.8rem; }
|
|
69
|
+
.pass { background: #dcfce7; color: #166534; border-radius: 999px; padding: 0.1rem 0.6rem; margin-left: 0.4rem; }
|
|
70
|
+
.fail { background: #fee2e2; color: #991b1b; border-radius: 999px; padding: 0.1rem 0.6rem; margin-left: 0.4rem; }
|
|
71
|
+
</style>
|
|
72
|
+
</head>
|
|
73
|
+
<body>
|
|
74
|
+
<h1>__TITLE__</h1>
|
|
75
|
+
<p class="subtitle">Every step with its reason, its code and its result. Click a box to jump to its step.</p>
|
|
76
|
+
<div class="diagram"><pre class="mermaid">__DIAGRAM__</pre></div>
|
|
77
|
+
__CARDS__
|
|
78
|
+
<p class="muted">Made with whyflow.</p>
|
|
79
|
+
<script type="module">
|
|
80
|
+
import mermaid from "https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs";
|
|
81
|
+
mermaid.initialize({ startOnLoad: true, securityLevel: "loose", theme: "neutral" });
|
|
82
|
+
</script>
|
|
83
|
+
<script src="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.9.0/build/highlight.min.js"></script>
|
|
84
|
+
<script>hljs.highlightAll();</script>
|
|
85
|
+
</body>
|
|
86
|
+
</html>
|
|
87
|
+
"""
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _value(value) -> str:
|
|
91
|
+
"""One value, readable: yes/no for true/false, 3 decimals for numbers."""
|
|
92
|
+
if isinstance(value, (bool, np.bool_)):
|
|
93
|
+
return "yes" if value else "no"
|
|
94
|
+
if isinstance(value, str):
|
|
95
|
+
return html.escape(value)
|
|
96
|
+
if isinstance(value, (int, np.integer)):
|
|
97
|
+
return str(value)
|
|
98
|
+
try:
|
|
99
|
+
return f"{float(value):.3f}"
|
|
100
|
+
except (TypeError, ValueError):
|
|
101
|
+
return html.escape(str(value))
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _dag_mermaid(dag: DAG) -> str:
|
|
105
|
+
"""The causal diagram as Mermaid text: each arrow labeled with its effect size. Unmeasured variables are dashed."""
|
|
106
|
+
lines = ["graph LR"]
|
|
107
|
+
for var in dag.variables.values():
|
|
108
|
+
lines.append(f" {var.name}")
|
|
109
|
+
for cause, effect in var.causes.items():
|
|
110
|
+
lines.append(f" {cause} -->|{effect}| {var.name}")
|
|
111
|
+
lines += [f" style {var.name} stroke-dasharray:5 4" for var in dag.variables.values() if not var.observed]
|
|
112
|
+
return "\n".join(lines)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
ADJUSTMENT_NODE_STYLES = {
|
|
116
|
+
# class: (fill, border, text, legend label)
|
|
117
|
+
"focus": ("#1f2937", "#1f2937", "#ffffff", "cause and outcome"),
|
|
118
|
+
"good": ("#dcfce7", "#16a34a", "#14532d", "adjusted for: right"),
|
|
119
|
+
"bad": ("#fee2e2", "#dc2626", "#7f1d1d", "adjusted for: wrong"),
|
|
120
|
+
"suggest": ("#ffffff", "#16a34a", "#14532d", "adjust for this instead"),
|
|
121
|
+
"plain": ("#f3f4f6", "#9ca3af", "#374151", "other variables"),
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _edges(path: list[str]) -> set[frozenset]:
|
|
126
|
+
return {frozenset(pair) for pair in zip(path, path[1:], strict=False)}
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _adjustment_mermaid(result: dict) -> str:
|
|
130
|
+
"""The causal diagram, lit up: the effect's paths in green, open bias paths flowing in red."""
|
|
131
|
+
dag = result["dag"]
|
|
132
|
+
adjusted, bad = set(result["adjusts_for"]), set(result["bad_adjustments"])
|
|
133
|
+
suggestion = set(result["suggested_sets"][0]) if result["suggested_sets"] and not result["passed"] else set()
|
|
134
|
+
causal = set().union(*map(_edges, result["causal_paths"])) if result["causal_paths"] else set()
|
|
135
|
+
leaking = set().union(*map(_edges, result["open_paths"])) if result["open_paths"] else set()
|
|
136
|
+
|
|
137
|
+
lines, red, green = ["graph LR"], [], []
|
|
138
|
+
for var in dag.variables.values():
|
|
139
|
+
if var.name in (result["cause"], result["outcome"]):
|
|
140
|
+
kind = "focus"
|
|
141
|
+
elif var.name in bad:
|
|
142
|
+
kind = "bad"
|
|
143
|
+
elif var.name in adjusted:
|
|
144
|
+
kind = "good"
|
|
145
|
+
elif var.name in suggestion:
|
|
146
|
+
kind = "suggest"
|
|
147
|
+
else:
|
|
148
|
+
kind = "plain"
|
|
149
|
+
label = f"{var.name}<br/><small>adjusted</small>" if var.name in adjusted else var.name
|
|
150
|
+
lines.append(f' {var.name}["{label}"]:::{kind}')
|
|
151
|
+
index = 0
|
|
152
|
+
for var in dag.variables.values():
|
|
153
|
+
for cause, effect in var.causes.items():
|
|
154
|
+
edge = frozenset((cause, var.name))
|
|
155
|
+
lines.append(f" {cause} e{index}@-->|{effect}| {var.name}")
|
|
156
|
+
if edge in leaking:
|
|
157
|
+
lines.append(f" e{index}@{{ animate: true }}")
|
|
158
|
+
red.append(str(index))
|
|
159
|
+
elif edge in causal:
|
|
160
|
+
green.append(str(index))
|
|
161
|
+
index += 1
|
|
162
|
+
if red:
|
|
163
|
+
lines.append(f" linkStyle {','.join(red)} stroke:#dc2626,stroke-width:3px")
|
|
164
|
+
if green:
|
|
165
|
+
lines.append(f" linkStyle {','.join(green)} stroke:#16a34a,stroke-width:3px")
|
|
166
|
+
for kind, (fill, border, text, _) in ADJUSTMENT_NODE_STYLES.items():
|
|
167
|
+
width = "3px" if kind in ("good", "bad", "suggest") else "1px"
|
|
168
|
+
lines.append(f" classDef {kind} fill:{fill},stroke:{border},color:{text},stroke-width:{width}")
|
|
169
|
+
lines.append(" classDef suggest stroke-dasharray:6 3")
|
|
170
|
+
lines += [f" style {var.name} stroke-dasharray:5 4" for var in dag.variables.values() if not var.observed]
|
|
171
|
+
return "\n".join(lines)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _sets_text(sets: list[list[str]]) -> str:
|
|
175
|
+
return " or ".join("<strong>" + (", ".join(map(html.escape, s)) or "nothing") + "</strong>" for s in sets)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _passed(step) -> bool | None:
|
|
179
|
+
"""True/False for a test step that reports 'passed', otherwise None."""
|
|
180
|
+
if step.kind == "test" and isinstance(step.result, dict) and "passed" in step.result:
|
|
181
|
+
return bool(step.result["passed"])
|
|
182
|
+
return None
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _workflow_mermaid(workflow) -> str:
|
|
186
|
+
"""The workflow as Mermaid text: one box per step, clickable, colored by kind."""
|
|
187
|
+
lines = ["graph TD"]
|
|
188
|
+
for name, step in workflow.steps.items():
|
|
189
|
+
mark = {True: " ✅", False: " ❌", None: ""}[_passed(step)] + (" ⚠️" if step.warnings else "")
|
|
190
|
+
lines.append(f' {name}["{KIND_LABELS[step.kind]}{mark}<br/>{name}"]:::{step.kind}')
|
|
191
|
+
lines.append(f' click {name} href "#{name}"')
|
|
192
|
+
for need in step.needs:
|
|
193
|
+
lines.append(f" {need} --> {name}")
|
|
194
|
+
for kind, color in KIND_COLORS.items():
|
|
195
|
+
lines.append(f" classDef {kind} fill:{color},color:#fff,stroke:none")
|
|
196
|
+
return "\n".join(lines)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _result(step) -> str:
|
|
200
|
+
"""A step's result, shown in the most useful way for its type."""
|
|
201
|
+
if not step.done:
|
|
202
|
+
return "<p class='muted'>Not run yet.</p>"
|
|
203
|
+
result = step.result
|
|
204
|
+
if isinstance(result, DAG):
|
|
205
|
+
return f"<pre class='mermaid'>{html.escape(_dag_mermaid(result))}</pre>"
|
|
206
|
+
if isinstance(result, pd.DataFrame):
|
|
207
|
+
columns = ", ".join(html.escape(str(column)) for column in result.columns)
|
|
208
|
+
preview = result.head().to_html(index=False, border=0)
|
|
209
|
+
return f"<p>{len(result)} rows. Columns: {columns}</p>{preview}"
|
|
210
|
+
if callable(result):
|
|
211
|
+
return "<p class='muted'>A function, used by later steps.</p>"
|
|
212
|
+
if isinstance(result, dict) and "roles" in result and "dag" in result:
|
|
213
|
+
return _adjustment(result)
|
|
214
|
+
if isinstance(result, dict) and "sweep" in result:
|
|
215
|
+
return _sensitivity(step.name, result)
|
|
216
|
+
if isinstance(result, dict) and "estimates" in result:
|
|
217
|
+
return _repeated_recovery(result)
|
|
218
|
+
if isinstance(result, dict):
|
|
219
|
+
return _table(result)
|
|
220
|
+
if result is None:
|
|
221
|
+
return "<p class='muted'>No result.</p>"
|
|
222
|
+
return f"<pre>{html.escape(repr(result))[:2000]}</pre>"
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _table(result: dict) -> str:
|
|
226
|
+
rows = "".join(f"<tr><th>{html.escape(str(key))}</th><td>{_value(value)}</td></tr>" for key, value in result.items())
|
|
227
|
+
return f"<table>{rows}</table>"
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _repeated_recovery(result: dict) -> str:
|
|
231
|
+
"""A many-simulation recovery test: the verdict in words, the numbers, and two charts."""
|
|
232
|
+
caught = round(result["coverage"] * result["repeats"])
|
|
233
|
+
verdict = (
|
|
234
|
+
f"<p class='verdict{'' if result['passed'] else ' bad'}'>In <strong>{result['repeats']}</strong> simulations, the estimator's range caught the "
|
|
235
|
+
f"true value <strong>{caught}</strong> times ({result['coverage']:.0%}). It promises "
|
|
236
|
+
f"{result['expected_coverage']:.0%}; anything above {result['lowest_acceptable_coverage']:.0%} is within "
|
|
237
|
+
f"the luck of {result['repeats']} tries. On average it was off by <strong>{result['bias']:+.3g}</strong>.</p>"
|
|
238
|
+
)
|
|
239
|
+
numbers = _table({key: value for key, value in result.items() if key not in ("estimates", "lows", "highs")})
|
|
240
|
+
histogram = estimate_histogram(result["estimates"], result["true_value"])
|
|
241
|
+
strip = interval_strip(result["estimates"], result["lows"], result["highs"], result["true_value"])
|
|
242
|
+
return (
|
|
243
|
+
f"{verdict}<div class='chart'><h4>Where the estimates landed</h4>{histogram}</div>"
|
|
244
|
+
f"<div class='chart'><h4>Each simulation's range: green caught the true value, red missed it</h4>{strip}</div>"
|
|
245
|
+
f"<details><summary>All numbers</summary>{numbers}</details>"
|
|
246
|
+
)
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _adjustment(result: dict) -> str:
|
|
250
|
+
"""The good-and-bad-controls check: verdict, the lit-up diagram, and what each variable is."""
|
|
251
|
+
cause, outcome = html.escape(result["cause"]), html.escape(result["outcome"])
|
|
252
|
+
chosen = ", ".join(map(html.escape, result["adjusts_for"])) or "nothing"
|
|
253
|
+
if result["passed"]:
|
|
254
|
+
verdict = (
|
|
255
|
+
f"<p class='verdict'>Adjusting for <strong>{chosen}</strong> gives the total effect of {cause} on "
|
|
256
|
+
f"{outcome} without bias, if the causal diagram is right.</p>"
|
|
257
|
+
)
|
|
258
|
+
else:
|
|
259
|
+
problems = "".join(f"<li>{html.escape(problem)}</li>" for problem in result["problems"])
|
|
260
|
+
if result["suggested_sets"]:
|
|
261
|
+
fix = f"Adjust for {_sets_text(result['suggested_sets'])} instead."
|
|
262
|
+
else:
|
|
263
|
+
fix = (
|
|
264
|
+
"No set of measured variables removes this bias: something unmeasured is in the way. "
|
|
265
|
+
"You'd need to measure it, use a different design, or check how big the bias could be."
|
|
266
|
+
)
|
|
267
|
+
verdict = (
|
|
268
|
+
f"<div class='verdict bad'><p>Adjusting for <strong>{chosen}</strong> gives a biased answer:</p>"
|
|
269
|
+
f"<ul>{problems}</ul><p>{fix}</p></div>"
|
|
270
|
+
)
|
|
271
|
+
legend = "".join(
|
|
272
|
+
f"<span style='--swatch:{fill};--edge:{border}'>{label}</span>"
|
|
273
|
+
for fill, border, _, label in ADJUSTMENT_NODE_STYLES.values()
|
|
274
|
+
)
|
|
275
|
+
legend += (
|
|
276
|
+
"<span style='--swatch:#16a34a;--edge:#16a34a'>the effect you want</span>"
|
|
277
|
+
"<span style='--swatch:#dc2626;--edge:#dc2626'>bias leaking in (moving)</span>"
|
|
278
|
+
)
|
|
279
|
+
role_rows = "".join(
|
|
280
|
+
f"<tr><th>{html.escape(name)}</th><td>{html.escape(ROLE_TEXT[role])}</td></tr>"
|
|
281
|
+
for name, role in result["roles"].items()
|
|
282
|
+
if role not in ("cause", "outcome")
|
|
283
|
+
)
|
|
284
|
+
return (
|
|
285
|
+
f"{verdict}<pre class='mermaid'>{html.escape(_adjustment_mermaid(result))}</pre>"
|
|
286
|
+
f"<div class='legend'>{legend}</div>"
|
|
287
|
+
f"<h4>What each variable is, for this question</h4><table>{role_rows}</table>"
|
|
288
|
+
)
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _sensitivity(name: str, result: dict) -> str:
|
|
292
|
+
"""The hidden-confounder sweep: verdict, chart, and a slider to look at each strength."""
|
|
293
|
+
cause, outcome = html.escape(result["cause"]), html.escape(result["outcome"])
|
|
294
|
+
tipping = result["tipping_point"]
|
|
295
|
+
if tipping is None:
|
|
296
|
+
verdict = (
|
|
297
|
+
f"<p class='verdict'>Even a hidden confounder of strength {result['sweep'][-1]['strength']:g} "
|
|
298
|
+
f"(the strongest tried) doesn't stop the estimator's ranges from catching the truth.</p>"
|
|
299
|
+
)
|
|
300
|
+
else:
|
|
301
|
+
row = next(r for r in result["sweep"] if r["strength"] == tipping)
|
|
302
|
+
verdict = (
|
|
303
|
+
f"<p class='verdict bad'>A hidden confounder with arrows of <strong>{tipping:g}</strong> into both "
|
|
304
|
+
f"{cause} and {outcome} would be enough to break this: the estimate drifts to "
|
|
305
|
+
f"<strong>{row['mean_estimate']:.3g}</strong> (truth {result['true_value']:.3g}) and the ranges catch the truth "
|
|
306
|
+
f"only {row['coverage']:.0%} of the time. Ask yourself: could something that strong be missing from the diagram?</p>"
|
|
307
|
+
)
|
|
308
|
+
chart_id = f"sens-{name}"
|
|
309
|
+
chart = sensitivity_chart(result["sweep"], result["true_value"], tipping, chart_id)
|
|
310
|
+
rows = json.dumps([
|
|
311
|
+
{**r, "ok": r["coverage"] >= result["lowest_acceptable_coverage"]} for r in result["sweep"]
|
|
312
|
+
])
|
|
313
|
+
script = f"""<script>(() => {{
|
|
314
|
+
const rows = {rows}, truth = {result['true_value']!r};
|
|
315
|
+
const slider = document.getElementById("{chart_id}-slider"), out = document.getElementById("{chart_id}-out");
|
|
316
|
+
const dots = document.querySelectorAll("#{chart_id} .pt");
|
|
317
|
+
const fmt = (v) => String(Number(Number(v).toPrecision(3)));
|
|
318
|
+
function show(i) {{
|
|
319
|
+
const r = rows[i];
|
|
320
|
+
out.className = "readout " + (r.ok ? "ok" : "bad");
|
|
321
|
+
out.innerHTML = `Hidden confounder of strength <strong>${{fmt(r.strength)}}</strong>: average estimate <strong>${{fmt(r.mean_estimate)}}</strong>`
|
|
322
|
+
+ ` (typical range ${{fmt(r.mean_low)}} to ${{fmt(r.mean_high)}}). The ranges caught the true value ${{fmt(truth)}}`
|
|
323
|
+
+ ` in <strong>${{Math.round(r.coverage * 100)}}%</strong> of simulations.`;
|
|
324
|
+
dots.forEach((d, j) => d.setAttribute("r", j === i ? 7 : 3.5));
|
|
325
|
+
}}
|
|
326
|
+
slider.addEventListener("input", (e) => show(Number(e.target.value)));
|
|
327
|
+
show(0);
|
|
328
|
+
}})();</script>"""
|
|
329
|
+
return (
|
|
330
|
+
f"{verdict}<div class='chart'><h4>The estimate as a hidden confounder gets stronger (band: its typical range)</h4>"
|
|
331
|
+
f"{chart}</div>"
|
|
332
|
+
f"<input type='range' class='slider' id='{chart_id}-slider' min='0' max='{len(result['sweep']) - 1}' step='1' value='0' "
|
|
333
|
+
f"aria-label='Strength of the hidden confounder'>"
|
|
334
|
+
f"<p id='{chart_id}-out' class='readout'></p>{script}"
|
|
335
|
+
f"<p class='muted'>Strength is the size of the hidden variable's arrows into {cause} and {outcome}, in the same "
|
|
336
|
+
f"units as the diagram's other arrows. {result['repeats']} simulations of {result['simulated_rows']} rows per strength.</p>"
|
|
337
|
+
)
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def _card(step) -> str:
|
|
341
|
+
badge = {True: "<span class='pass'>passed</span>", False: "<span class='fail'>failed</span>", None: ""}[
|
|
342
|
+
_passed(step)
|
|
343
|
+
]
|
|
344
|
+
notes = "".join(f"<p class='warn'>⚠️ {html.escape(warning)}</p>" for warning in step.warnings)
|
|
345
|
+
if step.adjusts_for is not None:
|
|
346
|
+
notes += f"<p class='adjusts'><strong>Adjusts for:</strong> {html.escape(', '.join(step.adjusts_for) or 'nothing')}</p>"
|
|
347
|
+
return f"""
|
|
348
|
+
<section class="card" id="{step.name}" style="border-left-color:{KIND_COLORS[step.kind]}">
|
|
349
|
+
<div class="kind">{KIND_LABELS[step.kind]}{badge}</div>
|
|
350
|
+
<h2>{html.escape(step.name)}</h2>
|
|
351
|
+
<p class="why"><strong>Why:</strong> {html.escape(step.why)}</p>
|
|
352
|
+
{notes}
|
|
353
|
+
<details open><summary>Code</summary><pre><code class="language-python">{html.escape(step.code)}</code></pre></details>
|
|
354
|
+
<h3>Result</h3>
|
|
355
|
+
{_result(step)}
|
|
356
|
+
</section>"""
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def render(workflow) -> str:
|
|
360
|
+
"""The whole report as one HTML page."""
|
|
361
|
+
return (
|
|
362
|
+
PAGE.replace("__TITLE__", html.escape(workflow.title))
|
|
363
|
+
.replace("__DIAGRAM__", html.escape(_workflow_mermaid(workflow)))
|
|
364
|
+
.replace("__CARDS__", "".join(_card(step) for step in workflow.steps.values()))
|
|
365
|
+
)
|
whyflow/sensitivity.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Sensitivity analysis: what if there is a confounder nobody measured?
|
|
2
|
+
|
|
3
|
+
The diagram can only check the confounders you drew. This step adds one you didn't: a hidden variable that
|
|
4
|
+
pushes both the cause and the outcome, at growing strengths. For each strength it simulates data, runs your
|
|
5
|
+
estimator, and records how far the estimate drifts from the truth. The answer is a tipping point: how strong a
|
|
6
|
+
hidden confounder would have to be before your conclusion stops holding.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import math
|
|
10
|
+
from collections.abc import Callable
|
|
11
|
+
|
|
12
|
+
import numpy as np
|
|
13
|
+
|
|
14
|
+
from whyflow.checks import DEFAULT_COVERAGE, REQUIRED, true_value_of
|
|
15
|
+
from whyflow.dag import DAG
|
|
16
|
+
|
|
17
|
+
DEFAULT_STRENGTHS = (0.0, 0.1, 0.2, 0.3, 0.5, 0.75, 1.0)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def check_sensitivity(
|
|
21
|
+
dag: DAG,
|
|
22
|
+
target: dict,
|
|
23
|
+
fit: Callable,
|
|
24
|
+
strengths: tuple[float, ...] = DEFAULT_STRENGTHS,
|
|
25
|
+
n: int = 1000,
|
|
26
|
+
repeats: int = 30,
|
|
27
|
+
seed: int = 0,
|
|
28
|
+
) -> dict:
|
|
29
|
+
"""Rerun the estimator on data with a hidden confounder of each strength, and find the tipping point."""
|
|
30
|
+
if not strengths:
|
|
31
|
+
raise ValueError("Give at least one strength to try.")
|
|
32
|
+
cause, outcome = target["cause"], target["outcome"]
|
|
33
|
+
truth = true_value_of(dag, target)
|
|
34
|
+
|
|
35
|
+
rows = []
|
|
36
|
+
expected = DEFAULT_COVERAGE
|
|
37
|
+
for strength in strengths:
|
|
38
|
+
haunted = dag.with_hidden_confounder(cause, outcome, strength)
|
|
39
|
+
runs = []
|
|
40
|
+
for i in range(repeats):
|
|
41
|
+
found = fit(haunted.simulate(n=n, seed=seed + i))
|
|
42
|
+
missing = set(REQUIRED) - set(found)
|
|
43
|
+
if missing:
|
|
44
|
+
raise ValueError(f"The estimator must return estimate, low and high. Missing: {sorted(missing)}")
|
|
45
|
+
runs.append(found)
|
|
46
|
+
expected = float(runs[0].get("prob", DEFAULT_COVERAGE))
|
|
47
|
+
estimates = np.array([float(r["estimate"]) for r in runs])
|
|
48
|
+
lows = np.array([float(r["low"]) for r in runs])
|
|
49
|
+
highs = np.array([float(r["high"]) for r in runs])
|
|
50
|
+
rows.append({
|
|
51
|
+
"strength": float(strength),
|
|
52
|
+
"mean_estimate": float(estimates.mean()),
|
|
53
|
+
"mean_low": float(lows.mean()),
|
|
54
|
+
"mean_high": float(highs.mean()),
|
|
55
|
+
"coverage": float(np.mean((lows <= truth) & (truth <= highs))),
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
lowest_acceptable = expected - 3 * math.sqrt(expected * (1 - expected) / repeats)
|
|
59
|
+
tipping = next((row["strength"] for row in rows if row["coverage"] < lowest_acceptable), None)
|
|
60
|
+
return {
|
|
61
|
+
"true_value": truth,
|
|
62
|
+
"cause": cause,
|
|
63
|
+
"outcome": outcome,
|
|
64
|
+
"repeats": repeats,
|
|
65
|
+
"simulated_rows": n,
|
|
66
|
+
"expected_coverage": expected,
|
|
67
|
+
"lowest_acceptable_coverage": round(lowest_acceptable, 3),
|
|
68
|
+
"tipping_point": tipping,
|
|
69
|
+
"sweep": rows,
|
|
70
|
+
}
|