Every step with its reason, its code and its result. Click a box to jump to its step.
graph TD
generative_model["Generative model<br/>generative_model"]:::generative_model
click generative_model href "#generative_model"
estimand["Estimand<br/>estimand"]:::estimand
click estimand href "#estimand"
generative_model --> estimand
estimator["Estimator<br/>estimator"]:::estimator
click estimator href "#estimator"
adjustment_check["Test on simulated data ✅<br/>adjustment_check"]:::test
click adjustment_check href "#adjustment_check"
generative_model --> adjustment_check
estimand --> adjustment_check
estimator --> adjustment_check
recovery_test["Test on simulated data ✅<br/>recovery_test"]:::test
click recovery_test href "#recovery_test"
generative_model --> recovery_test
estimand --> recovery_test
estimator --> recovery_test
sensitivity_check["Sensitivity analysis<br/>sensitivity_check"]:::sensitivity
click sensitivity_check href "#sensitivity_check"
generative_model --> sensitivity_check
estimand --> sensitivity_check
estimator --> sensitivity_check
states["Data<br/>states"]:::data
click states href "#states"
analysis["Real-data analysis<br/>analysis"]:::analysis
click analysis href "#analysis"
estimator --> analysis
states --> analysis
classDef generative_model fill:#6366f1,color:#fff,stroke:none
classDef estimand fill:#0ea5e9,color:#fff,stroke:none
classDef estimator fill:#f59e0b,color:#fff,stroke:none
classDef test fill:#22c55e,color:#fff,stroke:none
classDef sensitivity fill:#0d9488,color:#fff,stroke:none
classDef data fill:#64748b,color:#fff,stroke:none
classDef analysis fill:#ef4444,color:#fff,stroke:noneWhy: Southern states have more Waffle Houses, marry younger, and younger marriage means more divorce. Waffles themselves do nothing.
@wf.simulation(why="Southern states have more Waffle Houses, marry younger, and younger marriage means more divorce. "
"Waffles themselves do nothing.")
def generative_model(s):
south = s.bernoulli("South", 0.3)
age = s.normal("MedianAgeMarriage", 26.5 - 1.2 * south, 1.0)
marriage = s.normal("Marriage", 20 - 2.0 * (age - 26), 3.0)
s.poisson("WaffleHouses", np.exp(1.0 + 3.0 * south))
s.normal("Divorce", 9.7 - 1.0 * (age - 26) + 0.05 * (marriage - 20), 1.5)
The causal diagram, read from the simulation code above: an arrow means that line used that variable.
graph LR
South
MedianAgeMarriage
South --> MedianAgeMarriage
Marriage
MedianAgeMarriage --> Marriage
WaffleHouses
South --> WaffleHouses
Divorce
Marriage --> Divorce
MedianAgeMarriage --> Divorce
Why: The effect of one more Waffle House on the divorce rate (per 1,000 adults).
@wf.step(kind="estimand", why="The effect of one more Waffle House on the divorce rate (per 1,000 adults).")
def estimand(generative_model):
return {"cause": "WaffleHouses", "outcome": "Divorce",
"true_value": generative_model.total_effect("WaffleHouses", "Divorce")}
| cause | WaffleHouses |
|---|---|
| outcome | Divorce |
| true_value | 0.000 |
Why: Divorce on Waffle Houses, adjusting for the South to close the back door.
@wf.step(kind="estimator", why="Divorce on Waffle Houses, adjusting for the South to close the back door.")
def estimator():
def fit(data):
model = smf.ols("Divorce ~ WaffleHouses + South", data=data).fit()
low, high = model.conf_int().loc["WaffleHouses"]
return {"estimate": model.params["WaffleHouses"], "low": low, "high": high}
return fit
A function, used by later steps.
Why: Before running anything: use the causal diagram to check that the estimator adjusts for the right variables. Adjusting for a mediator or a collider, or missing a confounder, biases the answer no matter how much data you have.
# whyflow reads the estimator's model formula (or its adjusts_for=[...]) to see what it
# adjusts for, and checks that against the causal diagram from the generative model:
check_adjustment(diagram, target["cause"], target["outcome"], adjusts_for)
Read from the estimator's formula: Divorce ~ WaffleHouses + South
Adjusting for South gives the total effect of WaffleHouses on Divorce without bias, if the causal diagram is right.
graph LR
South["South<br/><small>adjusted</small>"]:::good
MedianAgeMarriage["MedianAgeMarriage"]:::plain
Marriage["Marriage"]:::plain
WaffleHouses["WaffleHouses"]:::focus
Divorce["Divorce"]:::focus
South e0@--> MedianAgeMarriage
MedianAgeMarriage e1@--> Marriage
South e2@--> WaffleHouses
Marriage e3@--> Divorce
MedianAgeMarriage e4@--> Divorce
classDef focus fill:#1f2937,stroke:#1f2937,color:#ffffff,stroke-width:1px
classDef good fill:#dcfce7,stroke:#16a34a,color:#14532d,stroke-width:3px
classDef bad fill:#fee2e2,stroke:#dc2626,color:#7f1d1d,stroke-width:3px
classDef suggest fill:#ffffff,stroke:#16a34a,color:#14532d,stroke-width:3px
classDef plain fill:#f3f4f6,stroke:#9ca3af,color:#374151,stroke-width:1px
classDef suggest stroke-dasharray:6 3| South | confounder: links cause and outcome through a back door, without being part of the effect |
|---|---|
| MedianAgeMarriage | confounder: links cause and outcome through a back door, without being part of the effect |
| Marriage | confounder: links cause and outcome through a back door, without being part of the effect |
Why: Before touching real data: simulate data from the generative model many times, where the true answer is known, and check that the estimator finds it, and that its ranges catch it as often as they promise.
def check_recovery(
dag: DAG,
target: dict,
fit: Callable,
n: int = 5000,
seed: int = 0,
repeats: int = 1,
expected_coverage: float | None = None,
) -> dict:
"""Simulate data from the generative model, run the estimator, and see if it finds the truth.
target says what we want: 'cause' and 'outcome' (and optionally 'true_value').
fit(data) is the estimator: it must return 'estimate', 'low' and 'high'.
With repeats=1, it's one simulation: passed means the truth is inside the range.
With more repeats, it's the reliable version: passed means the ranges caught the truth about as often
as they promise (their coverage), allowing for the luck of a finite number of simulations.
"""
if repeats < 1:
raise ValueError("repeats must be at least 1")
truth = true_value_of(dag, target)
if repeats == 1:
found = _fit_once(fit, dag.simulate(n=n, seed=seed))
low, high = float(found["low"]), float(found["high"])
return {
"estimate": float(found["estimate"]),
"low": low,
"high": high,
"true_value": truth,
"passed": low <= truth <= high,
"simulated_rows": n,
# anything else the estimator reports (e.g. which kind of interval) is kept too
**{key: value for key, value in found.items() if key not in REQUIRED},
}
runs = [_fit_once(fit, dag.simulate(n=n, seed=seed + i)) for i in range(repeats)]
estimates = np.array([float(run["estimate"]) for run in runs])
lows = np.array([float(run["low"]) for run in runs])
highs = np.array([float(run["high"]) for run in runs])
expected = expected_coverage or runs[0].get("prob") or DEFAULT_COVERAGE
coverage = float(np.mean((lows <= truth) & (truth <= highs)))
# A perfect estimator still misses sometimes; allow three standard errors of that luck.
lowest_acceptable = expected - 3 * math.sqrt(expected * (1 - expected) / repeats)
return {
"true_value": truth,
"repeats": repeats,
"simulated_rows": n,
"coverage": coverage,
"expected_coverage": float(expected),
"lowest_acceptable_coverage": round(lowest_acceptable, 3),
"mean_estimate": float(estimates.mean()),
"bias": float(estimates.mean() - truth),
"rmse": float(math.sqrt(np.mean((estimates - truth) ** 2))),
"passed": coverage >= lowest_acceptable,
**{key: value for key, value in runs[0].items() if key not in (*REQUIRED, "prob")},
# every simulation's result, for the report's charts
"estimates": estimates.tolist(),
"lows": lows.tolist(),
"highs": highs.tolist(),
}
In 100 simulations, the estimator's range caught the true value 97 times (97%). It promises 95%; anything above 88% is within the luck of 100 tries. On average it was off by +0.0107.
| true_value | 0.000 |
|---|---|
| repeats | 100 |
| simulated_rows | 50 |
| coverage | 0.970 |
| expected_coverage | 0.950 |
| lowest_acceptable_coverage | 0.885 |
| mean_estimate | 0.011 |
| bias | 0.011 |
| rmse | 0.064 |
| passed | yes |
Why: The diagram can only include the confounders we thought of. This asks how strong a confounder nobody measured would have to be before the estimator stops finding the truth.
def check_sensitivity(
dag: DAG,
target: dict,
fit: Callable,
strengths: tuple[float, ...] = DEFAULT_STRENGTHS,
n: int = 1000,
repeats: int = 30,
seed: int = 0,
) -> dict:
"""Rerun the estimator on data with a hidden confounder of each strength, and find the tipping point."""
if not strengths:
raise ValueError("Give at least one strength to try.")
cause, outcome = target["cause"], target["outcome"]
truth = true_value_of(dag, target)
rows = []
expected = DEFAULT_COVERAGE
for strength in strengths:
haunted = dag.with_hidden_confounder(cause, outcome, strength)
# In a curved model (yes/no outcomes, say) a hidden confounder can change the true effect itself,
# so each simulated world is judged against its own truth.
if isinstance(dag, Simulation):
truth = true_value_of(haunted, {key: value for key, value in target.items() if key != "true_value"})
runs = []
for i in range(repeats):
found = fit(haunted.simulate(n=n, seed=seed + i))
missing = set(REQUIRED) - set(found)
if missing:
raise ValueError(f"The estimator must return estimate, low and high. Missing: {sorted(missing)}")
runs.append(found)
expected = float(runs[0].get("prob", DEFAULT_COVERAGE))
estimates = np.array([float(r["estimate"]) for r in runs])
lows = np.array([float(r["low"]) for r in runs])
highs = np.array([float(r["high"]) for r in runs])
rows.append({
"strength": float(strength),
"mean_estimate": float(estimates.mean()),
"mean_low": float(lows.mean()),
"mean_high": float(highs.mean()),
"coverage": float(np.mean((lows <= truth) & (truth <= highs))),
"true_value": truth,
})
lowest_acceptable = expected - 3 * math.sqrt(expected * (1 - expected) / repeats)
tipping = next((row["strength"] for row in rows if row["coverage"] < lowest_acceptable), None)
return {
"true_value": rows[0]["true_value"],
"cause": cause,
"outcome": outcome,
"repeats": repeats,
"simulated_rows": n,
"expected_coverage": expected,
"lowest_acceptable_coverage": round(lowest_acceptable, 3),
"tipping_point": tipping,
"sweep": rows,
}
A hidden confounder with arrows of 1 into both WaffleHouses and Divorce would be enough to break this: the estimate drifts to 0.0145 (truth 0) and the ranges catch the truth only 70% of the time. Ask yourself: could something that strong be missing from the diagram?
Strength is the size of the hidden variable's arrows into WaffleHouses and Divorce, in the same units as the diagram's other arrows. 30 simulations of 50 rows per strength.
Why: The 50 states, as used in the book.
@wf.step(kind="data", why="The 50 states, as used in the book.")
def states():
return pd.read_csv(DATA_URL, sep=";")
50 rows. Columns: Location, Loc, Population, MedianAgeMarriage, Marriage, Marriage SE, Divorce, Divorce SE, WaffleHouses, South, Slaves1860, Population1860, PropSlaves1860
| Location | Loc | Population | MedianAgeMarriage | Marriage | Marriage SE | Divorce | Divorce SE | WaffleHouses | South | Slaves1860 | Population1860 | PropSlaves1860 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Alabama | AL | 4.78 | 25.3 | 20.2 | 1.27 | 12.7 | 0.79 | 128 | 1 | 435080 | 964201 | 0.45 |
| Alaska | AK | 0.71 | 25.2 | 26.0 | 2.93 | 12.5 | 2.05 | 0 | 0 | 0 | 0 | 0.00 |
| Arizona | AZ | 6.33 | 25.8 | 20.3 | 0.98 | 10.8 | 0.74 | 18 | 0 | 0 | 0 | 0.00 |
| Arkansas | AR | 2.92 | 24.3 | 26.4 | 1.70 | 13.5 | 1.22 | 41 | 1 | 111115 | 435450 | 0.26 |
| California | CA | 37.25 | 26.8 | 19.1 | 0.39 | 8.0 | 0.24 | 0 | 0 | 0 | 379994 | 0.00 |
Why: The estimator passed its tests, so now it runs on the real states.
@wf.step(kind="analysis", why="The estimator passed its tests, so now it runs on the real states.")
def analysis(estimator, states):
return estimator(states)
| estimate | 0.001 |
|---|---|
| low | -0.010 |
| high | 0.011 |
Made with whyflow.