{ "cells": [ { "cell_type": "markdown", "id": "title", "metadata": {}, "source": [ "# A medicine with two effects on readmission and death: separable effects with TMLE\n", "\n", "## At a glance\n", "\n", "A heart-failure clinic sends patients home on no water pill, a standard dose or a high dose, as\n", "their doctors choose. In this simulated clinic the pill has two parts: one clears fluid, which\n", "keeps patients out of hospital, and one lowers blood potassium, which can cause a fatal heart\n", "rhythm. So part of any drop in readmissions could be patients who died before they could be\n", "readmitted. Would a potassium supplement that blocks the second part keep the benefit without the\n", "deaths?\n", "\n", "Some patients left the clinic's follow-up early. Had every patient stayed, the high dose rather\n", "than no pill would change readmission by day 90 by -18.6 per 100 patients (95% confidence interval\n", "-21.5 to -15.5), and death before any readmission by +23.4 per 100 (20.7 to 26.1). The high dose\n", "with the supplement, against no pill, would change readmission by -13.6 per 100 (-16.8 to -10.3)\n", "and death by only +1.0 (0.7 to 1.4); the other -5.0 readmissions per 100 are patients who died\n", "first. As given, the high dose costs more deaths than the readmissions it saves.\n", "\n", "These numbers rest on conditions no data can check: age and prior admissions capture every common\n", "cause of the dose, leaving follow-up and the events; the fluid part changes death only through\n", "readmission, and the potassium part readmission only through death; the supplement blocks the\n", "potassium part and nothing else; and no unrecorded factor, such as frailty, affects both events.\n", "The supplement numbers also count a death before a readmission when both fall in the same\n", "month; counting the readmission first gives -16.5 (see \"Go deeper\"). The data are simulated, so we know the true changes (-17.7, +23.1 and -13.1 per 100),\n", "and each interval contains its value." ] }, { "cell_type": "markdown", "id": "plan", "metadata": {}, "source": [ "## The question\n", "\n", "The clinic decides the dose when the patient goes home; discharge is time zero, when follow-up\n", "starts. Follow-up ends at the first readmission or death. They are competing events: a patient\n", "who dies can no longer be readmitted. The quantity to estimate is the share readmitted, and the\n", "share who die before any readmission, by day 90 under three plans: every patient on the high\n", "dose, no patient on the pill, and every patient on the high dose with a supplement that keeps\n", "potassium at its level without the pill.\n", "\n", "```text\n", " older, prior_admissions ──▶ dose ──▶ fluid part ──────▶ readmission\n", " │ └──▶ potassium part ──▶ death\n", " └──────────────────────────────────────────▶ readmission, death, leaving follow-up\n", " assumed absent: fluid part ──▶ death; potassium part ──▶ readmission;\n", " an unrecorded cause of the dose and an event, or of both events\n", "```\n", "\n", "Doctors gave higher doses to patients with more admissions in the past year and lower doses to\n", "patients aged 75 or older, and both characteristics also change the chance of each event. They\n", "are confounders, variables that drive both the dose and the outcome. The clinic checks on\n", "patients on days 30, 60 and 90, and a patient can leave follow-up after a check, which is\n", "censoring: an event may happen later but the data hide it.\n", "\n", "No patient got the supplement. The arrows marked absent let us compute its plan anyway. Because the\n", "potassium part has no path to readmission, high-dose patients still alive show the readmission\n", "chance under the fluid part. Because the fluid part has no path to death, patients on no pill show\n", "the death chance with potassium kept level. A factor that changed both events would make the high-dose survivors\n", "unlike the plan's. Stensrud and colleagues (2022) call this a separable effect." ] }, { "cell_type": "markdown", "id": "setup-heading", "metadata": {}, "source": [ "## The data" ] }, { "cell_type": "code", "execution_count": 1, "id": "setup", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:09:00.919197Z", "iopub.status.busy": "2026-11-13T23:09:00.918996Z", "iopub.status.idle": "2026-11-13T23:09:02.291987Z", "shell.execute_reply": "2026-11-13T23:09:02.291370Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "cleverly 0.2.4\n" ] } ], "source": [ "from dataclasses import replace\n", "\n", "import pandas as pd\n", "from sklearn.linear_model import LogisticRegression\n", "\n", "import cleverly\n", "\n", "pd.set_option(\"display.width\", 160)\n", "pd.set_option(\"display.max_columns\", 20)\n", "print(\"cleverly\", cleverly.__version__)" ] }, { "cell_type": "markdown", "id": "data-heading", "metadata": {}, "source": [ "`make_heart_failure` draws 8,000 simulated patients and the true answers, which real data never\n", "give." ] }, { "cell_type": "code", "execution_count": 2, "id": "data", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:09:02.294998Z", "iopub.status.busy": "2026-11-13T23:09:02.294658Z", "iopub.status.idle": "2026-11-13T23:09:02.424967Z", "shell.execute_reply": "2026-11-13T23:09:02.424353Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "rows and columns: (8000, 5)\n", "['older', 'prior_admissions', 'dose', 'day', 'event']\n", " older prior_admissions dose day event\n", "0 0.0 3.0 2.0 70.0 2\n", "1 0.0 2.0 1.0 90.0 0\n", "2 1.0 3.0 2.0 11.0 1\n", "3 0.0 3.0 2.0 52.0 1\n", "4 0.0 1.0 0.0 20.0 2\n", "\n", "patients by dose: {0.0: 2096, 1.0: 3805, 2.0: 2099}\n", "first event by day 90: {'neither': 4204, 'readmission': 2053, 'death': 1743}\n", "left follow-up after the check on day: {30.0: 518, 60.0: 350}\n", "\n", "true risk by day 90, the share of patients with each event first:\n", " readmission death\n", "high dose 0.1866 0.3610\n", "no pill 0.3636 0.1300\n", "high dose with supplement 0.2327 0.1409\n" ] } ], "source": [ "from cleverly.datasets import make_heart_failure\n", "\n", "# With your own data, load one row per patient, such as pd.read_csv(...), with the baseline\n", "# characteristics, the dose, the day of the first event or of the last follow-up check, and an\n", "# event code: 1 for a readmission, 2 for a death, 0 for neither by that day.\n", "# Real data have no `truth`: delete the lines marked \"simulation only\" here and below.\n", "frame, truth = make_heart_failure(n=8_000, seed=11)\n", "print(\"rows and columns:\", frame.shape)\n", "print(list(frame.columns))\n", "print(frame.head().to_string())\n", "print()\n", "print(\"patients by dose:\", frame[\"dose\"].value_counts().sort_index().to_dict())\n", "labels = {0: \"neither\", 1: \"readmission\", 2: \"death\"}\n", "print(\"first event by day 90:\", frame[\"event\"].map(labels).value_counts().to_dict())\n", "left = frame[frame[\"event\"].eq(0) & frame[\"day\"].lt(90)]\n", "print(\"left follow-up after the check on day:\", left[\"day\"].value_counts().sort_index().to_dict())\n", "print()\n", "\n", "# simulation only, to the end of the cell: the true risk of each event by day 90. In `truth`,\n", "# readmission_dose is the dose whose fluid part every patient gets, and death_dose the dose\n", "# whose potassium part they get.\n", "by_parts = truth[truth[\"day\"].eq(90)].set_index([\"readmission_dose\", \"death_dose\"])\n", "known = pd.DataFrame(\n", " {\n", " \"high dose\": by_parts.loc[(2, 2)],\n", " \"no pill\": by_parts.loc[(0, 0)],\n", " \"high dose with supplement\": by_parts.loc[(2, 0)],\n", " }\n", ").T[[\"readmission\", \"death\"]]\n", "print(\"true risk by day 90, the share of patients with each event first:\")\n", "print(known.round(4).to_string())" ] }, { "cell_type": "markdown", "id": "data-reading", "metadata": {}, "source": [ "Each row is one patient. When `event` is 1 (readmitted) or 2 (died), `day` is the day it happened,\n", "such as day 70 for the death in row 0; when `event` is 0, `day` is the last check that found the\n", "patient with neither. No plan uses the standard dose, but those patients still help fit the models." ] }, { "cell_type": "markdown", "id": "association-heading", "metadata": {}, "source": [ "## Why a simple comparison misleads" ] }, { "cell_type": "code", "execution_count": 3, "id": "association", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:09:02.426089Z", "iopub.status.busy": "2026-11-13T23:09:02.425952Z", "iopub.status.idle": "2026-11-13T23:09:02.440842Z", "shell.execute_reply": "2026-11-13T23:09:02.440049Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "baseline means by dose:\n", " older prior_admissions\n", "dose \n", "0.0 0.492 1.111\n", "1.0 0.394 1.502\n", "2.0 0.292 1.931\n", "\n", "share with each recorded first event, high dose minus no pill:\n", " readmission simple -0.1358, true -0.1770\n", " death simple +0.2099, true +0.2310\n" ] } ], "source": [ "print(\"baseline means by dose:\")\n", "print(frame.groupby(\"dose\")[[\"older\", \"prior_admissions\"]].mean().round(3).to_string())\n", "print()\n", "\n", "# The simple comparison: the share with each recorded first event by day 90, high dose minus no\n", "# pill.\n", "high_or_none = frame[frame[\"dose\"].isin([0.0, 2.0])]\n", "shares = pd.crosstab(high_or_none[\"dose\"], high_or_none[\"event\"], normalize=\"index\")\n", "print(\"share with each recorded first event, high dose minus no pill:\")\n", "for event_code, cause in ((1, \"readmission\"), (2, \"death\")):\n", " simple = shares.loc[2.0, event_code] - shares.loc[0.0, event_code]\n", " line = f\" {cause:12s} simple {simple:+.4f}\"\n", " true = known.loc[\"high dose\", cause] - known.loc[\"no pill\", cause] # simulation only\n", " line += f\", true {true:+.4f}\" # simulation only\n", " print(line)" ] }, { "cell_type": "markdown", "id": "association-reading", "metadata": {}, "source": [ "High-dose patients had more prior admissions and were less often 75 or older. Prior admissions\n", "raise both events, so the high dose went to patients more likely to be readmitted, and the simple\n", "readmission difference, -0.1358, is smaller in size than the true -0.1770. The simple shares also\n", "count a patient who left follow-up as having neither event. And no simple comparison can estimate\n", "the supplement plan, which no patient received." ] }, { "cell_type": "markdown", "id": "protocol-heading", "metadata": {}, "source": [ "## Set up the analysis\n", "\n", "First, write the study description (`StudyProtocol`): who is in it, when follow-up starts, what\n", "each plan means, and how death and leaving follow-up count. It does not change the estimate; each\n", "result keeps a copy, so a reader knows what was estimated." ] }, { "cell_type": "code", "execution_count": 4, "id": "protocol", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:09:02.442665Z", "iopub.status.busy": "2026-11-13T23:09:02.442032Z", "iopub.status.idle": "2026-11-13T23:09:02.447923Z", "shell.execute_reply": "2026-11-13T23:09:02.447233Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Population: Adults sent home from the clinic's hospital after an admission for heart failure\n", "Eligibility: Age 18 years or older; Discharged home alive after a heart-failure admission\n", "Follow-up starts: Discharge, after baseline measurement and the discharge prescription\n", "Strategies: Prescribe the water pill at the high dose; Prescribe no water pill; Prescribe the high dose with a potassium supplement that offsets its potassium loss\n", "Versions: The high dose, taken as prescribed or not; Usual heart-failure care without the water pill; The high dose's fluid-clearing action, with blood potassium kept at its level without the pill\n", "Outcome: First unplanned readmission, and death before any readmission\n", "Horizon: 90 days after discharge, with checks on days 30, 60 and 90\n", "Intercurrent events: Treat death before readmission as a competing event: report the risk of each event first, with neither prevented; Treat leaving follow-up after a check as censoring, so the target is the risk had every patient stayed in follow-up (hypothetical strategy); Analyze the prescribed dose regardless of how the pills were taken\n", "Interference unit: Patient\n", "Rationale: Age and prior admissions recorded at discharge hold every common cause of the dose, of leaving follow-up, and of the two events; The fluid-clearing part changes death only through readmission, and the potassium part changes readmission only through death; No unrecorded cause of both readmission and death exists beyond the recorded characteristics\n" ] } ], "source": [ "from cleverly.datasets import heart_failure_protocol\n", "\n", "# For your own study, build cleverly.StudyProtocol(...) directly, with the fields printed below.\n", "protocol = heart_failure_protocol()\n", "print(\"\\n\".join(protocol.summary_lines()))" ] }, { "cell_type": "markdown", "id": "protocol-reading", "metadata": {}, "source": [ "Each risk is the share of patients with that event first, with neither event prevented.\n", "\n", "Next, name the columns for the day, the event code and the dose (`TimeToEvent`), the event each\n", "code stands for (`causes=`), and the check days (`grid=`). The fit works month by month, so each\n", "event day falls in the month that ends at the next check. `cleverly` calls a plan a regimen.\n", "`Separable` declares the supplement plan: `arms=` gives the dose whose part acts on each event, and\n", "`first=` orders a death and a readmission in the same month. `RegimeMean` asks for each plan's\n", "risks, and `study.identify(...)` states the question and lists the conditions an answer rests on." ] }, { "cell_type": "code", "execution_count": 5, "id": "identify", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:09:02.449483Z", "iopub.status.busy": "2026-11-13T23:09:02.449086Z", "iopub.status.idle": "2026-11-13T23:09:02.474897Z", "shell.execute_reply": "2026-11-13T23:09:02.474047Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " Causal question (ey_regime)\n", "==============================================================================\n", "Question: mean outcome under each Rows: 8,000\n", " declared regime Answered by: adjusting for history\n", "Outcome: event=1@30, event=1@60,\n", " event=1@90, event=2@30,\n", " event=2@60, event=2@90\n", " (event by each time)\n", "Treatment: dose\n", "Baseline: older, prior_admissions\n", "==============================================================================\n", "What each treatment time adjusts for\n", "treatment adjusted for\n", "------------------------------------------------------------------------------\n", "dose older, prior_admissions\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 and whether it stays\n", " in follow-up are unrelated to\n", " the outcomes it would have\n", " 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 and of staying in\n", " follow-up.\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, RegimeMean, TimeToEvent\n", "from cleverly.longitudinal import Separable\n", "\n", "# For your own data, change the column names, the check days and the event labels.\n", "design = TimeToEvent(\n", " time=\"day\",\n", " event=\"event\",\n", " treatment=\"dose\",\n", " baseline=(\"older\", \"prior_admissions\"),\n", " grid=(30, 60, 90),\n", " causes={1: \"readmission\", 2: \"death\"},\n", ")\n", "plans = {\n", " \"high dose\": 2,\n", " \"no pill\": 0,\n", " # The fluid part at the high dose and the potassium part at no pill. A death counts before a\n", " # readmission in the same month.\n", " \"high dose with supplement\": Separable(arms={\"readmission\": 2, \"death\": 0}, first=\"death\"),\n", "}\n", "study = CausalStudy(frame, design=design, protocol=protocol)\n", "risks = study.identify(RegimeMean(plans, horizons=(90,)))\n", "print(risks.summary())" ] }, { "cell_type": "markdown", "id": "identify-reading", "metadata": {}, "source": [ "`cleverly` turns each row into an indicator of each event by each check (`event=1@30` is a\n", "readmission by day 30). Of the four printed conditions, two carry the most weight here: age and\n", "prior admissions hold every common cause of the dose, of leaving follow-up and of either event; and\n", "every kind of patient had a real chance of each compared dose and of staying in follow-up\n", "(overlap). The supplement plan adds three:\n", "\n", "- the two parts could be given apart;\n", "- the fluid part changes death only by changing readmission, and the potassium part changes\n", " readmission only by changing death;\n", "- no unrecorded factor, such as frailty, affects both events.\n", "\n", "The data cannot check any of these seven except overlap, which the weight check below partly\n", "checks; only a trial that gave the two parts apart could test the last three." ] }, { "cell_type": "markdown", "id": "estimate-heading", "metadata": {}, "source": [ "## Estimate the risk of each event under each plan\n", "\n", "The method, targeted maximum likelihood estimation (TMLE), models the chance of each event in each\n", "month among patients still at risk, called a hazard. A correction step then adjusts those models,\n", "using the treatment model (who got which dose) and the censoring model (who stays in follow-up), so\n", "that right dose and follow-up models can offset an error in one of the two hazard models.\n", "\n", "- `outcome_learner` predicts the two hazards; `survival_model=\"hazard\"` asks for hazards, which\n", " the supplement plan needs.\n", "- `treatment_learner` and `censoring_learner` predict the dose and staying in follow-up.\n", "- `Targeting(algorithm=\"one_step\")` runs the correction step in many small steps, the form a\n", " supplement plan requires.\n", "- `CrossFitting(enabled=False)` fits every model on all rows, which suits simple models that\n", " cannot memorize their training rows." ] }, { "cell_type": "code", "execution_count": 6, "id": "estimate", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:09:02.476531Z", "iopub.status.busy": "2026-11-13T23:09:02.476027Z", "iopub.status.idle": "2026-11-13T23:09:06.414570Z", "shell.execute_reply": "2026-11-13T23:09:06.414083Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " Longitudinal estimate (LTMLE)\n", "==============================================================================\n", "Question: the event risk under Rows: 8,000\n", " each plan; each row is Time points: 3 (at 30, 60, 90)\n", " defined below Out-of-fold predictions: no\n", "Outcome: readmission at Outcome model: logistic regression\n", " event=1@30, event=1@60, (hazards)\n", " event=1@90; death at Treatment model: logistic regression\n", " event=2@30, event=2@60, Censoring model: logistic regression\n", " event=2@90 (competing Probability limits: [0.01, 1]\n", " causes)\n", "Treatment: dose, given at baseline\n", "Adjusted for: older, prior_admissions\n", "Censoring: day>=30, day>=60,\n", " day>=90; each plan\n", " keeps every unit\n", " observed\n", "Method: longitudinal targeted\n", " maximum likelihood\n", " (LTMLE)\n", "==============================================================================\n", " estimate std. error 95% CI p-value\n", "------------------------------------------------------------------------------\n", "cif_regimen[high dose, death 0.3508 0.0118 [0.3280, 0.3743] <0.0001\n", "@ t=3]\n", "cif_regimen[high dose, 0.1935 0.0097 [0.1752, 0.2133] <0.0001\n", "readmission @ t=3]\n", "cif_regimen[no pill, death 0.1165 0.0074 [0.1027, 0.1319] <0.0001\n", "@ t=3]\n", "cif_regimen[no pill, 0.3792 0.0119 [0.3561, 0.4028] <0.0001\n", "readmission @ t=3]\n", "cif_regimen[high dose with 0.1262 0.0081 [0.1111, 0.1430] <0.0001\n", "supplement, death @ t=3]\n", "cif_regimen[high dose with 0.2433 0.0121 [0.2203, 0.2678] <0.0001\n", "supplement, readmission\n", "@ t=3]\n", "==============================================================================\n", "What each row estimates\n", " meaning\n", "------------------------------------------------------------------------------\n", "cif_regimen[high dose, death @ t=3] probability of\n", " death by time 90 if\n", " every unit followed\n", " plan high dose\n", "cif_regimen[high dose, readmission @ t=3] probability of\n", " readmission by time\n", " 90 if every unit\n", " followed plan high\n", " dose\n", "cif_regimen[no pill, death @ t=3] probability of\n", " death by time 90 if\n", " every unit followed\n", " plan no pill\n", "cif_regimen[no pill, readmission @ t=3] probability of\n", " readmission by time\n", " 90 if every unit\n", " followed plan no\n", " pill\n", "cif_regimen[high dose with supplement, death @ t=3] probability of\n", " death by time 90 if\n", " every unit followed\n", " plan high dose with\n", " supplement\n", "cif_regimen[high dose with supplement, readmission @ t=3] probability of\n", " readmission by time\n", " 90 if every unit\n", " followed plan high\n", " dose with\n", " supplement\n", "==============================================================================\n", "What each plan assigns and who followed it to the end\n", "plan followed max weight effective size assigns\n", "------------------------------------------------------------------------------\n", "high dose 983 of 8,000 12.7 806 2 from\n", " baseline,\n", " held\n", "no pill 1,167 of 8,000 10.1 974 0 from\n", " baseline,\n", " held\n", "high dose with 2,150 of 8,000 15.2 1,727 the part\n", "supplement acting on\n", " readmission\n", " at 2, the\n", " part acting\n", " on death at\n", " 0; death\n", " counted\n", " first within\n", " a time step\n", "==============================================================================\n", "Simultaneous 95% bands\n", " band\n", "------------------------------------------------------------------------------\n", "cif_regimen[high dose, death @ t=3] [0.3217, 0.3811]\n", "cif_regimen[high dose, readmission @ t=3] [0.1702, 0.2192]\n", "cif_regimen[no pill, death @ t=3] [0.0991, 0.1365]\n", "cif_regimen[no pill, readmission @ t=3] [0.3497, 0.4096]\n", "cif_regimen[high dose with supplement, death @ t=3] [0.1071, 0.1481]\n", "cif_regimen[high dose with supplement, readmission @ t=3] [0.2141, 0.2750]\n", "==============================================================================\n", "Notes:\n", "[1] The interval of cif_regimen[high dose, death @ t=3], cif_regimen[high\n", " dose, readmission @ t=3], cif_regimen[no pill, death @ t=3],\n", " cif_regimen[no pill, readmission @ t=3], cif_regimen[high dose with\n", " supplement, death @ t=3], cif_regimen[high dose with supplement,\n", " readmission @ t=3] is built on the log-odds scale and turned back, so it\n", " stays inside the possible range of a proportion and need not be centred on\n", " the estimate.\n", "[2] The bands cover all 6 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" ] } ], "source": [ "from cleverly import CrossFitting, ModelSpec, Runtime, Targeting, TMLEMethod\n", "\n", "\n", "# For your own data, swap in your learners. With flexible learners, leave out\n", "# cross_fitting=... to keep the default, which predicts each row out of fold.\n", "def logistic():\n", " return LogisticRegression(max_iter=1000, random_state=5)\n", "\n", "\n", "method = TMLEMethod(\n", " models=ModelSpec(\n", " outcome_learner=logistic(),\n", " treatment_learner=logistic(),\n", " censoring_learner=logistic(),\n", " survival_model=\"hazard\",\n", " ),\n", " targeting=Targeting(algorithm=\"one_step\"),\n", " cross_fitting=CrossFitting(enabled=False),\n", " runtime=Runtime(random_state=5, n_jobs=1),\n", ")\n", "result = risks.estimate(method=method)\n", "print(result.summary())" ] }, { "cell_type": "markdown", "id": "estimate-reading", "metadata": {}, "source": [ "`cif_regimen[high dose, readmission @ t=3]` is the share readmitted by day 90 under the high dose:\n", "0.1935, against 0.3792 with no pill. The `t` counts checks, so `t=3` is day 90, and the p-values\n", "test only whether a risk is zero. In the plan table, `followed` counts patients whose dose matches\n", "the plan and who were still event-free and in follow-up in the last month; the supplement plan\n", "reads 2,150, the high-dose and no-pill patients together, since it borrows one hazard from each\n", "group. The bands cover all six risks at once. [Read cleverly's output](../user-guide/reading-output.md) explains how every row name is built." ] }, { "cell_type": "markdown", "id": "effects-heading", "metadata": {}, "source": [ "## Split the drop in readmission into its two sources\n", "\n", "`result.contrast(...)` compares two plans' risks, allowing for both coming from the same patients." ] }, { "cell_type": "code", "execution_count": 7, "id": "effects", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:09:06.415705Z", "iopub.status.busy": "2026-11-13T23:09:06.415567Z", "iopub.status.idle": "2026-11-13T23:09:06.443275Z", "shell.execute_reply": "2026-11-13T23:09:06.442337Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "change in the risk by day 90, per 100 patients:\n", " event part plans compared change per 100 ci_low ci_high true\n", "readmission whole medicine high dose - no pill -18.6 -21.5 -15.5 -17.7\n", "readmission fluid part high dose with supplement - no pill -13.6 -16.8 -10.3 -13.1\n", "readmission potassium part high dose - high dose with supplement -5.0 -5.9 -4.2 -4.6\n", " death whole medicine high dose - no pill 23.4 20.7 26.1 23.1\n", " death fluid part high dose with supplement - no pill 1.0 0.7 1.4 1.1\n", " death potassium part high dose - high dose with supplement 22.5 19.7 25.2 22.0\n", "label of every estimate: ['supported']\n" ] } ], "source": [ "# `t=3` is the third check, day 90; with your own grid, use the number of your last check.\n", "def risk(plan, cause):\n", " return f\"cif_regimen[{plan}, {cause} @ t=3]\"\n", "\n", "\n", "# Each difference: the first plan's risk minus the second plan's.\n", "pairs = {\n", " \"whole medicine\": (\"high dose\", \"no pill\"),\n", " \"fluid part\": (\"high dose with supplement\", \"no pill\"),\n", " \"potassium part\": (\"high dose\", \"high dose with supplement\"),\n", "}\n", "effects = {}\n", "rows = []\n", "for cause in (\"readmission\", \"death\"):\n", " for part, (plan, base) in pairs.items():\n", " # psi holds the two named risks in order; .psi is an estimate's value and .ci its interval.\n", " effects[cause, part] = result.contrast(\n", " lambda psi: psi[0] - psi[1], [risk(plan, cause), risk(base, cause)], name=part\n", " )\n", " low, high = effects[cause, part].ci\n", " rows.append(\n", " {\n", " \"event\": cause,\n", " \"part\": part,\n", " \"plans compared\": f\"{plan} - {base}\",\n", " \"change per 100\": 100 * effects[cause, part].psi,\n", " \"ci_low\": 100 * low,\n", " \"ci_high\": 100 * high,\n", " \"true\": 100 * (known.loc[plan, cause] - known.loc[base, cause]), # simulation only\n", " }\n", " )\n", "print(\"change in the risk by day 90, per 100 patients:\")\n", "print(pd.DataFrame(rows).round(1).to_string(index=False))\n", "print(\"label of every estimate:\", sorted({result[name].support.label for name in result}))" ] }, { "cell_type": "markdown", "id": "effects-reading", "metadata": {}, "source": [ "With the potassium part blocked, the fluid part alone changes readmission by -13.6 per 100 (95% CI\n", "-16.8 to -10.3). The other -5.0 (-5.9 to -4.2) of the whole medicine's -18.6 is the potassium\n", "part's share: high-dose patients who died before they could be readmitted. Reading -18.6 as the\n", "pill's benefit would count those deaths as a benefit.\n", "\n", "For death, the potassium part carries +22.5 of the +23.4 per 100. The fluid part adds +1.0 because\n", "patients who avoid readmission stay at risk of dying first." ] }, { "cell_type": "markdown", "id": "assessment-heading", "metadata": {}, "source": [ "## Check the weights behind the estimate\n", "\n", "The correction step weights each patient who followed a plan by one over their predicted chance of\n", "following it and staying in follow-up. For the supplement plan, the weight is also multiplied by\n", "the patient's predicted chance of still being event-free under that plan, divided by the same\n", "chance on their own dose. The overlap check reads these weights and the effective sample size, the\n", "number of equally weighted patients they are worth." ] }, { "cell_type": "code", "execution_count": 8, "id": "assessment", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:09:06.445253Z", "iopub.status.busy": "2026-11-13T23:09:06.445099Z", "iopub.status.idle": "2026-11-13T23:09:06.527217Z", "shell.execute_reply": "2026-11-13T23:09:06.525978Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " check status\n", "score_equations passed\n", " support completed\n", "nuisance_models completed\n", "needs attention: none\n", "\n", "weights by plan and month:\n", " regimen time n_followed max_weight effective_n share_truncated\n", " high dose 1 2099 10.4 1700.0 0.0\n", " high dose 2 1418 11.8 1149.2 0.0\n", " high dose 3 983 12.7 805.6 0.0\n", " no pill 1 2096 8.7 1762.5 0.0\n", " no pill 2 1558 9.3 1312.6 0.0\n", " no pill 3 1167 10.1 974.4 0.0\n", "high dose with supplement 1 4195 10.4 3460.8 0.0\n", "high dose with supplement 2 2976 12.9 2430.1 0.0\n", "high dose with supplement 3 2150 15.2 1727.5 0.0\n", "smallest effective sample, as a share of its group: 80.3%\n" ] } ], "source": [ "assessment = result.assess()\n", "ledger = assessment.to_frame()\n", "# Keep the checks that ran: `passed` has a pass mark, `completed` is a report to read.\n", "ran = ledger[ledger[\"status\"].isin([\"passed\", \"completed\"])]\n", "print(ran[[\"check\", \"status\"]].to_string(index=False))\n", "print(\"needs attention:\", tuple(item.name for item in assessment.attention) or \"none\")\n", "print()\n", "support = assessment.report(\"support\").to_frame()\n", "# The weights are the same for both events, so the readmission rows show them all. Time 1 to 3\n", "# are the months ending on days 30, 60 and 90.\n", "weights = support[support[\"cause\"].eq(\"readmission\")]\n", "columns = [\"regimen\", \"time\", \"n_followed\", \"max_weight\", \"effective_n\", \"share_truncated\"]\n", "print(\"weights by plan and month:\")\n", "print(weights[columns].round(1).to_string(index=False))\n", "ratio = (support[\"effective_n\"] / support[\"n_followed\"]).min()\n", "print(f\"smallest effective sample, as a share of its group: {ratio:.1%}\")" ] }, { "cell_type": "markdown", "id": "assessment-reading", "metadata": {}, "source": [ "Nothing needs attention, the correction step reached its target (`score_equations passed`), and\n", "`nuisance_models` records the fitted hazard, dose and follow-up models. The largest weight is 15.2,\n", "in the supplement plan's last month: above either group's largest, because of that extra factor,\n", "which the 0.01 floor on predicted chances does not cap. Every group is worth at least 80.3% of its\n", "size, and no predicted chance hit the floor (`share_truncated` is 0). Warning signs would be a few\n", "huge weights or an effective sample far below the group size." ] }, { "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 fluid part's effect on readmission:\n", "\n", "- `placebo` replaces each dose with one drawn at random in the observed proportions, so the\n", " difference should be near zero;\n", "- `random_common_cause` adds a pure-noise column, so the difference should barely move;\n", "- `subset` refits on random 70% samples, so the refits should spread about as much as the\n", " standard error predicts for samples of that size.\n", "\n", "None can detect a missing confounder or a broken condition of the supplement plan." ] }, { "cell_type": "code", "execution_count": 9, "id": "refute", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:09:06.529084Z", "iopub.status.busy": "2026-11-13T23:09:06.528884Z", "iopub.status.idle": "2026-11-13T23:11:00.588770Z", "shell.execute_reply": "2026-11-13T23:11:00.587298Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "fluid part, as a named estimate: -0.1359\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ " test original refuted_mean refuted_sd statistic_name statistic verdict\n", " placebo -0.1359 -0.0020 0.0140 t -0.6338 descriptive\n", " subset -0.1359 -0.1308 0.0099 scatter ratio rho 0.9106 descriptive\n", "random_common_cause -0.1359 -0.1358 0.0002 paired shift in standard errors 0.0034 descriptive\n" ] } ], "source": [ "import warnings\n", "\n", "from cleverly import RegimeContrast\n", "from cleverly.exceptions import ConvergenceWarning, SparseInfluenceWarning\n", "\n", "# refute needs the difference as a named estimate, so this fit asks for differences directly.\n", "contrast_fit = study.identify(RegimeContrast(plans, reference=\"no pill\", horizons=(90,))).estimate(\n", " method=method\n", ")\n", "fluid_name = \"ate_regimen[high dose with supplement vs no pill, readmission @ t=3]\"\n", "print(f\"fluid part, as a named estimate: {contrast_fit[fluid_name].psi:.4f}\")\n", "with warnings.catch_warnings():\n", " # The checks warn that the supplement plan's small change in death rests on few rows, and\n", " # two placebo refits, on doses drawn at random, stop the correction step slightly short of\n", " # its target. The readings use only the readmission difference and the refits' estimates.\n", " warnings.simplefilter(\"ignore\", SparseInfluenceWarning)\n", " warnings.simplefilter(\"ignore\", ConvergenceWarning)\n", " # Each check refits 20 times, the default.\n", " refutation = contrast_fit.diagnostics.refute(\n", " estimand=fluid_name, tests=(\"placebo\", \"subset\", \"random_common_cause\"), random_state=61\n", " )\n", "columns = [\n", " \"test\",\n", " \"original\",\n", " \"refuted_mean\",\n", " \"refuted_sd\",\n", " \"statistic_name\",\n", " \"statistic\",\n", " \"verdict\",\n", "]\n", "print(refutation.to_frame()[columns].round(4).to_string(index=False))" ] }, { "cell_type": "markdown", "id": "refute-reading", "metadata": {}, "source": [ "All three behave as expected. The random doses give a mean of -0.0020, the noise column barely\n", "moves the estimate, and the subset refits have a scatter ratio of 0.91, where 1 is ideal and 20\n", "refits easily give 0.7 to 1.3. The verdict reads `descriptive` because no simulation study backs a\n", "pass mark for this fit, so you judge the numbers. Checks that plant a known effect refuse a\n", "supplement plan." ] }, { "cell_type": "markdown", "id": "sensitivity-heading", "metadata": {}, "source": [ "## What if a confounder is missing?\n", "\n", "The E-value measures how strongly a missing confounder would need to be linked to both the dose and\n", "readmission to explain the effect away. It needs two plans that each set the whole dose, so it\n", "covers the whole medicine only." ] }, { "cell_type": "code", "execution_count": 10, "id": "evalue", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:11:00.591060Z", "iopub.status.busy": "2026-11-13T23:11:00.590853Z", "iopub.status.idle": "2026-11-13T23:11:00.604001Z", "shell.execute_reply": "2026-11-13T23:11:00.602910Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " E-value\n", "==============================================================================\n", "Question: how strong a confounder Estimate: rr_regimen[high dose vs no\n", " would explain away pill, readmission @ t=3]\n", " rr_regimen[high dose vs no Scale: risk ratio\n", " pill, readmission @ t=3]\n", "==============================================================================\n", " risk ratio E-value\n", "------------------------------------------------------------------------------\n", "estimate 0.510 3.33\n", "95% limit nearest the null 0.573 2.88\n", "==============================================================================\n", "An unmeasured confounder would need a risk ratio of 3.33 with both the\n", "treatment and the outcome, beyond the measured covariates, to explain away the\n", "estimate; 2.88 to move the interval to the null.\n", "Warnings:\n", "[1] No validation study licenses the E-value of the limit for this kind of\n", " fit, so read it as descriptive.\n", "Notes:\n", "[2] The E-value is the strength at which the confounder's associations with\n", " the treatment and with the outcome, taken as equal, could explain the\n", " estimate away. Unequal strengths can trade off: one association may be\n", " below the E-value if the other is above it.\n", "[3] The risk is the chance of the event by the horizon. The E-value also\n", " assumes that censoring is random given the treatment and covariates, and\n", " that the unmeasured confounder does not affect censoring.\n", "[4] The validation study licenses no derived estimate for this estimate.\n" ] } ], "source": [ "# The E-value reads two plans that each set the whole dose: here the high dose against no pill.\n", "bound = result.sensitivity.evalue(\n", " (risk(\"high dose\", \"readmission\"), risk(\"no pill\", \"readmission\"))\n", ")\n", "print(bound.summary())" ] }, { "cell_type": "markdown", "id": "evalue-reading", "metadata": {}, "source": [ "The high-dose readmission risk is 0.510 times the no-pill risk. A missing confounder would need a\n", "risk ratio of 3.33 with both the dose and readmission to explain that away, and 2.88 to move the\n", "interval's end nearest no effect onto it; whether one that strong is plausible is a judgment about\n", "the clinic. The bound assumes the factor does not change who leaves follow-up.\n", "\n", "`cleverly` has no such bound for the supplement plan, and its made-up-confounder check refuses this\n", "fit: that confounder would shift both events, breaking the condition that no factor affects both." ] }, { "cell_type": "code", "execution_count": 11, "id": "sensitivity", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:11:00.605665Z", "iopub.status.busy": "2026-11-13T23:11:00.605472Z", "iopub.status.idle": "2026-11-13T23:11:06.992687Z", "shell.execute_reply": "2026-11-13T23:11:06.991573Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " left out readmission difference with both left out one move in SEs\n", " older whole medicine -0.1856 -0.1832 0.1546\n", " older fluid part -0.1359 -0.1440 -0.4894\n", "prior_admissions whole medicine -0.1856 -0.1373 3.1419\n", "prior_admissions fluid part -0.1359 -0.0814 3.2763\n" ] } ], "source": [ "# For your own data, leave out each of your strongest recorded confounders in turn.\n", "moves = []\n", "for dropped in design.baseline:\n", " reduced = replace(design, baseline=tuple(n for n in design.baseline if n != dropped))\n", " refit = (\n", " CausalStudy(frame, design=reduced, protocol=protocol)\n", " .identify(RegimeMean(plans, horizons=(90,)))\n", " .estimate(method=method)\n", " )\n", " for part in (\"whole medicine\", \"fluid part\"):\n", " plan, base = pairs[part]\n", " full = effects[\"readmission\", part]\n", " moved = refit.contrast(\n", " lambda psi: psi[0] - psi[1],\n", " [risk(plan, \"readmission\"), risk(base, \"readmission\")],\n", " name=part,\n", " )\n", " moves.append(\n", " {\n", " \"left out\": dropped,\n", " \"readmission difference\": part,\n", " \"with both\": full.psi,\n", " \"left out one\": moved.psi,\n", " \"move in SEs\": (moved.psi - full.psi) / full.std_error,\n", " }\n", " )\n", "print(pd.DataFrame(moves).round(4).to_string(index=False))" ] }, { "cell_type": "markdown", "id": "sensitivity-reading", "metadata": {}, "source": [ "Leaving out `prior_admissions` moves the fluid part's effect from -0.1359 to -0.0814, or 3.3\n", "standard errors, and the whole medicine's by 3.1, so the adjustment rests mostly on prior\n", "admissions; a missing confounder as strong could move the estimates as far. Leaving out `older`\n", "moves each by less than half a standard error." ] }, { "cell_type": "markdown", "id": "interpret", "metadata": {}, "source": [ "## What we can and can't conclude\n", "\n", "For the clinic, had every patient stayed in follow-up: the high dose trades -18.6 readmissions per\n", "100 patients for +23.4 deaths before readmission. Counting a death first within a month, a\n", "supplement that blocks the potassium part would keep -13.6 of the drop (-16.8 to -10.3) at +1.0\n", "deaths. These hold for adults sent home after a heart-failure admission, under the conditions in\n", "\"Set up the analysis\", and lean on prior admissions.\n", "\n", "The supplement plan describes a treatment no patient got, so its answer needs outside evidence,\n", "such as a trial, that the supplement blocks the potassium part and nothing else. One simulated\n", "sample does not show how the method performs in general." ] }, { "cell_type": "markdown", "id": "method-evidence", "metadata": {}, "source": [ "## Go deeper\n", "\n", "### How we know the method works\n", "\n", "Simulation studies check each method over many repeated samples.\n", "[Separable effects](../technical-reference/method-evidence/separable-effects.md) checks this\n", "fit: a baseline treatment with three levels, three checks, two events and leaving follow-up,\n", "with plans that set the whole treatment and plans that set its two parts apart, at 16,000\n", "patients. It uses another simulation, with one yes-or-no characteristic, and models that fit the\n", "mean of each group of patients with the same characteristics. This page's logistic models, two\n", "characteristics and 8,000 patients rest on that study and on theory. No other software that fits\n", "this estimate was found to compare against. The\n", "[technical entry](../technical-reference/longitudinal-tmle.md#validation-issues-special-to-this-method)\n", "lists the method's evidence and limits; its section \"Separable effects\" gives the exact\n", "definition and conditions." ] }, { "cell_type": "markdown", "id": "order-heading", "metadata": {}, "source": [ "### Which event counts first within a month\n", "\n", "The fit works month by month on the checks, not on exact days, so a death and a readmission in the\n", "same month need an order, and when the two parts sit at different doses, the order changes the\n", "question. Death first means that each month the supplement plan's death chance, the no-pill one,\n", "applies first, and readmission is judged among those still alive; readmission first reverses that." ] }, { "cell_type": "code", "execution_count": 12, "id": "order", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:11:06.994379Z", "iopub.status.busy": "2026-11-13T23:11:06.994198Z", "iopub.status.idle": "2026-11-13T23:11:10.350577Z", "shell.execute_reply": "2026-11-13T23:11:10.349575Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "fluid part, change in readmission by day 90 per 100 patients:\n", " death first -13.6 95% CI -16.8 to -10.3 true -13.1\n", " readmission first -16.5 95% CI -19.6 to -13.4 true -15.8\n" ] } ], "source": [ "from cleverly.datasets import heart_failure_truth\n", "\n", "# The same question with a readmission counted before a death in the same month.\n", "readmission_first = {\n", " **plans,\n", " \"high dose with supplement\": Separable(\n", " arms={\"readmission\": 2, \"death\": 0}, first=\"readmission\"\n", " ),\n", "}\n", "other_order = study.identify(RegimeMean(readmission_first, horizons=(90,))).estimate(method=method)\n", "fluid = pairs[\"fluid part\"]\n", "names = [risk(plan, \"readmission\") for plan in fluid]\n", "orders = {\"death first\": result, \"readmission first\": other_order}\n", "print(\"fluid part, change in readmission by day 90 per 100 patients:\")\n", "for order, fit in orders.items():\n", " estimate = fit.contrast(lambda psi: psi[0] - psi[1], names, name=order)\n", " low, high = estimate.ci\n", " # simulation only: the true value of each order.\n", " first = order.split()[0]\n", " fluid_only, none = (\n", " heart_failure_truth(*doses, first=first).set_index(\"day\").loc[90, \"readmission\"]\n", " for doses in ((2, 0), (0, 0))\n", " )\n", " true = fluid_only - none\n", " print(\n", " f\" {order:18s} {100 * estimate.psi:+5.1f} 95% CI {100 * low:+5.1f} to {100 * high:+5.1f}\"\n", " f\" true {100 * true:+5.1f}\"\n", " )" ] }, { "cell_type": "markdown", "id": "order-reading", "metadata": {}, "source": [ "Each order lands near its own true value, and the two differ by about 3 per 100. In this simulated\n", "clinic a death does come first within a month, so -13.1 is the supplement's effect here and -15.8\n", "is only what the readmission-first formula gives. With real data the order is a choice about what\n", "the supplement plan means, which the data cannot settle, so `cleverly` requires `first=`. The order\n", "matters on a coarse grid like these monthly checks, and little when checks are close together, so\n", "closer checks are the way to make the choice matter less. Pick it before you look at the results,\n", "and report it with the answer." ] }, { "cell_type": "markdown", "id": "where-next", "metadata": {}, "source": [ "## Where to go next\n", "\n", "[Readmission when death can come first](longitudinal-survival.ipynb) follows a treatment offered at\n", "two points, with death as a competing event, and also asks the different question of readmission\n", "had death been prevented. [Readmission by day 30, 60 and 90](discharge-to-readmission.ipynb)\n", "follows readmission with leaving follow-up and no competing event. The [longitudinal TMLE\n", "reference](../technical-reference/longitudinal-tmle.md) gives the exact definition under \"Separable\n", "effects\", and [scope and refusals](../technical-reference/scope-and-refusals.md) lists what a\n", "separable fit refuses. The [examples index](index.md) lists every example." ] } ], "metadata": { "cleverly_execution": { "command": [ "python", "scripts/execute_notebook.py", "docs/examples/separable-effects.ipynb" ], "gated": { "code_source_sha256": "27586040f7bdb244de9b2054e5a0ddba13600696d4a293cb41a517b01946a56e", "execution_payload_sha256": "f29fd699b7fc7e6c6d899c2b67ba4482930027dfe2001c829226a0f778e1a4c2" }, "recorded": { "cleverly_commit": "26d6a178ddefa6268fe222aaf6736c0c74094b45", "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 }