whyflow 0.2.0__tar.gz → 0.3.0__tar.gz

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.
Files changed (42) hide show
  1. {whyflow-0.2.0 → whyflow-0.3.0}/.github/workflows/tests.yml +0 -1
  2. {whyflow-0.2.0 → whyflow-0.3.0}/CHANGELOG.md +22 -0
  3. {whyflow-0.2.0 → whyflow-0.3.0}/CITATION.cff +1 -1
  4. {whyflow-0.2.0 → whyflow-0.3.0}/PKG-INFO +60 -21
  5. {whyflow-0.2.0 → whyflow-0.3.0}/README.md +59 -20
  6. whyflow-0.3.0/example.py +44 -0
  7. whyflow-0.3.0/examples/admissions.py +53 -0
  8. whyflow-0.3.0/examples/plant_fungus.py +54 -0
  9. whyflow-0.3.0/examples/waffle_divorce.py +67 -0
  10. {whyflow-0.2.0 → whyflow-0.3.0}/pyproject.toml +1 -1
  11. {whyflow-0.2.0 → whyflow-0.3.0}/tests/test_adjustment.py +4 -3
  12. whyflow-0.3.0/tests/test_formulas.py +73 -0
  13. whyflow-0.3.0/tests/test_sim.py +136 -0
  14. {whyflow-0.2.0 → whyflow-0.3.0}/whyflow/__init__.py +5 -1
  15. {whyflow-0.2.0 → whyflow-0.3.0}/whyflow/charts.py +9 -3
  16. {whyflow-0.2.0 → whyflow-0.3.0}/whyflow/checks.py +10 -2
  17. whyflow-0.3.0/whyflow/formulas.py +44 -0
  18. {whyflow-0.2.0 → whyflow-0.3.0}/whyflow/report.py +22 -5
  19. {whyflow-0.2.0 → whyflow-0.3.0}/whyflow/sensitivity.py +7 -1
  20. whyflow-0.3.0/whyflow/sim.py +274 -0
  21. {whyflow-0.2.0 → whyflow-0.3.0}/whyflow/workflow.py +59 -10
  22. whyflow-0.2.0/example.py +0 -49
  23. {whyflow-0.2.0 → whyflow-0.3.0}/.gitattributes +0 -0
  24. {whyflow-0.2.0 → whyflow-0.3.0}/.github/workflows/demo.yml +0 -0
  25. {whyflow-0.2.0 → whyflow-0.3.0}/.github/workflows/publish.yml +0 -0
  26. {whyflow-0.2.0 → whyflow-0.3.0}/.gitignore +0 -0
  27. {whyflow-0.2.0 → whyflow-0.3.0}/CONTRIBUTING.md +0 -0
  28. {whyflow-0.2.0 → whyflow-0.3.0}/LICENSE +0 -0
  29. {whyflow-0.2.0 → whyflow-0.3.0}/examples/haunted_dag.py +0 -0
  30. {whyflow-0.2.0 → whyflow-0.3.0}/examples/howell_children.py +0 -0
  31. {whyflow-0.2.0 → whyflow-0.3.0}/examples/howell_children_pymc.py +0 -0
  32. {whyflow-0.2.0 → whyflow-0.3.0}/examples/mediator_mistake.py +0 -0
  33. {whyflow-0.2.0 → whyflow-0.3.0}/tests/test_bayes.py +0 -0
  34. {whyflow-0.2.0 → whyflow-0.3.0}/tests/test_charts.py +0 -0
  35. {whyflow-0.2.0 → whyflow-0.3.0}/tests/test_checks.py +0 -0
  36. {whyflow-0.2.0 → whyflow-0.3.0}/tests/test_dag.py +0 -0
  37. {whyflow-0.2.0 → whyflow-0.3.0}/tests/test_report.py +0 -0
  38. {whyflow-0.2.0 → whyflow-0.3.0}/tests/test_sensitivity.py +0 -0
  39. {whyflow-0.2.0 → whyflow-0.3.0}/tests/test_workflow.py +0 -0
  40. {whyflow-0.2.0 → whyflow-0.3.0}/whyflow/adjustment.py +0 -0
  41. {whyflow-0.2.0 → whyflow-0.3.0}/whyflow/bayes.py +0 -0
  42. {whyflow-0.2.0 → whyflow-0.3.0}/whyflow/dag.py +0 -0
@@ -1,5 +1,4 @@
1
1
  name: tests
2
- name: tests
3
2
 
4
3
  on:
5
4
  push:
@@ -2,6 +2,28 @@
2
2
 
