← all whyflow examples

Haunted DAG: effect of parents' education on children's

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
    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:none
Generative model

generative_model

Why: Grandparents shape parents and children; an unmeasured neighborhood shapes parents and children.

Code
@wf.step(kind="generative_model",
         why="Grandparents shape parents and children; an unmeasured neighborhood shapes parents and children.")
def generative_model():
    return (
        DAG()
        .add("U", observed=False)
        .add("G")
        .add("P", causes={"G": 1.0, "U": 2.0})
        .add("C", causes={"P": 1.0, "G": 0.0, "U": 2.0})
    )

Result

graph LR
    U
    G
    P
    G -->|1.0| P
    U -->|2.0| P
    C
    P -->|1.0| C
    G -->|0.0| C
    U -->|2.0| C
    style U stroke-dasharray:5 4
Estimand

estimand

Why: The total effect of parents' education on children's.

Code
@wf.step(kind="estimand", needs=["generative_model"],
         why="The total effect of parents' education on children's.")
def estimand(dag):
    return {"cause": "P", "outcome": "C"}

Result

causeP
outcomeC
Estimator

estimator

Why: Regress C on P, adjusting for G to close the back door through the grandparents.

Adjusts for: G

Code
@wf.step(kind="estimator", adjusts_for=["G"],
         why="Regress C on P, adjusting for G to close the back door through the grandparents.")
def estimator():
    def fit(data):
        model = smf.ols("C ~ P + G", data=data).fit()
        low, high = model.conf_int().loc["P"]
        return {"estimate": model.params["P"], "low": low, "high": high}
    return fit

Result

A function, used by later steps.

Test on simulated datafailed

adjustment_check

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.

Code
# 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)

Result

Read from the estimator's formula: C ~ P + G

Adjusting for G gives a biased answer:

No set of measured variables removes this bias: something unmeasured is in the way. You'd need to measure it, use a different design, or check how big the bias could be.

graph LR
    U["U"]:::plain
    G["G<br/><small>adjusted</small>"]:::good
    P["P"]:::focus
    C["C"]:::focus
    G e0@-->|1.0| P
    U e1@-->|2.0| P
    e1@{ animate: true }
    P e2@-->|1.0| C
    G e3@-->|0.0| C
    U e4@-->|2.0| C
    e4@{ animate: true }
    linkStyle 1,4 stroke:#dc2626,stroke-width:3px
    linkStyle 2 stroke:#16a34a,stroke-width:3px
    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
    style U stroke-dasharray:5 4
cause and outcomeadjusted for: rightadjusted for: wrongadjust for this insteadother variablesthe effect you wantbias leaking in (moving)

What each variable is, for this question

Uconfounder: links cause and outcome through a back door, without being part of the effect
Gconfounder: links cause and outcome through a back door, without being part of the effect
Test on simulated datafailed

recovery_test

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.

Code
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(),
    }

Result

In 50 simulations, the estimator's range caught the true value 0 times (0%). It promises 95%; anything above 86% is within the luck of 50 tries. On average it was off by +0.799.

Where the estimates landed

true value 1average estimate 1.80.951.181.421.651.89

Each simulation's range: green caught the true value, red missed it

0.951.191.441.681.93
All numbers
true_value1.000
repeats50
simulated_rows1000
coverage0.000
expected_coverage0.950
lowest_acceptable_coverage0.858
mean_estimate1.799
bias0.799
rmse0.799
passedno

Made with whyflow.