{ "cells": [ { "cell_type": "markdown", "id": "title", "metadata": {}, "source": [ "# Three offers after discharge: g-formula and blip models\n", "\n", "## At a glance\n", "\n", "A hospital's navigators decide three times whether to offer a patient navigation: at discharge, on\n", "day 10, and on day 20. What would the average day-30 recovery score be if every patient got all\n", "three offers, against none? And how much does each single offer add?\n", "\n", "Offering all three times raises the average score by an estimated 10.66 points (95% confidence\n", "interval 9.49 to 11.82), from 49.37 to 60.03 on a scale of 0 to 100. This answer comes from the\n", "parametric g-formula, which simulates each patient's symptoms and score under each plan. A second\n", "method, the blip model, estimates each offer's effect: the discharge offer adds about 13.39 points\n", "for patients who live alone against 2.00 for the others, and the later offers about 2 to 4 each.\n", "\n", "Both answers depend on their models. With models of the symptom flags that are too simple, the g-formula\n", "reports 12.32 points and misses the true 11.22; it then disagrees with the blip model by 1.50\n", "points, a warning that one of them is off.\n", "\n", "Both answers are also causal only if the recorded characteristics and symptom flags capture\n", "everything that drove both the offers and the score, which the data cannot check.\n", "\n", "The data are simulated; the main fit's interval contains the true gain (11.22)." ] }, { "cell_type": "markdown", "id": "plan", "metadata": {}, "source": [ "## The question\n", "\n", "Navigators offer more often to patients who live alone, to patients with a high discharge risk,\n", "and to patients whose check-in before a later decision flags symptoms. The program lead asks for\n", "the mean day-30 score under the plan `always` (offer at all three decisions) against `never` (no\n", "offer), and for the effect of each single offer.\n", "\n", "In the graph, an arrow means \"causes\". $W$ is the baseline record (living alone and discharge\n", "risk), $A_1$, $A_2$, $A_3$ the three offers, $S_2$ and $S_3$ the symptom flags on days 10 and 20,\n", "$Y$ the day-30 score, and $U$ an unrecorded cause.\n", "\n", "```text\n", " W (lives alone, discharge risk) --> every offer and the score\n", " W (lives alone) --> S_2, S_3 (the symptom flags)\n", "\n", " A_1 (discharge) --> S_2 (symptoms, day 10) --> A_2 (day 10) --> S_3 (symptoms, day 20) --> A_3 (day 20)\n", " \\ \\ \\ \\ \\\n", " +-------------------------+------------------------+-----------------------+-----------------------+--> Y (score, day 30)\n", "\n", " U (unrecorded cause) - - -> the offers and Y (assumed absent)\n", "```\n", "\n", "A confounder is a cause of both an offer and the score. The symptom flags cause the difficulty. A\n", "flag is a reason for the next offer and lowers the score, so each later offer must be compared among\n", "patients with the same flags. But the earlier offer changed the flag: part of the discharge offer's\n", "effect works by preventing symptoms. Adjusting for both flags in one regression of the score would\n", "remove that part of the effect. Both methods below adjust each offer for the flags recorded before\n", "it and keep the early offers' effect through the later flags.\n", "\n", ":::{dropdown} Details: what each arrow and missing arrow asserts\n", "| arrow or absent arrow | what it asserts | role |\n", "| --- | --- | --- |\n", "| `W` to the offers and `Y` | living alone and discharge risk shape every offer, and both lower the score | baseline confounder |\n", "| `W` to `S_2`, `S_3` | patients who live alone have symptoms more often | baseline confounder |\n", "| `A_1` to `S_2`, `A_2` to `S_3` | the discharge offer lowers the chance of day-10 symptoms only for patients who live alone; the day-10 offer lowers day-20 symptoms a little for everyone and much more for them | the treatment changes a later confounder |\n", "| `S_2` to `A_2`, `S_3` to `A_3` | navigators offer more often after a symptom flag | a time-varying confounder |\n", "| `S_2`, `S_3` to `Y` | symptoms lower the day-30 score | the path through which early offers work |\n", "| offers to the next offer | a patient offered once is more likely to be offered again | part of the record the analysis adjusts for |\n", "| `U` absent | nothing unrecorded drives both an offer and the score | the assumption the data cannot check |\n", ":::" ] }, { "cell_type": "markdown", "id": "setup-heading", "metadata": {}, "source": [ "## Load the tools\n", "\n", "Every fit sets its seeds, so a rerun prints the same numbers. Another version of `cleverly` can\n", "print slightly different numbers." ] }, { "cell_type": "code", "execution_count": 1, "id": "setup", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:03:24.259621Z", "iopub.status.busy": "2026-11-13T23:03:24.259491Z", "iopub.status.idle": "2026-11-13T23:03:25.671255Z", "shell.execute_reply": "2026-11-13T23:03:25.670404Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "cleverly 0.2.4\n" ] } ], "source": [ "import dataclasses\n", "\n", "import pandas as pd\n", "\n", "import cleverly\n", "\n", "pd.set_option(\"display.width\", 130)\n", "pd.set_option(\"display.max_columns\", 20)\n", "print(\"cleverly\", cleverly.__version__)" ] }, { "cell_type": "markdown", "id": "data-heading", "metadata": {}, "source": [ "## The data\n", "\n", "`make_recovery_score` draws 4,000 simulated patients and also returns the true values, which real\n", "data never give you. The seed, 3100, was fixed before the page first ran, so the page could not\n", "pick a flattering draw." ] }, { "cell_type": "code", "execution_count": 2, "id": "data", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:03:25.673089Z", "iopub.status.busy": "2026-11-13T23:03:25.672530Z", "iopub.status.idle": "2026-11-13T23:03:25.779056Z", "shell.execute_reply": "2026-11-13T23:03:25.778182Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "rows and columns: (4000, 8)\n", "['lives_alone', 'discharge_risk', 'offer_discharge', 'symptoms_day10', 'offer_day10', 'symptoms_day20', 'offer_day20', 'recovery_day30']\n", " lives_alone discharge_risk offer_discharge symptoms_day10 offer_day10 symptoms_day20 offer_day20 recovery_day30\n", "0 1.0 0.53 1.0 1.0 1.0 0.0 0.0 42.42\n", "1 0.0 0.92 0.0 1.0 1.0 0.0 1.0 48.16\n", "2 0.0 0.11 0.0 0.0 0.0 0.0 1.0 68.09\n", "3 1.0 0.17 0.0 1.0 1.0 0.0 0.0 45.42\n", "4 0.0 0.50 0.0 1.0 0.0 1.0 0.0 23.23\n", "\n", "share of each group, by living situation:\n", " offer_discharge symptoms_day10 offer_day10 symptoms_day20\n", "lives_alone \n", "0.0 0.132 0.299 0.498 0.170\n", "1.0 0.624 0.426 0.672 0.128\n", "\n", "true values of the simulated data:\n", " ey_regimen[never] 49.24\n", " ey_regimen[always] 60.46\n", " ate_regimen[always vs never] 11.22\n" ] } ], "source": [ "from cleverly.datasets import make_recovery_score\n", "\n", "# With your own data, load a wide table here: one row per patient, with the baseline columns, then\n", "# for each decision what the navigator saw just before it (here a symptom flag) and the offer\n", "# (1 offered, 0 not), and the day-30 score last.\n", "# Real data have no `truth`, so drop every line that uses it.\n", "frame, truth = make_recovery_score(4_000, seed=3100)\n", "OFFERS = [\"offer_discharge\", \"offer_day10\", \"offer_day20\"] # the offer columns, in time order\n", "print(\"rows and columns:\", frame.shape)\n", "print(list(frame.columns))\n", "print(frame.head(5).round(2).to_string())\n", "print()\n", "print(\"share of each group, by living situation:\")\n", "by_group = frame.groupby(\"lives_alone\")\n", "shares = by_group[[\"offer_discharge\", \"symptoms_day10\", \"offer_day10\", \"symptoms_day20\"]].mean()\n", "print(shares.round(3).to_string())\n", "print()\n", "print(\"true values of the simulated data:\")\n", "for name in (\"ey_regimen[never]\", \"ey_regimen[always]\", \"ate_regimen[always vs never]\"):\n", " print(f\" {name:30s} {truth[name]:.2f}\")" ] }, { "cell_type": "markdown", "id": "data-reading", "metadata": {}, "source": [ "Each row is one patient: `lives_alone` (1 or 0), `discharge_risk` (0 to 1, higher is worse), then\n", "in time order the discharge offer, the day-10 symptom flag and offer, the day-20 flag and offer, and\n", "the day-30 score. The second table shows how unequal the offers are: 0.624 of the patients who live\n", "alone got the discharge offer, against 0.132 of the others. A name such as `ey_regimen[always]`\n", "reads: the expected (mean) score under the plan (`regimen`) `always`, and\n", "`ate_regimen[always vs never]` is the average effect, the difference of the two means." ] }, { "cell_type": "markdown", "id": "association-heading", "metadata": {}, "source": [ "## Why a simple comparison misleads\n", "\n", "A quick analysis would compare the patients who happened to get all three offers with those who\n", "got none." ] }, { "cell_type": "code", "execution_count": 3, "id": "association", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:03:25.780728Z", "iopub.status.busy": "2026-11-13T23:03:25.780215Z", "iopub.status.idle": "2026-11-13T23:03:25.789592Z", "shell.execute_reply": "2026-11-13T23:03:25.788642Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " offered all three times never offered\n", "patients 495.000 812.000\n", "lives alone 0.754 0.110\n", "discharge risk 0.638 0.389\n", "symptoms on day 10 0.315 0.240\n", "mean score on day 30 55.987 57.815\n", "\n", "difference in mean score: -1.83 true effect of always against never: 11.22\n" ] } ], "source": [ "# This cell only shows why a simple comparison misleads, so you can skip it on your own data.\n", "groups = {\n", " \"offered all three times\": frame[(frame[OFFERS] == 1).all(axis=1)],\n", " \"never offered\": frame[(frame[OFFERS] == 0).all(axis=1)],\n", "}\n", "summary = pd.DataFrame(\n", " {\n", " label: {\n", " \"patients\": len(rows),\n", " \"lives alone\": rows[\"lives_alone\"].mean(),\n", " \"discharge risk\": rows[\"discharge_risk\"].mean(),\n", " \"symptoms on day 10\": rows[\"symptoms_day10\"].mean(),\n", " \"mean score on day 30\": rows[\"recovery_day30\"].mean(),\n", " }\n", " for label, rows in groups.items()\n", " }\n", ")\n", "print(summary.round(3).to_string())\n", "scores = summary.loc[\"mean score on day 30\"]\n", "crude = scores[\"offered all three times\"] - scores[\"never offered\"]\n", "print()\n", "print(\n", " f\"difference in mean score: {crude:.2f} true effect of always against never: \"\n", " f\"{truth['ate_regimen[always vs never]']:.2f}\"\n", ")" ] }, { "cell_type": "markdown", "id": "association-reading", "metadata": {}, "source": [ "The simple difference is -1.83 points: offered patients seem to do worse, while the true effect is\n", "a gain of 11.22. The offered patients are not like the others. Three in four live alone (0.754\n", "against 0.110), their discharge risk is higher (0.638 against 0.389), and more of them had\n", "symptoms on day 10, which is part of why they were offered again. Those patients would score lower\n", "under any plan." ] }, { "cell_type": "markdown", "id": "protocol-heading", "metadata": {}, "source": [ "## Write down the study design\n", "\n", "The study description (`StudyProtocol`) says who is in the study, when follow-up starts, the\n", "plans, the outcome, and how events after the start count. It is optional, but `CausalStudy` stores\n", "it with every result, so whoever reads your result later sees exactly what was estimated." ] }, { "cell_type": "code", "execution_count": 4, "id": "protocol", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:03:25.791128Z", "iopub.status.busy": "2026-11-13T23:03:25.790716Z", "iopub.status.idle": "2026-11-13T23:03:25.795961Z", "shell.execute_reply": "2026-11-13T23:03:25.795244Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Population: Adults discharged home from a participating hospital during the enrollment period\n", "Eligibility: Age 18 years or older; Discharged alive; Discharged home from a participating hospital\n", "Follow-up starts: Hospital discharge, after baseline measurement and before first assignment\n", "Strategies: Offer navigation at discharge, on day 10 and on day 20; Offer no navigation at any of the three decisions\n", "Versions: The declared navigation contact at each of the three decisions; Usual discharge support without navigation contacts\n", "Outcome: Patient-reported recovery score on day 30, on a scale from 0 to 100\n", "Horizon: 30 days after discharge\n", "Intercurrent events: Every patient completes the day-30 score, so no patient leaves follow-up; The protocol scores death before day 30 as 0 (composite strategy); Analyze each navigation offer regardless of completed contacts\n", "Interference unit: Individual patient\n", "Rationale: The navigator reads only the recorded discharge risk, living situation, symptom flags and earlier offers, which supports no hidden confounding at each decision; Version records support that the navigation contact at each of the three decisions is one well-defined action, so a patient's recorded score is the score they would have had under the offers they got; Reserved navigator capacity supports no interference between patients\n" ] } ], "source": [ "from cleverly.datasets import recovery_score_protocol\n", "\n", "# For your own study, build cleverly.StudyProtocol(target_population=..., eligibility=(...),\n", "# time_zero=..., treatment_strategies=(...), treatment_versions=(...), outcome=..., horizon=...,\n", "# intercurrent_event_handling=(...), interference_unit=..., assumption_rationale=(...)).\n", "# Each field is plain text, and a tuple holds several sentences; the printed lines below are\n", "# this study's values, a model for your own.\n", "protocol = recovery_score_protocol()\n", "print(\"\\n\".join(protocol.summary_lines()))" ] }, { "cell_type": "markdown", "id": "protocol-reading", "metadata": {}, "source": [ "Follow-up starts at discharge, before the first offer, so no offer changes who is in\n", "the study. \"Intercurrent events\" are events after the start that could change what the score means:\n", "every patient completes the score, and a death before day 30 would count as a score of 0 (nobody\n", "dies in the simulated data). \"Versions\" says what one offer is, so that every patient's offer means\n", "the same contact; the rationale gives the reason to believe three of the conditions the next\n", "section lists, and the fourth, overlap, is probed from the data." ] }, { "cell_type": "markdown", "id": "identify-heading", "metadata": {}, "source": [ "## Columns, plans, and what must hold\n", "\n", "`LongitudinalTreatment` names the columns of the wide table: one offer per decision, and the\n", "columns recorded before each one. A plan (a \"regime\" or \"regimen\" in the output) is a tuple with\n", "one offer per decision. `study.identify` with `RegimeMean` checks which methods can estimate the\n", "mean score under each plan from these columns, and lists what must hold for the answer to be\n", "causal. A \"unit\" in the output is a patient." ] }, { "cell_type": "code", "execution_count": 5, "id": "identify", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:03:25.797073Z", "iopub.status.busy": "2026-11-13T23:03:25.796951Z", "iopub.status.idle": "2026-11-13T23:03:25.820923Z", "shell.execute_reply": "2026-11-13T23:03:25.820272Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " Causal question (ey_regime)\n", "==============================================================================\n", "Question: mean outcome under each Rows: 4,000\n", " declared regime Answered by: adjusting for history\n", "Outcome: recovery_day30\n", " (continuous)\n", "Treatment: offer_discharge,\n", " offer_day10, offer_day20\n", "Baseline: lives_alone,\n", " discharge_risk\n", "==============================================================================\n", "What each treatment time adjusts for\n", "treatment adjusted for\n", "------------------------------------------------------------------------------\n", "offer_discharge lives_alone, discharge_risk\n", "offer_day10 lives_alone, discharge_risk, symptoms_day10, offer_discharge\n", "offer_day20 lives_alone, discharge_risk, symptoms_day10, symptoms_day20,\n", " offer_discharge, offer_day10\n", "==============================================================================\n", "Conditions the answer rests on\n", "condition checkable what it says\n", "------------------------------------------------------------------------------\n", "well-defined treatment no Each unit's observed outcomes\n", " are the ones it would have\n", " had under the treatments it\n", " actually received over time.\n", " This needs each treatment to\n", " be well defined: every way of\n", " getting the same treatment\n", " has the same effect.\n", "no interference no One unit's treatment does not\n", " change another unit's\n", " outcome.\n", "no hidden confounding at each time no At each time, among units\n", " with the same recorded\n", " history, which treatment a\n", " unit got is unrelated to the\n", " outcomes it would have had.\n", "overlap at each time partly At each time, units with\n", " every history that following\n", " the compared regimens can\n", " produce had some chance of\n", " the treatment a regimen\n", " assigns.\n", "==============================================================================\n", "Methods\n", "method name\n", "------------------------------------------------------------------------------\n", "tmle targeted maximum likelihood (TMLE)\n", "sdr sequentially doubly robust regression (SDR)\n", "ipsi incremental propensity score intervention (IPSI)\n", "gcomp sequential g-computation\n", "ipw sequential inverse probability weighting\n", "parametric_gformula parametric g-formula\n", "==============================================================================\n", "Notes:\n", "[1] The data cannot confirm these conditions. Overlap (marked partly) can be\n", " probed: after a fit, result.diagnostics.support() shows where the fitted\n", " treatment model gives units little chance of a compared treatment. That\n", " check reads a fitted model, so a clean result does not prove overlap.\n", "[2] The methods table lists the methods that fit. 6 other methods cannot\n", " estimate this question; the full summary says why.\n" ] } ], "source": [ "from cleverly import CausalStudy, LongitudinalTreatment, RegimeMean\n", "\n", "# For your own data, change the column names: one offer column per decision, in time order, and\n", "# for each decision the columns recorded just before it.\n", "design = LongitudinalTreatment(\n", " outcome=\"recovery_day30\",\n", " treatment=(\"offer_discharge\", \"offer_day10\", \"offer_day20\"),\n", " baseline=(\"lives_alone\", \"discharge_risk\"),\n", " time_varying=((), (\"symptoms_day10\",), (\"symptoms_day20\",)),\n", ")\n", "plans = {\"never\": (0, 0, 0), \"always\": (1, 1, 1)} # one offer per decision\n", "study = CausalStudy(frame, design=design, protocol=protocol)\n", "question = study.identify(RegimeMean(plans, reference=\"never\"))\n", "print(question.summary())" ] }, { "cell_type": "markdown", "id": "identify-reading", "metadata": {}, "source": [ "Each offer is adjusted for the flags recorded before it. In plain words, the conditions are that an\n", "offer means the same contact for every patient, that one patient's offers do not change another's\n", "score, that at each decision nothing unrecorded drives both the offer and the score, and that\n", "patients with every record the plans can produce had a real chance of the plan's offer (overlap).\n", "The first three need judgment; \"Check overlap\" probes the fourth.\n", "\n", "This page fits the parametric g-formula (`parametric_gformula`) and the blip model, a separate tool\n", "(`snmm()`) that gives each offer's effect. Both show how the offers work, at the price that more of\n", "their models must be right. For the plan means alone, TMLE (in the [weekly outcomes\n", "example](weekly-outcomes.ipynb)) needs only all its offer models or all its score models right, and\n", "no form for the effects." ] }, { "cell_type": "markdown", "id": "gformula-heading", "metadata": {}, "source": [ "## The main answer: simulate each plan forward\n", "\n", "The parametric g-formula fits a model for each symptom flag from the record before it, and a\n", "model for the score from the whole record. Then it copies each\n", "patient, sets the offers to the plan's values, and walks the copy forward in time: it draws the\n", "day-10 flag from its model, then the day-20 flag, then predicts the score. The mean of the\n", "predicted scores is the plan's mean. Because the simulated flags respond to the plan's offers,\n", "every route from an early offer to the score stays in the answer.\n", "\n", "The price is that the symptom models and the score model must all be right. Here the symptom\n", "models include every product of two record columns, so an offer's effect on symptoms can differ by\n", "living situation. On your own data, allow such products and compare with a second method. For fixed plans like these the simulation\n", "reads no offer model (note [2]'s \"natural-treatment model\"); only the overlap check does." ] }, { "cell_type": "code", "execution_count": 6, "id": "gformula", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:03:25.822334Z", "iopub.status.busy": "2026-11-13T23:03:25.821879Z", "iopub.status.idle": "2026-11-13T23:03:26.733652Z", "shell.execute_reply": "2026-11-13T23:03:26.732804Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " Longitudinal estimate (parametric g-formula)\n", "==============================================================================\n", "Question: recovery_day30 under Rows: 4,000\n", " each plan; each row is Time points: 3\n", " defined below Out-of-fold predictions: no\n", "Outcome: recovery_day30 Outcome model: generalized linear\n", " (continuous), at the model\n", " end Covariate models: generalized linear\n", "Treatment: offer_discharge, model for 2\n", " offer_day10, covariates\n", " offer_day20\n", "Adjusted for: lives_alone,\n", " discharge_risk; later:\n", " symptoms_day10,\n", " symptoms_day20\n", "Method: parametric g-formula\n", " (forward simulation)\n", "==============================================================================\n", " estimate std. error 95% CI p-value\n", "------------------------------------------------------------------------------\n", "ey_regimen[never] 49.37 0.36 [48.66, 50.06] <0.0001\n", "ey_regimen[always] 60.03 0.48 [59.08, 60.96] <0.0001\n", "==============================================================================\n", "What each row estimates\n", " meaning\n", "------------------------------------------------------------------------------\n", "ey_regimen[never] mean recovery_day30 if every unit followed plan never\n", "ey_regimen[always] mean recovery_day30 if every unit followed plan always\n", "==============================================================================\n", "What each plan assigns and who followed it to the end\n", "plan followed in data assigns\n", "------------------------------------------------------------------------------\n", "never 812 of 4,000 0 at every time point\n", "always 495 of 4,000 1 at every time point\n", "==============================================================================\n", "Simultaneous 95% bands\n", " band\n", "------------------------------------------------------------------------------\n", "ey_regimen[never] [48.58, 50.15]\n", "ey_regimen[always] [58.98, 61.08]\n", "==============================================================================\n", "Notes:\n", "[1] The interval of ey_regimen[never], ey_regimen[always] is widened on the\n", " side where a skewed outcome makes misses more likely, so it need not be\n", " centred on the estimate. Its t distribution has 250 or more degrees of\n", " freedom, so it is close to the normal one. The p-value is the level at\n", " which the interval would just reach the null value.\n", "[2] The bands cover all 2 rows at once with 95% probability; use them when you\n", " read several rows together. No validation study covers the bands for this\n", " kind of fit, so cleverly marks them experimental.\n", "[3] The interval holds only if every covariate model, outcome (or\n", " event-hazard) model and natural-treatment model the simulation reads is\n", " correctly specified. It includes the simulation error.\n" ] } ], "source": [ "from cleverly import ModelSpec, ParametricGFormulaMethod, Runtime\n", "from cleverly.learners import GLM\n", "\n", "gformula = ParametricGFormulaMethod(\n", " models=ModelSpec(\n", " outcome_learner=GLM(family=\"gaussian\"), # the day-30 score: linear regression\n", " treatment_learner=GLM(), # each offer: logistic regression, read by the overlap check\n", " ),\n", " # Each symptom flag: logistic regression with every product of two record columns, so the\n", " # offer's effect on symptoms can differ by living situation.\n", " covariate_learner=GLM(interactions=2),\n", " n_draws=10, # simulated copies of each patient under each plan\n", " runtime=Runtime(random_state=3100, n_jobs=1), # fix the seed of the simulation\n", ")\n", "result = question.estimate(method=gformula)\n", "print(result.summary())" ] }, { "cell_type": "markdown", "id": "gformula-reading", "metadata": {}, "source": [ "The two rows are the plan means. The p-values test a mean score of zero, which nobody asks, so\n", "ignore them here. \"Followed in data\" counts the patients whose actual offers matched each plan.\n", "The\n", "simultaneous bands are not needed, because the next cell compares the two plans directly." ] }, { "cell_type": "code", "execution_count": 7, "id": "gformula-plans", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:03:26.735319Z", "iopub.status.busy": "2026-11-13T23:03:26.735169Z", "iopub.status.idle": "2026-11-13T23:03:26.746198Z", "shell.execute_reply": "2026-11-13T23:03:26.745497Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " estimate ci_low ci_high truth covers\n", "ey_regimen[never] 49.37 48.66 50.06 49.24 True\n", "ey_regimen[always] 60.03 59.08 60.96 60.46 True\n", "ate_regimen[always vs never] 10.66 9.49 11.82 11.22 True\n", "\n", "support: ['supported']\n", "\n", "share of each variance that comes from the simulation:\n", " ey_regimen[never] 2.7%\n", " ey_regimen[always] 1.2%\n", " ate_regimen[always vs never] 0.5%\n" ] } ], "source": [ "LEVELS = [\"ey_regimen[never]\", \"ey_regimen[always]\"]\n", "# contrast() takes the difference of the two plan means with their joint uncertainty.\n", "difference = result.contrast(\n", " lambda means: means[1] - means[0], LEVELS, name=\"ate_regimen[always vs never]\"\n", ")\n", "\n", "\n", "# against_truth needs the true values, so on your own data read result.summary() instead.\n", "def against_truth(estimates):\n", " rows = {}\n", " for estimate in estimates:\n", " low, high = estimate.ci\n", " rows[estimate.name] = {\n", " \"estimate\": estimate.psi,\n", " \"ci_low\": low,\n", " \"ci_high\": high,\n", " \"truth\": truth[estimate.name],\n", " \"covers\": bool(low <= truth[estimate.name] <= high),\n", " }\n", " return pd.DataFrame(rows).T.astype(\n", " {\"estimate\": float, \"ci_low\": float, \"ci_high\": float, \"truth\": float}\n", " )\n", "\n", "\n", "print(against_truth([result[key] for key in LEVELS] + [difference]).round(2).to_string())\n", "print()\n", "print(\"support:\", sorted({result[key].support.label for key in LEVELS}))\n", "print()\n", "shares = result.simulation.monte_carlo_share\n", "print(\"share of each variance that comes from the simulation:\")\n", "for name, share in shares.items():\n", " print(f\" {name:30s} {share:.1%}\")" ] }, { "cell_type": "markdown", "id": "gformula-plans-reading", "metadata": {}, "source": [ "Against the truth, all three intervals hold, and the gain of `always` over `never` is 10.66 points\n", "(9.49 to 11.82); `result.contrast` accounts for the two means sharing patients. The means and their difference read `supported`: a simulation study checks this kind of\n", "fit (\"How we know the method works\" at the end).\n", "\n", "The simulation adds noise, because each patient is copied only ten times (`n_draws=10`). The\n", "interval includes it, and the last lines show its share of each variance, under 3% here and\n", "smallest for the difference, since both plans reuse the same random draws. Above 10%, `cleverly`\n", "warns; raise `n_draws` then.\n", "\n", ":::{dropdown} Details: the page's 400 repeated draws\n", "A simulation we ran for this page (script\n", "`reviews/notebook-review/probes/model-based-over-time/sweep.py` in the repository) repeats the\n", "page's fits on 400 draws, seeds 3100 to 3499. The g-formula intervals held the true value on 373\n", "of 400 draws for `never`, 381 for `always`, and 377 for the difference. A correct 95% interval\n", "gives about 380, and chance alone moves the count between about 371 and 388. The\n", "simulation's share of the variance was at most 3.0% for a plan mean and 0.7% for the difference.\n", ":::" ] }, { "cell_type": "markdown", "id": "failure-heading", "metadata": {}, "source": [ "## What goes wrong when the symptom models are too simple\n", "\n", "The default symptom model (`covariate_learner=None`) is a logistic regression on the record\n", "columns with no products. It assumes the discharge offer changes the log-odds of symptoms equally\n", "for every patient. In these data the offer prevents symptoms mainly\n", "among patients who live alone, who were also the ones offered, so the default model carries their\n", "effect to everyone." ] }, { "cell_type": "code", "execution_count": 8, "id": "failure-mode", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:03:26.747795Z", "iopub.status.busy": "2026-11-13T23:03:26.747329Z", "iopub.status.idle": "2026-11-13T23:03:27.514085Z", "shell.execute_reply": "2026-11-13T23:03:27.513134Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "main-terms symptom models:\n", " estimate ci_low ci_high truth covers\n", "ey_regimen[never] 50.05 49.4 50.70 49.24 False\n", "ey_regimen[always] 62.38 61.7 63.04 60.46 False\n", "ate_regimen[always vs never] 12.32 11.3 13.34 11.22 False\n", "\n", "support: ['supported']\n" ] } ], "source": [ "# This check needs the true values, so it runs only on simulated data. covariate_learner=None is\n", "# the default: main-terms logistic models, with no product of two columns.\n", "wrong = question.estimate(method=dataclasses.replace(gformula, covariate_learner=None))\n", "wrong_difference = wrong.contrast(\n", " lambda means: means[1] - means[0], LEVELS, name=\"ate_regimen[always vs never]\"\n", ")\n", "print(\"main-terms symptom models:\")\n", "print(against_truth([wrong[key] for key in LEVELS] + [wrong_difference]).round(2).to_string())\n", "print()\n", "print(\"support:\", sorted({wrong[key].support.label for key in LEVELS}))" ] }, { "cell_type": "markdown", "id": "failure-reading", "metadata": {}, "source": [ "With the default symptom models, all three intervals miss: the mean under `always` is 62.38 (61.70\n", "to 63.04) against a true 60.46, and the gain is 12.32 against 11.22. The fit still reads\n", "`supported`, because the label describes the kind of fit, not whether your models match your data.\n", "On real data no truth is printed, so you need a second method that rests on different models.\n", "\n", ":::{dropdown} Details: the wrong models over 400 draws\n", "In the page's simulation, the interval for the mean under `always` missed the truth on all 400\n", "draws, and the interval for the gain held it on only 71 of 400. The wrong models overstate the\n", "mean under `always` by 2.26 points on average.\n", ":::" ] }, { "cell_type": "markdown", "id": "snmm-heading", "metadata": {}, "source": [ "## What each offer adds\n", "\n", "A structural nested mean model (`snmm()`, \"the blip model\" below) answers the second question. It\n", "estimates the effect of one offer with the later offers set to no offer, called a \"blip\", and lets\n", "that effect depend on columns you name, here living alone at the first two decisions. It fits models of\n", "the offers and of the score, but none of the symptom flags. Each row's predictions come from models\n", "trained without that row (`n_folds=5`), as in cross-validation.\n", "\n", "Its own conditions are that the models of who is offered are right, and that the blips are linear\n", "in the named columns: an offer's effect may differ by living situation, but not, say, by the day-10\n", "flag." ] }, { "cell_type": "code", "execution_count": 9, "id": "snmm", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:03:27.515863Z", "iopub.status.busy": "2026-11-13T23:03:27.515333Z", "iopub.status.idle": "2026-11-13T23:03:28.006864Z", "shell.execute_reply": "2026-11-13T23:03:28.006325Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "effect of one offer, with the later offers set to no offer, in score points:\n", " effect ci_low ci_high truth\n", "offer lives_alone \n", "offer_discharge 0 2.00 0.60 3.36 2.0\n", " 1 13.39 12.18 14.59 14.1\n", "offer_day10 0 2.15 1.57 2.73 2.0\n", " 1 3.84 3.00 4.68 4.8\n", "offer_day20 0 2.10 1.79 2.40 2.0\n", " 1 2.10 1.79 2.40 2.0\n", "\n", "share of patients who live alone: 0.350\n", "part of the gain of always over never, by offer and group:\n", "lives_alone 0 1 both groups\n", "offer \n", "offer_discharge 1.30 4.69 5.98\n", "offer_day10 1.40 1.34 2.74\n", "offer_day20 1.36 0.73 2.10\n", "total: 10.82\n", "\n", "support: ['supported']\n" ] } ], "source": [ "from cleverly.datasets import RECOVERY_BOUNDS\n", "from cleverly.longitudinal import snmm\n", "\n", "# For your own data, change the column names, and list in FEATURES the baseline columns that you\n", "# expect to change how much an offer helps. Here decisions 1 and 2 may depend on lives_alone, and\n", "# decision 3 has one effect for all.\n", "FEATURES = {1: [\"lives_alone\"], 2: [\"lives_alone\"]}\n", "blips = snmm(\n", " frame,\n", " outcome=\"recovery_day30\",\n", " treatment=list(OFFERS),\n", " baseline=[\"lives_alone\", \"discharge_risk\"],\n", " time_varying=[[], [\"symptoms_day10\"], [\"symptoms_day20\"]],\n", " regimens=plans,\n", " reference=\"never\",\n", " blip_features=FEATURES,\n", " outcome_learner=GLM(family=\"gaussian\"),\n", " treatment_learner=GLM(family=\"binomial\"),\n", " n_folds=5, # out-of-fold predictions, as in cross-validation\n", " random_state=3100,\n", ")\n", "# Each effect is named blip[offer column:offer value:column it depends on]; \"intercept\" is the\n", "# effect for a patient with that column at 0. Offers coded 1 appear as 1.0. The loop reads the\n", "# names from FEATURES and assumes one 0-or-1 feature, lives_alone; adapt it for others.\n", "effect_rows = []\n", "for node, column in enumerate(OFFERS, start=1):\n", " names = [f\"blip[{column}:1.0:{feature}]\" for feature in [\"intercept\", *FEATURES.get(node, [])]]\n", " for alone in (0, 1):\n", " # The effect for a patient who lives alone adds the lives_alone term to the intercept.\n", " effect = blips.contrast(lambda values, a=alone: values[0] + a * sum(values[1:]), names)\n", " effect_rows.append(\n", " {\n", " \"offer\": column,\n", " \"lives_alone\": alone,\n", " \"effect\": effect.psi,\n", " \"ci_low\": effect.ci[0],\n", " \"ci_high\": effect.ci[1],\n", " \"truth\": truth[names[0]] + alone * sum(truth[name] for name in names[1:]),\n", " }\n", " )\n", "effects = pd.DataFrame(effect_rows).set_index([\"offer\", \"lives_alone\"])\n", "print(\"effect of one offer, with the later offers set to no offer, in score points:\")\n", "print(effects.round(2).to_string())\n", "print()\n", "# When the effects depend only on baseline columns, the gain of always over never is the\n", "# patients' average of the three effects. Each offer's part is its effect with the earlier offers\n", "# given and the later ones off, weighted by the share of patients in each group.\n", "alone_share = frame[\"lives_alone\"].mean()\n", "parts = effects[\"effect\"].unstack().reindex(OFFERS) * [1 - alone_share, alone_share]\n", "print(f\"share of patients who live alone: {alone_share:.3f}\")\n", "print(\"part of the gain of always over never, by offer and group:\")\n", "parts[\"both groups\"] = parts.sum(axis=1)\n", "print(parts.round(2).to_string())\n", "print(f\"total: {parts['both groups'].sum():.2f}\")\n", "print()\n", "print(\"support:\", sorted({estimate.support.label for estimate in blips.estimates.values()}))" ] }, { "cell_type": "markdown", "id": "snmm-reading", "metadata": {}, "source": [ "The discharge offer adds far more for a patient who lives alone, because it prevents day-10\n", "symptoms mainly among them. The day-20 offer has one declared effect, so its two rows repeat. Of the five distinct effects, four intervals hold their true\n", "values; the day-10 effect for patients who live alone (3.00 to 4.68) misses the true 4.8, ordinary\n", "sampling variation for one interval among several (Details).\n", "\n", "Because these effects depend only on living alone, the gain of `always` over `never` is the\n", "patients' average of the three effects, each with the earlier offers given and the later ones off.\n", "The discharge offer carries 5.98 of the 10.82 points, 4.69 of them from patients who live alone,\n", "though they are only 0.350 of the patients.\n", "\n", ":::{dropdown} Details: the blip model over 400 draws\n", "In the page's simulation, the effect intervals held their true values on 373 to 384 of 400\n", "draws (95% would be 380), and the average error of each was within 0.05 points of zero.\n", ":::" ] }, { "cell_type": "markdown", "id": "compare-heading", "metadata": {}, "source": [ "## Compare the two methods\n", "\n", "The blip model also reports the two plan means, derived from its effects, so they can sit beside\n", "both g-formula fits. `check_model()` then tests the blip model against a third method." ] }, { "cell_type": "code", "execution_count": 10, "id": "compare", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:03:28.008245Z", "iopub.status.busy": "2026-11-13T23:03:28.008117Z", "iopub.status.idle": "2026-11-13T23:03:28.670910Z", "shell.execute_reply": "2026-11-13T23:03:28.670339Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " g-formula g-formula, simple symptom models blip model truth\n", "ey_regimen[never] 49.37 50.05 49.46 49.24\n", "ey_regimen[always] 60.03 62.38 60.29 60.46\n", "ate_regimen[always vs never] 10.66 12.32 10.82 11.22\n", "gain of g-formula minus the blip model's: -0.16\n", "gain of g-formula, simple symptom models minus the blip model's: 1.50\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "always minus never, blip model: 10.80\n", "always minus never, method with no model of the effect (LTMLE): 10.41\n", "test of agreement: p = 0.29\n", "support: experimental\n" ] } ], "source": [ "comparison = pd.DataFrame(\n", " {\n", " \"g-formula\": [result[key].psi for key in LEVELS] + [difference.psi],\n", " \"g-formula, simple symptom models\": [wrong[key].psi for key in LEVELS]\n", " + [wrong_difference.psi],\n", " \"blip model\": [blips[key].psi for key in LEVELS]\n", " + [blips[\"ate_regimen[always vs never]\"].psi],\n", " \"truth\": [truth[key] for key in LEVELS] + [truth[\"ate_regimen[always vs never]\"]],\n", " },\n", " index=[*LEVELS, \"ate_regimen[always vs never]\"],\n", ")\n", "print(comparison.round(2).to_string())\n", "gain = comparison.loc[\"ate_regimen[always vs never]\"]\n", "for fit in (\"g-formula\", \"g-formula, simple symptom models\"):\n", " print(f\"gain of {fit} minus the blip model's: {gain[fit] - gain['blip model']:.2f}\")\n", "print()\n", "check = blips.check_model(q_bounds=RECOVERY_BOUNDS) # your score's known range, here (0, 100)\n", "print(\"always minus never, blip model:\", f\"{check.structural[0]:.2f}\")\n", "print(\n", " \"always minus never, method with no model of the effect (LTMLE):\",\n", " f\"{check.nonparametric[0]:.2f}\",\n", ")\n", "print(f\"test of agreement: p = {check.pvalue:.2f}\")\n", "print(\"support:\", check.support.label)" ] }, { "cell_type": "markdown", "id": "compare-reading", "metadata": {}, "source": [ "The two methods lean on different models: the g-formula on the symptom and score models, the blip\n", "model on the offer models and the linear effects. With products in its symptom models, the\n", "g-formula agrees with the blip model to within 0.3 points; with simple ones its gain sits 1.50\n", "points higher, more than half the width of the g-formula's interval. No exact test of such a gap exists, but\n", "on these data the page's 400 draws separate the two cases cleanly (Details). Treat a gap that large\n", "as a warning that one method is off: try richer symptom models, and run the check below. Agreement cannot catch a hidden cause that both methods miss, because\n", "both adjust for the same recorded columns. Choose the method you report before you look; this page\n", "reports the g-formula, which estimates the plan means directly.\n", "\n", "`check_model()` tests the blip model against longitudinal TMLE (LTMLE). LTMLE fits models of the\n", "offers and the score, then corrects the score model's answer with the offer models; it assumes no\n", "form for the effects, and it needs the score's known range (`q_bounds`) because it works on a 0-to-1\n", "scale and, fitted in folds, cannot take that scale from the observed scores. It fits\n", "both methods on the same rows and on five random fold splits, and compares the averages. The two gains, 10.80 for the blip model (its single fit gave\n", "10.82) and 10.41 for LTMLE, agree (p = 0.29). A small p-value would say that the linear effects are\n", "wrong; a large one does not prove them right. The check reads `experimental`: no simulation study\n", "covers it for this kind of fit.\n", "\n", ":::{dropdown} Details: the two methods and the model check over 400 draws\n", "In the page's simulation, the gain of the g-formula with products differed from the blip model's by\n", "at most 0.43 points, while the gain with simple symptom models sat at least 0.96 points above it,\n", "and more than 1.165, half the width of the page's interval, on 380 of 400 draws. The linear effects are right in\n", "these data, and the check gave p below 0.05 on 23 of 400 draws, close to the 5% a correct check\n", "should give.\n", ":::" ] }, { "cell_type": "markdown", "id": "assessment-heading", "metadata": {}, "source": [ "## Check overlap\n", "\n", "Overlap still matters for the g-formula: where few patients followed a plan, its models must\n", "extrapolate. `assess()` uses the g-formula fit's offer models to count how many patients followed\n", "each plan and how much weight each would need to stand in for all patients." ] }, { "cell_type": "code", "execution_count": 11, "id": "assessment", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:03:28.672538Z", "iopub.status.busy": "2026-11-13T23:03:28.672298Z", "iopub.status.idle": "2026-11-13T23:03:28.713509Z", "shell.execute_reply": "2026-11-13T23:03:28.712810Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "checks that need attention: none\n", " Overlap over time\n", "==============================================================================\n", "Regimens: 2 Result: no pass or fail\n", "Time points: 3\n", "==============================================================================\n", "regimen time rows max weight eff. rows capped assigned\n", "------------------------------------------------------------------------------\n", "never 1 2,783 3.78 2326.1 0.000 0.000\n", "never 2 1,348 25.27 703.6 0.000 0.000\n", "never 3 812 60.46 307.1 0.000 0.000\n", "always 1 1,217 12.36 691.8 0.000 1.000\n", "always 2 801 34.16 381.6 0.000 1.000\n", "always 3 495 63.48 206.5 0.000 1.000\n", "==============================================================================\n", "Overlap is thinnest for always at time 3: 206.5 effective rows of 495\n", "followed.\n", "Notes:\n", "[1] rows counts the units that followed the regimen and stayed observed\n", " through the time point. max weight and eff. rows describe the cumulative\n", " weight: one over the product of the treatment and censoring probabilities\n", " up to that time point, times the observation weight on a weighted fit. A\n", " product can be extreme while every time point looks fine. capped is the\n", " share of rows whose cumulative probability the lower limit replaced.\n", "[2] assigned is the share of the units at risk at that time point whom the\n", " regimen treats; a regimen that names one arm assigns exactly 0 or 1.\n" ] } ], "source": [ "assessment = result.assess()\n", "attention = tuple(item.name for item in assessment.attention)\n", "print(\"checks that need attention:\", attention or \"none\")\n", "print(assessment.report(\"support\").summary())" ] }, { "cell_type": "markdown", "id": "assessment-reading", "metadata": {}, "source": [ "Overlap is thinnest for `always` at the third decision, where the 495\n", "followers count as about 206.5 equally weighted patients, 42% of them. On your own data, worry when that share falls to a few percent." ] }, { "cell_type": "markdown", "id": "refutation-heading", "metadata": {}, "source": [ "## Try to break the result\n", "\n", "These checks change the data in a known way and refit the blip model's gain of `always` 20 times\n", "each. They use the blip model because it reports the gain as one estimate. The placebo swaps in\n", "random offers, so the gain should be about zero. The random common cause adds a column of pure\n", "noise, so the gain should barely move. The subset check refits on random 70% samples, whose gains\n", "should spread as the standard error predicts. None can detect a hidden cause." ] }, { "cell_type": "code", "execution_count": 12, "id": "refute", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:03:28.714702Z", "iopub.status.busy": "2026-11-13T23:03:28.714571Z", "iopub.status.idle": "2026-11-13T23:03:33.423309Z", "shell.execute_reply": "2026-11-13T23:03:33.422327Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " test original refuted_mean refuted_sd expectation verdict\n", " placebo 10.824 0.128 0.537 ~ 0 descriptive\n", " subset 10.824 10.644 0.390 scatter ~ 0.3788 descriptive\n", "random_common_cause 10.824 10.822 0.015 ~ 10.82 descriptive\n", "\n", "placebo: t = 1.065\n", "subset: scatter ratio rho = 1.028\n", "random_common_cause: paired shift in standard errors = -0.003\n" ] } ], "source": [ "from cleverly.validation import refute\n", "\n", "refutation = refute(\n", " blips,\n", " estimand=\"ate_regimen[always vs never]\",\n", " tests=(\"placebo\", \"subset\", \"random_common_cause\"),\n", " n_replicates=20,\n", ")\n", "columns = [\"test\", \"original\", \"refuted_mean\", \"refuted_sd\", \"expectation\", \"verdict\"]\n", "print(refutation.to_frame()[columns].round(3).to_string(index=False))\n", "print()\n", "for test in refutation.tests:\n", " if test.statistic_name:\n", " print(f\"{test.name}: {test.statistic_name} = {test.statistic:.3f}\")" ] }, { "cell_type": "markdown", "id": "refute-reading", "metadata": {}, "source": [ "None of the three raises a concern. The placebo refits average about zero (`t` 1.065, well inside\n", "2), the noise column leaves the gain unchanged to two decimals, and the 70% refits spread about as\n", "predicted (`rho` 1.028, ideal 1). `descriptive` means no simulation study backs a pass or fail, so\n", "you judge the numbers." ] }, { "cell_type": "markdown", "id": "sensitivity-heading", "metadata": {}, "source": [ "## What if a confounder is missing?\n", "\n", "`cleverly` has no bound for how strong a hidden cause must be to change an answer over time, so the\n", "code drops one recorded covariate at a time, refits both methods, and reports how far the gain\n", "moves, in standard errors." ] }, { "cell_type": "code", "execution_count": 13, "id": "sensitivity", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:03:33.424974Z", "iopub.status.busy": "2026-11-13T23:03:33.424802Z", "iopub.status.idle": "2026-11-13T23:03:35.876036Z", "shell.execute_reply": "2026-11-13T23:03:35.874329Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "move of always minus never, in standard errors of the full fit:\n", " g-formula move blip model move\n", "dropped \n", "without discharge risk -6.26 -6.57\n", "without symptom flags -7.36 -10.83\n" ] } ], "source": [ "# For your own data, drop each recorded covariate in turn. lives_alone stays, because the\n", "# blips read it.\n", "reduced = {\n", " \"without discharge risk\": {\n", " \"baseline\": (\"lives_alone\",),\n", " \"time_varying\": ((), (\"symptoms_day10\",), (\"symptoms_day20\",)),\n", " },\n", " \"without symptom flags\": {\n", " \"baseline\": (\"lives_alone\", \"discharge_risk\"),\n", " \"time_varying\": ((), (), ()),\n", " },\n", "}\n", "move_rows = []\n", "for label, columns in reduced.items():\n", " smaller = dataclasses.replace(design, **columns)\n", " fit = (\n", " CausalStudy(frame, design=smaller)\n", " .identify(RegimeMean(plans, reference=\"never\"))\n", " .estimate(method=gformula)\n", " )\n", " moved = fit.contrast(lambda means: means[1] - means[0], LEVELS).psi - difference.psi\n", " structural = snmm(\n", " frame,\n", " outcome=\"recovery_day30\",\n", " treatment=list(OFFERS),\n", " baseline=list(columns[\"baseline\"]),\n", " time_varying=[list(names) for names in columns[\"time_varying\"]],\n", " regimens=plans,\n", " reference=\"never\",\n", " blip_features=FEATURES,\n", " outcome_learner=GLM(family=\"gaussian\"),\n", " treatment_learner=GLM(family=\"binomial\"),\n", " n_folds=5,\n", " random_state=3100,\n", " )\n", " full = blips[\"ate_regimen[always vs never]\"]\n", " move_rows.append(\n", " {\n", " \"dropped\": label,\n", " \"g-formula move\": moved / difference.std_error,\n", " \"blip model move\": (structural[\"ate_regimen[always vs never]\"].psi - full.psi)\n", " / full.std_error,\n", " }\n", " )\n", "print(\"move of always minus never, in standard errors of the full fit:\")\n", "print(pd.DataFrame(move_rows).set_index(\"dropped\").round(2).to_string())" ] }, { "cell_type": "markdown", "id": "sensitivity-reading", "metadata": {}, "source": [ "Dropping either covariate moves the gain down by 6 to 11 standard errors, for both methods,\n", "because the navigators read them. An unrecorded cause of the offers and the score would bias the answer too:\n", "the interval spans about 2 standard errors on each side, so a cause whose omission moved the gain a\n", "third as far as the smallest move here could put the estimate outside it. Someone who knows how\n", "navigators decide must judge whether one exists; this comparison is not a bound." ] }, { "cell_type": "markdown", "id": "interpret", "metadata": {}, "source": [ "## What we can and can't conclude\n", "\n", "Had every patient been offered navigation at discharge, day 10 and day 20, the mean day-30\n", "recovery score would be about 10.7 points higher than with no offers (9.49 to 11.82). More than half of the gain\n", "comes from the discharge offer, most of that among patients who live alone, where one offer adds\n", "about 13 points against 2 to 4 elsewhere. That suggests where limited navigators might help most, though the page\n", "did not estimate a targeted plan.\n", "\n", "The interval covers sampling and simulation noise only. The answer also needs the four conditions\n", "of \"Columns, plans, and what must hold\", three of which the data cannot check, and each method's\n", "models: simple symptom models moved it by 1.66 points. The model check and the agreement between\n", "methods only partly check the models.\n", "\n", "One simulated sample says nothing about real patients or how the methods perform in general." ] }, { "cell_type": "markdown", "id": "method-evidence", "metadata": {}, "source": [ "## Go deeper\n", "\n", "### How we know the method works\n", "\n", "Two simulation studies check the methods on this page, each on other simulated data with three\n", "decisions and a continuous score.\n", "\n", "| fit on this page | simulation study | what it covers |\n", "| --- | --- | --- |\n", "| the g-formula (all rows) | [parametric g-formula](../technical-reference/method-evidence/parametric-gformula.md) | other simulated data with a Gaussian and a binary covariate per decision, main-terms models that are right for those data, 2,000 to 8,000 rows. `pygformula` cannot fit its models, so it is compared on four separate fixtures, for the point estimate only |\n", "| the blip model (five folds) | [structural nested mean](../technical-reference/method-evidence/structural-nested-mean.md) | other simulated data with binary covariates, 2,000 rows, ten folds. Its three-decision scenario has one effect per offer for all patients; a two-decision scenario lets the effect depend on a baseline column. EconML's `DynamicDML` agrees on the cells it reports |\n", "\n", "Neither study uses this page's data. The g-formula study fits main-terms symptom models, while this\n", "page's include products of two columns, and the blip-model study's three-decision scenario names\n", "no column in its effects, while this page names living alone. The page's own 400 draws show how often this page's intervals\n", "hold on its own simulated data; only the studies above test the methods more widely. The technical entries list each method's evidence and limits:\n", "[parametric g-formula](../technical-reference/parametric-gformula.md) and [structural dynamic\n", "effects](../technical-reference/structural-dynamic-effects.md)." ] }, { "cell_type": "markdown", "id": "where-next", "metadata": {}, "source": [ "## Where to go next\n", "\n", "The [weekly outcomes example](weekly-outcomes.ipynb) estimates effects of offers repeated over\n", "time without modeling the covariates, and the [discharge-to-readmission\n", "example](discharge-to-readmission.ipynb) follows patients after a discharge offer. The\n", "[longitudinal user guide](../user-guide/longitudinal.md) shows both methods on your own table. The\n", "[examples index](index.md) lists every example." ] } ], "metadata": { "cleverly_execution": { "command": [ "python", "scripts/execute_notebook.py", "docs/examples/model-based-over-time.ipynb" ], "gated": { "code_source_sha256": "96692a408d7576c645f6b7d500b01cde24487eb4089386400b769a0441d9855b", "execution_payload_sha256": "b829c0216c4754e58e6c5207d907f302e2c63645360ee1058603931599e97547" }, "recorded": { "cleverly_commit": "d91a8c51d2429c1d51b5a32cb5a432ac5b652031", "cleverly_version": "0.2.4", "cleverly_worktree_clean": false, "dependency_lock_sha256": "97129a1a44cd0790553fb022322da2d2f02b173723c6e8fadda8a84544278c22", "generator_files": [ "scripts/execute_notebook.py", "tests/notebooks.py" ], "generator_sha256": "f247771ab390b23e7e092d7eb35794e241c2ac84fc0526695df1cee1fc457a83", "package_source_sha256": "762ad45f627caef5bd6105008bf165b1bfe26fced79a24becb6f0276f9c804a9" }, "schema_version": 5 }, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.13.14" } }, "nbformat": 4, "nbformat_minor": 5 }