3
3
  All notable changes to whyflow. The format follows [Keep a Changelog](https://keepachangelog.com/).
4
4
 
5
+ ## [0.3.0] - 2026-12-04
6
+
7
+ The generative model can now be written as a simulation, the way Statistical Rethinking writes them, which
8
+ removes the "straight lines only" limit.
9
+
10
+ ### Added
11
+
12
+ - **`@wf.simulation`**: write the generative model as a function of `s` (`s.normal`, `s.bernoulli`,
13
+ `s.binomial`, `s.poisson`, `s.uniform`, `s.value`). whyflow reads the causal diagram from the code and finds
14
+ true effects by simulated experiments (cause on vs off, or moved up by one), so yes/no outcomes, counts,
15
+ curves and interactions all work with every check.
16
+ - **Formula reading**: the diagram check reads the estimator's model formula (`"y ~ x + z"`) to see what it
17
+ adjusts for. `adjusts_for` is now optional, and a declaration that contradicts the formula fails the check.
18
+ - **Book examples**: the plant fungus (ch. 6), graduate admissions (ch. 11) and Waffle House divorce (ch. 5,
19
+ real data), on the demo site and in the playground.
20
+ - `inv_logit`, `logit` and `pick` helpers, and `Simulation` for type hints.
21
+
22
+ ### Changed
23
+
24
+ - The sensitivity check judges each simulated world against its own true effect, which matters for curved
25
+ models where a hidden confounder changes the effect itself.
26
+
5
27
  ## [0.2.0] - 2026-12-04
6
28
 
7
29
  First release on PyPI: `pip install whyflow`.
@@ -8,7 +8,7 @@ abstract: >-
8
8
  authors:
9
9
  - family-names: Konialee
10
10
  given-names: Jawad
11
- version: 0.2.0
11
+ version: 0.3.0
12
12
  date-released: 2026-12-04
13
13
  license: MIT
14
14
  repository-code: "https://github.com/koopticon/whyflow"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: whyflow
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: Statistical workflows that carry their reasons, their code and their tests.
5
5
  Project-URL: Homepage, https://koopticon.github.io/whyflow/
6
6
  Project-URL: Repository, https://github.com/koopticon/whyflow
@@ -41,8 +41,8 @@ Description-Content-Type: text/markdown
41
41
 
42
42
  <p align="center">
43
43
  <a href="https://github.com/koopticon/whyflow/actions/workflows/tests.yml"><img alt="tests" src="https://github.com/koopticon/whyflow/actions/workflows/tests.yml/badge.svg"></a>
44
- <a href="https://pypi.org/project/whyflow/"><img alt="PyPI" src="https://img.shields.io/pypi/v/whyflow?color=0d9488"></a>
45
- <a href="https://pypi.org/project/whyflow/"><img alt="Python versions" src="https://img.shields.io/pypi/pyversions/whyflow"></a>
44
+ <a href="https://pypi.org/project/whyflow/"><img alt="PyPI" src="https://img.shields.io/pypi/v/whyflow?color=0d9488&label=pypi"></a>
45
+ <a href="https://pypi.org/project/whyflow/"><img alt="Python versions" src="https://img.shields.io/pypi/pyversions/whyflow?label=python"></a>
46
46
  <a href="https://github.com/koopticon/whyflow/blob/main/LICENSE"><img alt="MIT license" src="https://img.shields.io/badge/license-MIT-blue"></a>
47
47
  </p>
48
48
 
@@ -89,23 +89,27 @@ Python 3.11+. The examples also use `statsmodels`; the Bayesian one uses PyMC (`
89
89
  ```python
90
90
  import statsmodels.formula.api as smf
91
91
 
92
- from whyflow import DAG, Workflow
92
+ from whyflow import Workflow
93
93
 
94
- wf = Workflow("Total effect of age on weight")
94
+ wf = Workflow("Total effect of age on weight in children")
95
95
 
96
96
 
97
- @wf.step(kind="generative_model", why="Age makes children taller; age and height both make them heavier.")
98
- def generative_model():
99
- return DAG().add("age").add("height", causes={"age": 2.0}).add("weight", causes={"age": 0.5, "height": 0.4})
97
+ # The generative model, written as a simulation: whyflow reads the causal diagram from it
98
+ # and finds the true effect by running the experiment.
99
+ @wf.simulation(why="Age makes children taller, and both age and height make them heavier.")
100
+ def generative_model(s):
101
+ age = s.normal("age", 6, 3)
102
+ height = s.normal("height", 75 + 5 * age, 8)
103
+ s.normal("weight", -10 + 0.1 * age + 0.25 * height, 1.5)
100
104
 
101
105
 
102
106
  # A parameter named after a step receives that step's result.
103
- @wf.step(kind="estimand", why="The TOTAL effect of age, including the part that works through height.")
107
+ @wf.step(kind="estimand", why="The TOTAL effect of a year of age on weight, including the part through height.")
104
108
  def estimand(generative_model):
105
109
  return {"cause": "age", "outcome": "weight", "true_value": generative_model.total_effect("age", "weight")}
106
110
 
107
111
 
108
- @wf.step(kind="estimator", adjusts_for=[], why="Weight on age only: height is a mediator, so leave it out.")
112
+ @wf.step(kind="estimator", why="Weight on age only: height is a mediator, so leave it out.")
109
113
  def estimator():
110
114
  def fit(data):
111
115
  model = smf.ols("weight ~ age", data=data).fit()
@@ -115,17 +119,46 @@ def estimator():
115
119
  return fit
116
120
 
117
121
 
118
- wf.add_adjustment_check() # does the causal diagram agree with what the estimator adjusts for?
119
- wf.add_recovery_test() # 100 simulated datasets: does it find the true effect, 1.3?
122
+ wf.add_adjustment_check() # reads the formula above and checks it against the diagram
123
+ wf.add_recovery_test() # 100 simulated datasets: does it find the true effect?
120
124
  wf.add_sensitivity_check() # how strong would an unmeasured confounder have to be to break it?
121
125
 
122
126
  wf.run()
123
127
  wf.report("report.html") # or, in a Jupyter notebook, end a cell with: wf
124
128
  ```
125
129
 
126
- Now change the estimator to `weight ~ age + height` with `adjusts_for=["height"]` and run it again. The
127
- diagram check flags height as a mediator before any data exists, and the recovery test shows the cost: an
128
- estimate of 0.5 instead of 1.3.
130
+ Now change the formula to `"weight ~ age + height"` and run it again. The diagram check reads the new
131
+ formula and flags height as a mediator before any data exists, and the recovery test shows the cost: an
132
+ estimate of 0.1 instead of 1.35.
133
+
134
+ ## Write the model the way the book does
135
+
136
+ The generative model is a plain Python function of `s`, one line per variable, like the simulations in
137
+ *Statistical Rethinking*:
138
+
139
+ ```python
140
+ @wf.simulation(why="The treatment cuts the chance of fungus; fungus slows growth.")
141
+ def generative_model(s):
142
+ h0 = s.normal("h0", 10, 2)
143
+ treatment = s.bernoulli("treatment", 0.5)
144
+ fungus = s.bernoulli("fungus", 0.5 - 0.4 * treatment)
145
+ s.normal("h1", h0 + 5 - 3 * fungus, 1)
146
+ ```
147
+
148
+ From that one function whyflow:
149
+
150
+ - **draws the causal diagram itself.** Every value remembers which variables it was made from, so `fungus`
151
+ knows it used `treatment`. The diagram can't drift out of sync with the simulation.
152
+ - **finds the true effect by doing the experiment.** It reruns the simulation with the cause forced (treatment
153
+ on for everyone, then off; or a continuous cause moved up by one) and compares the outcome. That works the
154
+ same for yes/no variables, counts, curves and interactions.
155
+ - **reads your estimator's formula.** `"h1 ~ treatment + fungus + h0"` tells it you adjusted for fungus, so
156
+ `adjusts_for` is optional, and if you do declare it and it disagrees with the formula, the check fails.
157
+
158
+ Variables: `s.normal`, `s.bernoulli` (yes/no), `s.binomial`, `s.poisson` (counts), `s.uniform`, and
159
+ `s.value` for something computed exactly. Add `observed=False` for anything you couldn't measure. Use
160
+ `inv_logit(...)` to turn a linear score into a probability, and `pick(effects, group)` for per-group effects.
161
+ For straight-line models there's also the shorter `DAG().add("height", causes={"age": 2.0})`.
129
162
 
130
163
  ## What it checks
131
164
 
@@ -182,7 +215,8 @@ and tests together.
182
215
  like in real life.
183
216
  - **Jupyter.** End a cell with `wf` and the report appears inline.
184
217
  - **Steps without boilerplate.** Name a parameter after a step to receive its result, or list them with
185
- `needs=[...]` and name the parameters as you like.
218
+ `needs=[...]` and name the parameters as you like. Type hints keep your editor's autocomplete working:
219
+ `def estimand(generative_model: Simulation):`.
186
220
 
187
221
  ## Examples
188
222
 
@@ -190,7 +224,10 @@ Every example also runs on the [live demo](https://koopticon.github.io/whyflow/)
190
224
 
191
225
  | Example | What it shows |
192
226
  |---|---|
193
- | [`example.py`](example.py) | The quickstart: all three checks pass; a hidden confounder of 0.3 would break it. |
227
+ | [`example.py`](example.py) | The quickstart: all three checks pass. |
228
+ | [`examples/plant_fungus.py`](examples/plant_fungus.py) | *Book, ch. 6:* a yes/no treatment and post-treatment bias. Add fungus to the formula and the estimate collapses from 1.2 to 0. |
229
+ | [`examples/admissions.py`](examples/admissions.py) | *Book, ch. 11:* a yes/no outcome. The true effect is a change in probability; report the log-odds coefficient and the recovery test fails. |
230
+ | [`examples/waffle_divorce.py`](examples/waffle_divorce.py) | *Book, ch. 5:* Waffle Houses and divorce, tested on a simulation, then run on the real 50 states: no effect once the South is accounted for. |
194
231
  | [`examples/mediator_mistake.py`](examples/mediator_mistake.py) | The most common mistake, "controlling for" a mediator. Both tests fail: 0.5 instead of 1.3. |
195
232
  | [`examples/haunted_dag.py`](examples/haunted_dag.py) | McElreath's haunted DAG: an unmeasured confounder no adjustment can fix. |
196
233
  | [`examples/howell_children.py`](examples/howell_children.py) | Real data, the !Kung San census from the book: about **1.34 kg per year** of age. |
@@ -201,10 +238,12 @@ an example runs; it isn't included here. `python demo/build.py` builds the demo
201
238
 
202
239
  ## Current limits
203
240
 
204
- - Simulation covers continuous variables with straight-line relationships, and the target is a **total**
205
- effect of one variable on another.
206
- - The diagram check trusts what `adjusts_for` says; it can't read your model formula. The recovery test is what
207
- catches an estimator that does something different from what it declares.
241
+ - The target is the **total** effect of one variable on another (direct effects and other estimands aren't
242
+ built in yet).
243
+ - The diagram is read from what each line uses. A lookup like `effects[group]` hides the arrow from `group`;
244
+ write `pick(effects, group)` instead.
245
+ - Formulas are read when they're written out as text in the estimator (`"y ~ x + z"`). For anything else,
246
+ declare `adjusts_for=[...]`; the recovery test still catches an estimator that does something different.
208
247
  - The diagram check lists every path between cause and outcome: fine for a few dozen variables, slow for very
209
248
  large diagrams.
210
249
  - Every run re-runs every step (no caching yet).
@@ -11,8 +11,8 @@
11
11
 
12
12
  <p align="center">
13
13
  <a href="https://github.com/koopticon/whyflow/actions/workflows/tests.yml"><img alt="tests" src="https://github.com/koopticon/whyflow/actions/workflows/tests.yml/badge.svg"></a>
14
- <a href="https://pypi.org/project/whyflow/"><img alt="PyPI" src="https://img.shields.io/pypi/v/whyflow?color=0d9488"></a>
15
- <a href="https://pypi.org/project/whyflow/"><img alt="Python versions" src="https://img.shields.io/pypi/pyversions/whyflow"></a>
14
+ <a href="https://pypi.org/project/whyflow/"><img alt="PyPI" src="https://img.shields.io/pypi/v/whyflow?color=0d9488&label=pypi"></a>
15
+ <a href="https://pypi.org/project/whyflow/"><img alt="Python versions" src="https://img.shields.io/pypi/pyversions/whyflow?label=python"></a>
16
16
  <a href="https://github.com/koopticon/whyflow/blob/main/LICENSE"><img alt="MIT license" src="https://img.shields.io/badge/license-MIT-blue"></a>
17
17
  </p>
18
18
 
@@ -59,23 +59,27 @@ Python 3.11+. The examples also use `statsmodels`; the Bayesian one uses PyMC (`
59
59
  ```python
60
60
  import statsmodels.formula.api as smf
61
61
 
62
- from whyflow import DAG, Workflow
62
+ from whyflow import Workflow
63
63
 
64
- wf = Workflow("Total effect of age on weight")
64
+ wf = Workflow("Total effect of age on weight in children")
65
65
 
66
66
 
67
- @wf.step(kind="generative_model", why="Age makes children taller; age and height both make them heavier.")
68
- def generative_model():
69
- return DAG().add("age").add("height", causes={"age": 2.0}).add("weight", causes={"age": 0.5, "height": 0.4})
67
+ # The generative model, written as a simulation: whyflow reads the causal diagram from it
68
+ # and finds the true effect by running the experiment.
69
+ @wf.simulation(why="Age makes children taller, and both age and height make them heavier.")
70
+ def generative_model(s):
71
+ age = s.normal("age", 6, 3)
72
+ height = s.normal("height", 75 + 5 * age, 8)
73
+ s.normal("weight", -10 + 0.1 * age + 0.25 * height, 1.5)
70
74
 
71
75
 
72
76
  # A parameter named after a step receives that step's result.
73
- @wf.step(kind="estimand", why="The TOTAL effect of age, including the part that works through height.")
77
+ @wf.step(kind="estimand", why="The TOTAL effect of a year of age on weight, including the part through height.")
74
78
  def estimand(generative_model):
75
79
  return {"cause": "age", "outcome": "weight", "true_value": generative_model.total_effect("age", "weight")}
76
80
 
77
81
 
78
- @wf.step(kind="estimator", adjusts_for=[], why="Weight on age only: height is a mediator, so leave it out.")
82
+ @wf.step(kind="estimator", why="Weight on age only: height is a mediator, so leave it out.")
79
83
  def estimator():
80
84
  def fit(data):
81
85
  model = smf.ols("weight ~ age", data=data).fit()
@@ -85,17 +89,46 @@ def estimator():
85
89
  return fit
86
90
 
87
91
 
88
- wf.add_adjustment_check() # does the causal diagram agree with what the estimator adjusts for?
89
- wf.add_recovery_test() # 100 simulated datasets: does it find the true effect, 1.3?
92
+ wf.add_adjustment_check() # reads the formula above and checks it against the diagram
93
+ wf.add_recovery_test() # 100 simulated datasets: does it find the true effect?
90
94
  wf.add_sensitivity_check() # how strong would an unmeasured confounder have to be to break it?
91
95
 
92
96
  wf.run()
93
97
  wf.report("report.html") # or, in a Jupyter notebook, end a cell with: wf
94
98
  ```
95
99
 
96
- Now change the estimator to `weight ~ age + height` with `adjusts_for=["height"]` and run it again. The
97
- diagram check flags height as a mediator before any data exists, and the recovery test shows the cost: an
98
- estimate of 0.5 instead of 1.3.
100
+ Now change the formula to `"weight ~ age + height"` and run it again. The diagram check reads the new
101
+ formula and flags height as a mediator before any data exists, and the recovery test shows the cost: an
102
+ estimate of 0.1 instead of 1.35.
103
+
104
+ ## Write the model the way the book does
105
+
106
+ The generative model is a plain Python function of `s`, one line per variable, like the simulations in
107
+ *Statistical Rethinking*:
108
+
109
+ ```python
110
+ @wf.simulation(why="The treatment cuts the chance of fungus; fungus slows growth.")
111
+ def generative_model(s):
112
+ h0 = s.normal("h0", 10, 2)
113
+ treatment = s.bernoulli("treatment", 0.5)
114
+ fungus = s.bernoulli("fungus", 0.5 - 0.4 * treatment)
115
+ s.normal("h1", h0 + 5 - 3 * fungus, 1)
116
+ ```
117
+
118
+ From that one function whyflow:
119
+
120
+ - **draws the causal diagram itself.** Every value remembers which variables it was made from, so `fungus`
121
+ knows it used `treatment`. The diagram can't drift out of sync with the simulation.
122
+ - **finds the true effect by doing the experiment.** It reruns the simulation with the cause forced (treatment
123
+ on for everyone, then off; or a continuous cause moved up by one) and compares the outcome. That works the
124
+ same for yes/no variables, counts, curves and interactions.
125
+ - **reads your estimator's formula.** `"h1 ~ treatment + fungus + h0"` tells it you adjusted for fungus, so
126
+ `adjusts_for` is optional, and if you do declare it and it disagrees with the formula, the check fails.
127
+
128
+ Variables: `s.normal`, `s.bernoulli` (yes/no), `s.binomial`, `s.poisson` (counts), `s.uniform`, and
129
+ `s.value` for something computed exactly. Add `observed=False` for anything you couldn't measure. Use
130
+ `inv_logit(...)` to turn a linear score into a probability, and `pick(effects, group)` for per-group effects.
131
+ For straight-line models there's also the shorter `DAG().add("height", causes={"age": 2.0})`.
99
132
 
100
133
  ## What it checks
101
134
 
@@ -152,7 +185,8 @@ and tests together.
152
185
  like in real life.
153
186
  - **Jupyter.** End a cell with `wf` and the report appears inline.
154
187
  - **Steps without boilerplate.** Name a parameter after a step to receive its result, or list them with
155
- `needs=[...]` and name the parameters as you like.
188
+ `needs=[...]` and name the parameters as you like. Type hints keep your editor's autocomplete working:
189
+ `def estimand(generative_model: Simulation):`.
156
190
 
157
191
  ## Examples
158
192
 
@@ -160,7 +194,10 @@ Every example also runs on the [live demo](https://koopticon.github.io/whyflow/)
160
194
 
161
195
  | Example | What it shows |
162
196
  |---|---|
163
- | [`example.py`](example.py) | The quickstart: all three checks pass; a hidden confounder of 0.3 would break it. |
197
+ | [`example.py`](example.py) | The quickstart: all three checks pass. |
198
+ | [`examples/plant_fungus.py`](examples/plant_fungus.py) | *Book, ch. 6:* a yes/no treatment and post-treatment bias. Add fungus to the formula and the estimate collapses from 1.2 to 0. |
199
+ | [`examples/admissions.py`](examples/admissions.py) | *Book, ch. 11:* a yes/no outcome. The true effect is a change in probability; report the log-odds coefficient and the recovery test fails. |
200
+ | [`examples/waffle_divorce.py`](examples/waffle_divorce.py) | *Book, ch. 5:* Waffle Houses and divorce, tested on a simulation, then run on the real 50 states: no effect once the South is accounted for. |
164
201
  | [`examples/mediator_mistake.py`](examples/mediator_mistake.py) | The most common mistake, "controlling for" a mediator. Both tests fail: 0.5 instead of 1.3. |
165
202
  | [`examples/haunted_dag.py`](examples/haunted_dag.py) | McElreath's haunted DAG: an unmeasured confounder no adjustment can fix. |
166
203
  | [`examples/howell_children.py`](examples/howell_children.py) | Real data, the !Kung San census from the book: about **1.34 kg per year** of age. |
@@ -171,10 +208,12 @@ an example runs; it isn't included here. `python demo/build.py` builds the demo
171
208
 
172
209
  ## Current limits
173
210
 
174
- - Simulation covers continuous variables with straight-line relationships, and the target is a **total**
175
- effect of one variable on another.
176
- - The diagram check trusts what `adjusts_for` says; it can't read your model formula. The recovery test is what
177
- catches an estimator that does something different from what it declares.
211
+ - The target is the **total** effect of one variable on another (direct effects and other estimands aren't
212
+ built in yet).
213
+ - The diagram is read from what each line uses. A lookup like `effects[group]` hides the arrow from `group`;
214
+ write `pick(effects, group)` instead.
215
+ - Formulas are read when they're written out as text in the estimator (`"y ~ x + z"`). For anything else,
216
+ declare `adjusts_for=[...]`; the recovery test still catches an estimator that does something different.
178
217
  - The diagram check lists every path between cause and outcome: fine for a few dozen variables, slow for very
179
218
  large diagrams.
180
219
  - Every run re-runs every step (no caching yet).
@@ -0,0 +1,44 @@
1
+ """The quickstart from the README: the total effect of age on weight in children."""
2
+
3
+ import statsmodels.formula.api as smf
4
+
5
+ from whyflow import Workflow
6
+
7
+ wf = Workflow("Total effect of age on weight in children")
8
+
9
+
10
+ # The generative model, written as a simulation: whyflow reads the causal diagram from it
11
+ # and finds the true effect by running the experiment.
12
+ @wf.simulation(why="Age makes children taller, and both age and height make them heavier.")
13
+ def generative_model(s):
14
+ age = s.normal("age", 6, 3)
15
+ height = s.normal("height", 75 + 5 * age, 8)
16
+ s.normal("weight", -10 + 0.1 * age + 0.25 * height, 1.5)
17
+
18
+
19
+ # A parameter named after a step receives that step's result.
20
+ @wf.step(kind="estimand", why="The TOTAL effect of a year of age on weight, including the part through height.")
21
+ def estimand(generative_model):
22
+ return {"cause": "age", "outcome": "weight", "true_value": generative_model.total_effect("age", "weight")}
23
+
24
+
25
+ @wf.step(kind="estimator", why="Weight on age only: height is a mediator, so leave it out.")
26
+ def estimator():
27
+ def fit(data):
28
+ model = smf.ols("weight ~ age", data=data).fit()
29
+ low, high = model.conf_int().loc["age"]
30
+ return {"estimate": model.params["age"], "low": low, "high": high}
31
+
32
+ return fit
33
+
34
+
35
+ wf.add_adjustment_check() # reads the formula above and checks it against the diagram
36
+ wf.add_recovery_test() # 100 simulated datasets: does it find the true effect?
37
+ wf.add_sensitivity_check() # how strong would an unmeasured confounder have to be to break it?
38
+
39
+ if __name__ == "__main__":
40
+ results = wf.run()
41
+ test = results["recovery_test"]
42
+ print(f"true effect {test['true_value']:.2f}, passed: {test['passed']}, coverage: {test['coverage']:.0%}, "
43
+ f"bias: {test['bias']:+.3f}, tipping point: {results['sensitivity_check']['tipping_point']}")
44
+ wf.report("report.html")
@@ -0,0 +1,53 @@
1
+ """Statistical Rethinking, chapter 11: graduate admissions (a yes/no outcome).
2
+
3
+ Does applicant gender change the chance of admission? In this simulation there is no direct discrimination:
4
+ departments admit everyone at the same rate. But women apply more often to the department that admits fewer
5
+ people, so the TOTAL effect of gender on admission is still negative, through the choice of department.
6
+
7
+ Two lessons in one:
8
+ - A logistic regression's coefficient is on the log-odds scale (about -0.6 here); the true effect is a change
9
+ in probability (about -0.14). The estimator reports the average change in probability, which is what the
10
+ question asks for. Report the raw coefficient instead and the recovery test fails.
11
+ - The total effect isn't discrimination. Adjusting for department would ask a different question (the direct
12
+ effect), and the diagram check flags department as a mediator for this one.
13
+ """
14
+
15
+ import statsmodels.formula.api as smf
16
+
17
+ from whyflow import Workflow, inv_logit
18
+
19
+ wf = Workflow("Admissions: total effect of gender on the chance of admission")
20
+
21
+
22
+ @wf.simulation(why="Women apply more to the harder department; departments treat everyone the same.")
23
+ def generative_model(s):
24
+ gender = s.bernoulli("gender", 0.5) # 1 = woman
25
+ department = s.bernoulli("department", 0.3 + 0.4 * gender) # 1 = the harder department
26
+ s.bernoulli("admitted", inv_logit(0.5 - 1.5 * department)) # no direct effect of gender
27
+
28
+
29
+ @wf.step(kind="estimand", why="The total effect of gender on the probability of admission (woman vs man).")
30
+ def estimand(generative_model):
31
+ return {"cause": "gender", "outcome": "admitted", "true_value": generative_model.total_effect("gender", "admitted")}
32
+
33
+
34
+ @wf.step(kind="estimator",
35
+ why="Logistic regression on gender alone, reported as the average change in admission probability "
36
+ "(not the log-odds coefficient).")
37
+ def estimator():
38
+ def fit(data):
39
+ model = smf.logit("admitted ~ gender", data=data).fit(disp=0)
40
+ effect = model.get_margeff(at="overall", dummy=True).summary_frame().loc["gender"]
41
+ return {"estimate": effect.iloc[0], "low": effect.iloc[4], "high": effect.iloc[5]}
42
+
43
+ return fit
44
+
45
+
46
+ wf.add_adjustment_check()
47
+ wf.add_recovery_test()
48
+ wf.add_sensitivity_check(strengths=(0.0, 0.25, 0.5, 1.0, 1.5, 2.0))
49
+
50
+ if __name__ == "__main__":
51
+ results = wf.run()
52
+ print(f"true effect {results['estimand']['true_value']:.3f}, recovery passed: {results['recovery_test']['passed']}")
53
+ wf.report("admissions_report.html")
@@ -0,0 +1,54 @@
1
+ """Statistical Rethinking, chapter 6: the plant fungus experiment (post-treatment bias).
2
+
3
+ Plants get an anti-fungal treatment or not. The treatment reduces fungus, and fungus slows growth. Question:
4
+ what is the total effect of the treatment on final height?
5
+
6
+ The trap is "controlling for" fungus: it's how the treatment works, so adjusting for it hides the effect.
7
+ This estimator gets it right (final height on treatment and starting height). Change the formula to
8
+ "h1 ~ treatment + fungus + h0" and the diagram check catches the mistake from the formula alone.
9
+
10
+ The generative model is a simulation, written the way the book writes them: whyflow reads the causal diagram
11
+ from the code and finds the true effect by running the experiment (treatment on vs off).
12
+ """
13
+
14
+ import statsmodels.formula.api as smf
15
+
16
+ from whyflow import Workflow
17
+
18
+ wf = Workflow("Plant fungus: total effect of the treatment on growth")
19
+
20
+
21
+ @wf.simulation(why="Plants start at some height. The treatment cuts the chance of fungus; fungus slows growth.")
22
+ def generative_model(s):
23
+ h0 = s.normal("h0", 10, 2) # starting height
24
+ treatment = s.bernoulli("treatment", 0.5) # half the plants get it
25
+ fungus = s.bernoulli("fungus", 0.5 - 0.4 * treatment) # 50% chance of fungus without, 10% with
26
+ s.normal("h1", h0 + 5 - 3 * fungus, 1) # final height
27
+
28
+
29
+ @wf.step(kind="estimand", why="The TOTAL effect of the treatment on final height, including the part through fungus.")
30
+ def estimand(generative_model):
31
+ return {"cause": "treatment", "outcome": "h1", "true_value": generative_model.total_effect("treatment", "h1")}
32
+
33
+
34
+ @wf.step(kind="estimator",
35
+ why="Final height on treatment, plus starting height to sharpen the estimate. Not fungus: it's how the "
36
+ "treatment works.")
37
+ def estimator():
38
+ def fit(data):
39
+ model = smf.ols("h1 ~ treatment + h0", data=data).fit()
40
+ low, high = model.conf_int().loc["treatment"]
41
+ return {"estimate": model.params["treatment"], "low": low, "high": high}
42
+
43
+ return fit
44
+
45
+
46
+ wf.add_adjustment_check() # reads the formula above: adjusting for h0 only
47
+ wf.add_recovery_test()
48
+ wf.add_sensitivity_check()
49
+
50
+ if __name__ == "__main__":
51
+ results = wf.run()
52
+ print(f"true effect {results['estimand']['true_value']:.2f}, "
53
+ f"recovery passed: {results['recovery_test']['passed']}")
54
+ wf.report("fungus_report.html")
@@ -0,0 +1,67 @@
1
+ """Statistical Rethinking, chapter 5: do Waffle Houses cause divorce? (real data)
2
+
3
+ US states with more Waffle House restaurants have higher divorce rates. Nobody thinks waffles cause divorce:
4
+ both are more common in the South. Southern states marry younger, and marrying younger means more divorce.
5
+
6
+ The workflow tests the estimator on a simulation where waffles have NO effect, then runs it on the real 50
7
+ states (data from the rethinking package, downloaded when you run this). Remove "+ South" from the formula
8
+ and both checks fail: the diagram check finds the open back door through the South, and the recovery test
9
+ finds a "waffle effect" that the simulation proves isn't there.
10
+ """
11
+
12
+ import numpy as np
13
+ import pandas as pd
14
+ import statsmodels.formula.api as smf
15
+
16
+ from whyflow import Workflow
17
+
18
+ DATA_URL = "https://raw.githubusercontent.com/rmcelreath/rethinking/master/data/WaffleDivorce.csv"
19
+
20
+ wf = Workflow("Waffle Houses and divorce: is there any effect?")
21
+
22
+
23
+ @wf.simulation(why="Southern states have more Waffle Houses, marry younger, and younger marriage means more divorce. "
24
+ "Waffles themselves do nothing.")
25
+ def generative_model(s):
26
+ south = s.bernoulli("South", 0.3)
27
+ age = s.normal("MedianAgeMarriage", 26.5 - 1.2 * south, 1.0)
28
+ marriage = s.normal("Marriage", 20 - 2.0 * (age - 26), 3.0)
29
+ s.poisson("WaffleHouses", np.exp(1.0 + 3.0 * south))
30
+ s.normal("Divorce", 9.7 - 1.0 * (age - 26) + 0.05 * (marriage - 20), 1.5)
31
+
32
+
33
+ @wf.step(kind="estimand", why="The effect of one more Waffle House on the divorce rate (per 1,000 adults).")
34
+ def estimand(generative_model):
35
+ return {"cause": "WaffleHouses", "outcome": "Divorce",
36
+ "true_value": generative_model.total_effect("WaffleHouses", "Divorce")}
37
+
38
+
39
+ @wf.step(kind="estimator", why="Divorce on Waffle Houses, adjusting for the South to close the back door.")
40
+ def estimator():
41
+ def fit(data):
42
+ model = smf.ols("Divorce ~ WaffleHouses + South", data=data).fit()
43
+ low, high = model.conf_int().loc["WaffleHouses"]
44
+ return {"estimate": model.params["WaffleHouses"], "low": low, "high": high}
45
+
46
+ return fit
47
+
48
+
49
+ wf.add_adjustment_check()
50
+ wf.add_recovery_test(n=50) # 50 rows, like the 50 states: small data, wide ranges
51
+ wf.add_sensitivity_check(n=50)
52
+
53
+
54
+ @wf.step(kind="data", why="The 50 states, as used in the book.")
55
+ def states():
56
+ return pd.read_csv(DATA_URL, sep=";")
57
+
58
+
59
+ @wf.step(kind="analysis", why="The estimator passed its tests, so now it runs on the real states.")
60
+ def analysis(estimator, states):
61
+ return estimator(states)
62
+
63
+
64
+ if __name__ == "__main__":
65
+ results = wf.run()
66
+ print("real data:", {key: round(float(value), 4) for key, value in results["analysis"].items()})
67
+ wf.report("waffles_report.html")
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "whyflow"
7
- version = "0.2.0"
7
+ version = "0.3.0"
8
8
  description = "Statistical workflows that carry their reasons, their code and their tests."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -121,13 +121,14 @@ def test_workflow_adjustment_check_uses_what_the_estimator_declares():
121
121
  wf.add_adjustment_check()
122
122
  results = wf.run()
123
123
  assert not results["adjustment_check"]["passed"]
124
- assert "['height']" in wf.steps["adjustment_check"].code
124
+ assert results["adjustment_check"]["adjusts_for"] == ["height"]
125
125
 
126
126
 
127
- def test_estimator_must_declare_what_it_adjusts_for():
127
+ def test_without_a_formula_the_estimator_must_declare_what_it_adjusts_for():
128
128
  wf = workflow(adjusts_for=None)
129
+ wf.add_adjustment_check()
129
130
  with pytest.raises(ValueError, match="adjusts_for"):
130
- wf.add_adjustment_check()
131
+ wf.run()
131
132
 
132
133
 
133
134
  def test_report_lights_up_the_bias_path():