{ "cells": [ { "cell_type": "markdown", "id": "title", "metadata": {}, "source": [ "# Gain over current practice: TMLE for population impact\n", "\n", "## At a glance\n", "\n", "A hospital program offers transition navigation (a bedside transition plan and two navigator\n", "contacts) to some patients going home. A day-30 survey asks how well the move home went, and a\n", "\"top box\" answer is the best rating on its scale. A quarter of patients never answer. The manager\n", "asks what offering every eligible patient would add to current practice, and what current\n", "practice already achieves over offering no one.\n", "\n", "Offering everyone would raise the share of patients with a top-box answer from 0.5756 under\n", "current practice to about 0.67, a gain of 0.0956 (95% confidence interval 0.0739 to 0.1173), or\n", "about 10 more top-box patients per 100. Current practice already adds 0.0872 over offering no one.\n", "The usual average effect (ATE), 0.1828, compares offering everyone with offering no one, so it\n", "also counts the part current practice has already collected. If every patient were guaranteed a\n", "primary-care visit within 7 days, offering everyone instead of no one would still raise the share\n", "by 0.1153 (interval 0.0592 to 0.1724), against the ATE's 0.1828 when the visit follows the offer.\n", "\n", "The answer assumes that no unrecorded factor drives both who gets the offer and the outcome, and\n", "that non-responders would have answered like comparable respondents. The first is the more\n", "fragile on this page's checks. An unrecorded cause of the outcome much stronger than anything\n", "recorded could erase the gain, so the question for program staff is whether such a factor exists.\n", "\n", "The data are simulated, so we know the true gain (0.0799), and the interval contains it." ] }, { "cell_type": "markdown", "id": "plan", "metadata": {}, "source": [ "## The question\n", "\n", "Discharge teams choose who gets the offer, and they favor patients with a high discharge risk. The\n", "manager must decide whether to extend the offer to every eligible patient, so the main quantity is\n", "the gain: the top-box rate if everyone got the offer minus the rate under current practice, over\n", "every eligible patient, whether or not they answer. What current practice achieves is its rate\n", "minus the rate if no one got the offer. The code computes both with one quantity, the population\n", "attributable risk (PAR): today's rate minus the rate if every patient got the option named by\n", "`reference=`. The gain is minus the PAR with `reference=1`, and what current practice achieves is\n", "the PAR with `reference=0`.\n", "\n", "A second question asks whether the offer still helps when every patient sees a primary-care doctor\n", "within 7 days. The offer makes that visit more likely, so part of its effect may run through it.\n", "For that reason the gain does not adjust for the visit: adjusting would remove the part of the\n", "gain that runs through it. The controlled direct effect instead compares offer with no offer while\n", "every patient's visit is set to yes.\n", "\n", "```text\n", " W ────────────────────────────────┐\n", " │ ▼\n", " ├──────▶ A ──────────────────────▶ Y\n", " │ │ ▲\n", " │ ├──────▶ Z ──────────────┘\n", " │ │ ▲\n", " ├────────┼────────┘\n", " │ ▼\n", " └──────▶ R Y is seen only when R = 1\n", "\n", " W = discharge_risk, age, prior_utilization (recorded before the offer)\n", " A = transition_navigation (the offer)\n", " Z = pcp_visit_7d (a primary-care visit within 7 days of discharge)\n", " Y = top_box (the day-30 survey rates the transition top box)\n", " R = responded (the survey came back by day 45)\n", " not drawn: an unrecorded cause of A and Y, of Z and Y, or of R and Y,\n", " and any arrow from Z or Y to R\n", "```\n", "\n", "The graph shows what we assume causes what. The characteristics drive the offer, the visit, the\n", "outcome, and who answers; the offer drives the visit, the outcome, and who answers; and the visit\n", "drives the outcome. The analysis rests on what the graph leaves out. Without an arrow from the\n", "outcome to answering, non-responders would have answered like respondents with the same offer and\n", "characteristics, an assumption called \"missing at random\"." ] }, { "cell_type": "markdown", "id": "setup-heading", "metadata": {}, "source": [ "## The data\n", "\n", "Every fit sets its seeds, so a rerun prints the same numbers." ] }, { "cell_type": "code", "execution_count": 1, "id": "setup", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:04:06.070901Z", "iopub.status.busy": "2026-11-13T23:04:06.070663Z", "iopub.status.idle": "2026-11-13T23:04:07.558944Z", "shell.execute_reply": "2026-11-13T23:04:07.558322Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "cleverly 0.2.4\n" ] } ], "source": [ "import numpy as np\n", "import pandas as pd\n", "from sklearn.linear_model import LogisticRegression\n", "from sklearn.pipeline import make_pipeline\n", "from sklearn.preprocessing import PolynomialFeatures\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": "setup-reading", "metadata": {}, "source": [ "Another version of `cleverly` can print slightly different numbers." ] }, { "cell_type": "markdown", "id": "data-heading", "metadata": {}, "source": [ "`make_population_impact` draws 4,000 simulated discharges and also returns the true values, which\n", "real data never give you." ] }, { "cell_type": "code", "execution_count": 2, "id": "data", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:04:07.560972Z", "iopub.status.busy": "2026-11-13T23:04:07.560705Z", "iopub.status.idle": "2026-11-13T23:04:07.799571Z", "shell.execute_reply": "2026-11-13T23:04:07.798320Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "rows and columns: (4000, 7)\n", "['top_box', 'transition_navigation', 'discharge_risk', 'age', 'prior_utilization', 'pcp_visit_7d', 'responded']\n", " top_box transition_navigation discharge_risk age prior_utilization pcp_visit_7d responded\n", "0 1.0 0.0 0.097 0.445 0.777 1.0 1.0\n", "1 NaN 0.0 0.308 -0.018 -0.356 1.0 0.0\n", "2 1.0 1.0 0.691 0.590 0.924 1.0 1.0\n", "3 1.0 0.0 -1.211 1.138 0.822 1.0 1.0\n", "4 1.0 0.0 -1.634 -0.696 0.535 1.0 1.0\n", "\n", "share offered today: 0.437\n", "share with a 7-day visit: 0.508\n", "survey response rate: 0.758\n", "\n", "true values, known only because the data are simulated:\n", " top-box rate under current practice: 0.5641\n", " if every patient got the offer: 0.6440\n", " if no patient got the offer: 0.4791\n" ] } ], "source": [ "from cleverly.datasets import make_population_impact\n", "\n", "# With your own data, load your data frame here, such as frame = pd.read_csv(...), with a\n", "# missing value (NaN) wherever the outcome was not recorded and a 0/1 column that is 1 exactly\n", "# where it was. Real data have no `truth`: drop the lines that print it, and pass float(\"nan\")\n", "# as the true value to the `line` helper defined below.\n", "frame, truth = make_population_impact(n=4_000, seed=2031)\n", "print(\"rows and columns:\", frame.shape)\n", "print(list(frame.columns))\n", "print(frame.head().round(3))\n", "print()\n", "print(f\"share offered today: {frame['transition_navigation'].mean():.3f}\")\n", "print(f\"share with a 7-day visit: {frame['pcp_visit_7d'].mean():.3f}\")\n", "print(f\"survey response rate: {frame['responded'].mean():.3f}\")\n", "print()\n", "print(\"true values, known only because the data are simulated:\")\n", "print(f\" top-box rate under current practice: {truth['ey_obs']:.4f}\")\n", "print(f\" if every patient got the offer: {truth['ey1']:.4f}\")\n", "print(f\" if no patient got the offer: {truth['ey0']:.4f}\")" ] }, { "cell_type": "markdown", "id": "data-reading", "metadata": {}, "source": [ "Each row is one discharge: `top_box` (1 for top box, `NaN` when the survey did not come back), the\n", "offer, three characteristics measured before it on a standardized scale, the 7-day visit, and\n", "`responded`. The gain the manager asks about is the gap between 0.6440 and 0.5641 in the true\n", "values." ] }, { "cell_type": "markdown", "id": "association-heading", "metadata": {}, "source": [ "## Why a simple comparison misleads\n", "\n", "The quick answers use the respondents: the top-box rate of offered patients against the others,\n", "and the rate among everyone who answered." ] }, { "cell_type": "code", "execution_count": 3, "id": "association", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:04:07.801907Z", "iopub.status.busy": "2026-11-13T23:04:07.801195Z", "iopub.status.idle": "2026-11-13T23:04:07.814170Z", "shell.execute_reply": "2026-11-13T23:04:07.813192Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "top-box rate among respondents, offered: 0.6566\n", "top-box rate among respondents, not offered: 0.5326\n", "difference: 0.1241\n", "top-box rate among all respondents: 0.5869\n", "\n", "mean baseline covariate by offer:\n", " discharge_risk age prior_utilization\n", "transition_navigation \n", "0.0 -0.233 0.115 -0.113\n", "1.0 0.302 -0.124 0.116\n" ] } ], "source": [ "answered = frame[frame[\"responded\"] == 1]\n", "rates = answered.groupby(\"transition_navigation\")[\"top_box\"].mean()\n", "print(f\"top-box rate among respondents, offered: {rates[1.0]:.4f}\")\n", "print(f\"top-box rate among respondents, not offered: {rates[0.0]:.4f}\")\n", "print(f\"difference: {rates[1.0] - rates[0.0]:.4f}\")\n", "print(f\"top-box rate among all respondents: {answered['top_box'].mean():.4f}\")\n", "print()\n", "# The characteristics measured before the offer that every later fit adjusts for. For your own\n", "# data, list yours here.\n", "covariates = [\"discharge_risk\", \"age\", \"prior_utilization\"]\n", "print(\"mean baseline covariate by offer:\")\n", "print(frame.groupby(\"transition_navigation\")[covariates].mean().round(3))" ] }, { "cell_type": "markdown", "id": "association-reading", "metadata": {}, "source": [ "Offered respondents reach a top box 0.1241 more often than the others. That difference answers\n", "neither question. It compares offered with not offered, not everyone with today, and the offered\n", "patients had a higher discharge risk (mean 0.302 against -0.233), which lowers the chance of a top\n", "box. The rate among respondents, 0.5869, overstates today's rate (0.5641 in the true values)\n", "because high-risk patients answer less often." ] }, { "cell_type": "markdown", "id": "protocol-heading", "metadata": {}, "source": [ "## Set up the analysis\n", "\n", "First, describe the study (`StudyProtocol`). The description does not change the estimate; it\n", "records what the estimate means, so a reviewer can check it against the manager's decision. The\n", "code starts from this program's description and changes four fields: the population includes\n", "patients who never answer, the outcome is the top-box rating, a death before day 30 counts as not\n", "top box (an event after the offer that changes the outcome, which the output calls an\n", "intercurrent event), and the reasons add the survey assumption." ] }, { "cell_type": "code", "execution_count": 4, "id": "protocol", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:04:07.816368Z", "iopub.status.busy": "2026-11-13T23:04:07.815770Z", "iopub.status.idle": "2026-11-13T23:04:07.823933Z", "shell.execute_reply": "2026-11-13T23:04:07.823057Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Population: Adults with a discharge-home order at a participating hospital during the enrollment period, whether or not they return the survey\n", "Eligibility: Age 18 years or older; Discharge home ordered at a participating hospital\n", "Follow-up starts: Discharge-home order, after baseline measurement and before the navigation offer\n", "Strategies: Offer standard transition navigation; Provide usual discharge support\n", "Versions: Bedside transition plan and two scheduled navigator contacts within 30 days; No access to the transition-navigation offer\n", "Outcome: Top-box patient-reported transition score, from the survey sent on day 30 and closed on day 45\n", "Horizon: 30 days after discharge\n", "Intercurrent events: Use the transition score regardless of readmission; Analyze the offer regardless of completed contacts; The protocol scores death before day 30 as not top box (composite strategy)\n", "Interference unit: Individual patient\n", "Rationale: The recorded baseline variables cover the measured common causes; Given the arm and the baseline variables, survey response carries no further information about the unobserved score (missingness at random); Standardized offer and version records support that each offer is one well-defined action, so a patient's recorded outcome is the outcome they would have had under the offer they got; Reserved navigator capacity and access controls support no interference\n" ] } ], "source": [ "from dataclasses import replace\n", "\n", "from cleverly.datasets import navigation_protocol\n", "\n", "# For your own study, build the description with cleverly.StudyProtocol(target_population=...,\n", "# eligibility=..., time_zero=..., treatment_strategies=..., treatment_versions=..., outcome=...,\n", "# horizon=..., intercurrent_event_handling=..., interference_unit=..., assumption_rationale=...),\n", "# in the order the output prints them; each is text or a tuple of texts. With missing outcomes,\n", "# say in target_population that non-responders belong to it, and give the reason for missing at\n", "# random in assumption_rationale, as below.\n", "program = navigation_protocol()\n", "protocol = replace(\n", " program,\n", " target_population=f\"{program.target_population}, whether or not they return the survey\",\n", " outcome=(\n", " \"Top-box patient-reported transition score, from the survey sent on day 30 and \"\n", " \"closed on day 45\"\n", " ),\n", " intercurrent_event_handling=(\n", " *program.intercurrent_event_handling[:2],\n", " \"The protocol scores death before day 30 as not top box (composite strategy)\",\n", " ),\n", " assumption_rationale=(\n", " program.assumption_rationale[0],\n", " \"Given the arm and the baseline variables, survey response carries no further \"\n", " \"information about the unobserved score (missingness at random)\",\n", " *program.assumption_rationale[1:],\n", " ),\n", ")\n", "print(\"\\n\".join(protocol.summary_lines()))" ] }, { "cell_type": "markdown", "id": "protocol-reading", "metadata": {}, "source": [ "The strategies compare the offer with usual discharge support, and current practice is the mix of\n", "the two that discharge teams chose. These simulated data have no deaths. In real data a death\n", "gives a recorded \"not top box\" without a survey, so whether an outcome is recorded would depend on\n", "the outcome itself, which breaks missing at random. This page does not cover that case: data with\n", "deaths need the death rows handled by another design before this analysis." ] }, { "cell_type": "markdown", "id": "identify-heading", "metadata": {}, "source": [ "Next, name the columns and the quantity to estimate. `PointTreatment` describes a study with one\n", "treatment decided at one time, and `missingness=\"responded\"` marks who answered.\n", "`PopulationAttributableRisk(reference=1)` asks for today's rate minus the rate if every patient got\n", "the offer, so the gain is its negative. `study.identify(...)` lists what must be true for the\n", "answer to be causal." ] }, { "cell_type": "code", "execution_count": 5, "id": "identify", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:04:07.825287Z", "iopub.status.busy": "2026-11-13T23:04:07.825128Z", "iopub.status.idle": "2026-11-13T23:04:07.834217Z", "shell.execute_reply": "2026-11-13T23:04:07.833722Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " Causal question (par)\n", "==============================================================================\n", "Question: mean top_box as Rows: 4,000\n", " treated, minus the mean Answered by: adjusting for covariates\n", " if every unit had\n", " transition_navigation =\n", " 1\n", "Outcome: top_box (binary); 3,033\n", " of 4,000 observed\n", "Treatment: transition_navigation\n", " (levels 0, 1)\n", "Adjusted for: discharge_risk, age,\n", " prior_utilization\n", "==============================================================================\n", "Conditions the answer rests on\n", "condition checkable what it says\n", "------------------------------------------------------------------------------\n", "well-defined treatment no Each unit's observed outcome is\n", " the outcome it would have had\n", " under the treatment it actually\n", " received. This needs the treatment\n", " to be well defined: every way of\n", " getting the same level has the\n", " same effect.\n", "no interference no One unit's treatment does not\n", " change another unit's outcome.\n", "no hidden confounding no Among units with the same\n", " adjusted-for values, which\n", " treatment a unit got is unrelated\n", " to the outcomes it would have had.\n", " This holds when the adjusted-for\n", " columns account for the common\n", " causes of transition_navigation\n", " and top_box and none of them is\n", " affected by transition_navigation.\n", "overlap partly Every group of units that share\n", " the adjusted-for values had some\n", " chance of the reference level of\n", " transition_navigation.\n", "outcome missing at random no Among units with the same\n", " treatment and adjusted-for values,\n", " whether top_box was recorded is\n", " unrelated to its value.\n", "chance of a recorded outcome partly Every group of units that share\n", " the treatment and adjusted-for\n", " values that the question reads had\n", " some chance of a recorded top_box.\n", "recorded outcome at reference partly Every group of units that share\n", " the adjusted-for values had some\n", " chance of both the reference level\n", " of transition_navigation and a\n", " recorded top_box.\n", "==============================================================================\n", "Methods\n", "method name\n", "------------------------------------------------------------------------------\n", "tmle targeted maximum likelihood (TMLE)\n", "adaptive_iptw adaptive-propensity inverse probability weighting\n", "==============================================================================\n", "Notes:\n", "[1] Some top_box values are missing, so the mean of top_box as treated, under\n", " the treatment each unit actually got, need not equal the average of the\n", " recorded values. cleverly estimates it from a model of top_box and a model\n", " of which outcomes were recorded, so it rests on the outcome missing at\n", " random and chance of a recorded outcome conditions above.\n", "[2] 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", "[3] The methods table lists the methods that fit. 10 other methods cannot\n", " estimate this question; the full summary says why.\n" ] } ], "source": [ "from cleverly import CausalStudy, PointTreatment, PopulationAttributableRisk\n", "\n", "# For your own data, change the column names and the response column; the adjustment list is\n", "# the `covariates` list of the comparison cell. The visit is left out of it, because the offer\n", "# partly causes the visit.\n", "design = PointTreatment(\n", " outcome=\"top_box\",\n", " treatment=\"transition_navigation\",\n", " adjustment=tuple(covariates),\n", " missingness=\"responded\",\n", ")\n", "study = CausalStudy(frame, design=design, protocol=protocol)\n", "gain_question = study.identify(PopulationAttributableRisk(reference=1))\n", "print(gain_question.summary())" ] }, { "cell_type": "markdown", "id": "identify-reading", "metadata": {}, "source": [ "### What the answer assumes\n", "\n", "\"Well-defined treatment\" (an offer always means the same plan) and \"no interference\" (one\n", "patient's offer does not change another's outcome) rest on the\n", "[shared study design](index.md#the-shared-study-design): the protocol's last two reasons, a\n", "standard offer and reserved navigator capacity, are the argument to make for your own program.\n", "The data cannot check \"no hidden confounding\" or \"outcome missing at random\". \"Chance of a\n", "recorded outcome\" asks for a real chance of answering, with or without the offer, and \"recorded\n", "outcome at reference\" for a chance of the offer and an answer together; \"Check the overlap and the\n", "models\" probes both. Today's rate alone needs only the survey conditions, because it compares no\n", "options." ] }, { "cell_type": "markdown", "id": "estimate-heading", "metadata": {}, "source": [ "## Estimate current practice and the gain\n", "\n", "The method, targeted maximum likelihood estimation (TMLE), fits an outcome model for the chance of\n", "a top box, a treatment model for who gets the offer, and a response model for who answers. A\n", "correction step then weights each respondent by one over their predicted chance of their offer and\n", "of answering, so the respondents stand in for every patient. `NaturalCourseMean()` asks for\n", "today's rate. Each model is a learner: any scikit-learn classifier.\n", "\n", "- `outcome_learner`: a logistic regression on the offer, the characteristics, and each product of\n", " two of them, so the offer's effect can differ between patients.\n", "- `treatment_learner`, `missingness_learner`: logistic regressions, which have the true form in\n", " these simulated data. With real data a flexible classifier, such as scikit-learn's\n", " `HistGradientBoostingClassifier`, is the safer default.\n", "- `CrossFitting(n_folds=10)`: each patient's predictions come from models trained without that\n", " patient, like out-of-fold predictions in cross-validation.\n", "- `Runtime(random_state=2031, n_jobs=1)`: a fixed seed." ] }, { "cell_type": "code", "execution_count": 6, "id": "estimate", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:04:07.837015Z", "iopub.status.busy": "2026-11-13T23:04:07.836703Z", "iopub.status.idle": "2026-11-13T23:04:08.115563Z", "shell.execute_reply": "2026-11-13T23:04:08.114681Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " Effect estimate (TMLE)\n", "==============================================================================\n", "Question: mean top_box as Rows: 4,000\n", " treated, minus the mean Treated share: 0.437\n", " if every unit had Out-of-fold predictions: 10 folds\n", " transition_navigation = Outcome model: logistic regression\n", " 1 after polynomial terms\n", "Outcome: top_box (binary); 3,033 Treatment model: logistic regression\n", " of 4,000 observed Probability limits: [0.009532,\n", "Adjusted for: discharge_risk, age, 0.9905]\n", " prior_utilization Missingness model: logistic\n", "Method: targeted maximum regression\n", " likelihood (TMLE)\n", "==============================================================================\n", " estimate std. error 95% CI p-value\n", "------------------------------------------------------------------------------\n", "par -0.096 0.011 [-0.117, -0.074] <0.0001\n", "==============================================================================\n" ] } ], "source": [ "from cleverly import CrossFitting, ModelSpec, NaturalCourseMean, Runtime, TMLEMethod\n", "\n", "\n", "def logistic():\n", " return LogisticRegression(max_iter=2000)\n", "\n", "\n", "def with_products():\n", " return make_pipeline(\n", " PolynomialFeatures(degree=2, interaction_only=True, include_bias=False), logistic()\n", " )\n", "\n", "\n", "# For your own data, swap in your learners.\n", "method = TMLEMethod(\n", " models=ModelSpec(\n", " outcome_learner=with_products(),\n", " treatment_learner=logistic(),\n", " missingness_learner=logistic(),\n", " ),\n", " cross_fitting=CrossFitting(n_folds=10),\n", " runtime=Runtime(random_state=2031, n_jobs=1),\n", ")\n", "gain_fit = gain_question.estimate(method=method)\n", "current_fit = study.identify(NaturalCourseMean()).estimate(method=method)\n", "print(gain_fit.summary())" ] }, { "cell_type": "markdown", "id": "estimate-reading", "metadata": {}, "source": [ "`par` in the bottom table is today's rate minus the rate with everyone offered, so the gain is\n", "0.096 (interval 0.074 to 0.117), and the p-value tests a gain of zero. `Rows: 4,000` shows that\n", "the fit kept every patient, including the 967 whose outcome is missing. `Probability limits` are\n", "the caps read under \"Check the overlap and the models\". The interval is valid in large samples\n", "when the models are reasonably accurate." ] }, { "cell_type": "code", "execution_count": 7, "id": "estimates", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:04:08.116880Z", "iopub.status.busy": "2026-11-13T23:04:08.116731Z", "iopub.status.idle": "2026-11-13T23:04:08.534785Z", "shell.execute_reply": "2026-11-13T23:04:08.533718Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " estimate 95% interval\n", "top-box rate under current practice 0.5756 (0.5577, 0.5932) true 0.5641 supported\n", "gain if every patient got the offer 0.0956 (0.0739, 0.1173) true 0.0799 supported\n", " as a share of today's rate 0.1661 (0.1276, 0.2046) true 0.1416 supported\n", "what current practice achieves over no one 0.0872 (0.0680, 0.1064) true 0.0850 supported\n", " as a share of today's rate 0.1515 (0.1175, 0.1854) true 0.1507 supported\n" ] } ], "source": [ "from cleverly import PopulationAttributableFraction\n", "\n", "achieved_fit = study.identify(PopulationAttributableRisk(reference=0)).estimate(method=method)\n", "gain_share_fit = study.identify(PopulationAttributableFraction(reference=1)).estimate(method=method)\n", "achieved_share_fit = study.identify(PopulationAttributableFraction(reference=0)).estimate(\n", " method=method\n", ")\n", "\n", "\n", "def line(label, estimate, true, sign=1.0):\n", " \"\"\"Print one estimate, its 95% interval, the true value and the support label.\"\"\"\n", " low, high = sorted(sign * limit for limit in estimate.ci)\n", " print(\n", " f\"{label:46s} {sign * estimate.psi:7.4f} ({low:.4f}, {high:.4f}) \"\n", " f\"true {true:.4f} {estimate.support.label}\"\n", " )\n", "\n", "\n", "print(f\"{'':46s} estimate 95% interval\")\n", "line(\"top-box rate under current practice\", current_fit[\"ey_obs\"], truth[\"ey_obs\"])\n", "line(\"gain if every patient got the offer\", gain_fit[\"par\"], -truth[\"par[reference=1]\"], -1.0)\n", "line(\" as a share of today's rate\", gain_share_fit[\"paf\"], -truth[\"paf[reference=1]\"], -1.0)\n", "line(\"what current practice achieves over no one\", achieved_fit[\"par\"], truth[\"par[reference=0]\"])\n", "line(\" as a share of today's rate\", achieved_share_fit[\"paf\"], truth[\"paf[reference=0]\"])" ] }, { "cell_type": "markdown", "id": "estimates-reading", "metadata": {}, "source": [ "Each interval contains its true value. The gain is about a sixth of today's rate (share 0.1661),\n", "and removing the offer would lower today's rate by a 0.1515 share. `supported` means a simulation\n", "study checks this estimator with missing outcomes, though not with these models; `cleverly` marks\n", "a result `experimental` when no study does." ] }, { "cell_type": "markdown", "id": "failure-heading", "metadata": {}, "source": [ "## Why the average effect overstates the gain\n", "\n", "A common mistake reports the average treatment effect (ATE), the rate if everyone got the offer\n", "minus the rate if no one did, as the gain from extending the offer." ] }, { "cell_type": "code", "execution_count": 8, "id": "failure-mode", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:04:08.536327Z", "iopub.status.busy": "2026-11-13T23:04:08.535880Z", "iopub.status.idle": "2026-11-13T23:04:08.683499Z", "shell.execute_reply": "2026-11-13T23:04:08.682315Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "average effect, everyone against no one (ATE) 0.1828 (0.1448, 0.2199) true 0.1649 supported\n", "gain over current practice 0.0956 (0.0739, 0.1173) true 0.0799 supported\n", "\n", "achieved by current practice plus the gain: 0.1828\n", "share not offered today: 0.563\n", "\n", "true effect of the offer, known only because the data are simulated:\n", " among patients offered today: 0.1957\n", " among patients not offered today: 0.1412\n" ] } ], "source": [ "from cleverly import ATE\n", "\n", "ate_fit = study.identify(ATE(reference=0)).estimate(method=method)\n", "line(\"average effect, everyone against no one (ATE)\", ate_fit[\"ate\"], truth[\"ate\"])\n", "line(\"gain over current practice\", gain_fit[\"par\"], -truth[\"par[reference=1]\"], -1.0)\n", "print()\n", "parts = achieved_fit[\"par\"].psi - gain_fit[\"par\"].psi\n", "not_offered = 1 - frame[\"transition_navigation\"].mean()\n", "print(f\"achieved by current practice plus the gain: {parts:.4f}\")\n", "print(f\"share not offered today: {not_offered:.3f}\")\n", "print()\n", "# Real data have no truth: drop the lines from here on.\n", "print(\"true effect of the offer, known only because the data are simulated:\")\n", "print(f\" among patients offered today: {truth['att']:.4f}\")\n", "print(f\" among patients not offered today: {truth['atc']:.4f}\")" ] }, { "cell_type": "markdown", "id": "failure-reading", "metadata": {}, "source": [ "The ATE, 0.1828, splits into what current practice has already collected (0.0872) and what is\n", "left to gain (0.0956), which add up to 0.1828. Its interval, 0.1448 to 0.2199, misses the true gain\n", "of 0.0799. Only the 0.563 of patients not offered today can still gain, and in these simulated data\n", "they gain less than those already offered (true effects 0.1412 against 0.1957): discharge teams\n", "already favor high-risk patients, for whom the offer does more. Reporting the ATE as the gain would\n", "promise the manager the part current practice already delivers.\n", "\n", ":::{dropdown} Details: the identity behind the split\n", "With $A$ the offer and $Y^a$ the outcome under option $a$, the gain is\n", "$E(Y^1) - E(Y) = P(A = 0)\\,E(Y^1 - Y^0 \\mid A = 0)$, the share not offered times the effect\n", "among them (the ATC). What current practice achieves is\n", "$E(Y) - E(Y^0) = P(A = 1)\\,E(Y^1 - Y^0 \\mid A = 1)$, the share offered times the effect among\n", "them (the ATT), and the two sum to the ATE. The three fits start from the same models, but each\n", "corrects for its own quantity, so the identity need not hold exactly; here it holds to the printed\n", "digits. Each interval comes from its own fit.\n", ":::" ] }, { "cell_type": "markdown", "id": "ratios-heading", "metadata": {}, "source": [ "## The everyone-against-no-one effect as a ratio\n", "\n", "Some readers expect a relative effect. `RiskRatio` divides the rate if everyone got the offer by\n", "the rate if no one did, and `OddsRatio` divides the odds." ] }, { "cell_type": "code", "execution_count": 9, "id": "ratios", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:04:08.685100Z", "iopub.status.busy": "2026-11-13T23:04:08.684857Z", "iopub.status.idle": "2026-11-13T23:04:08.979060Z", "shell.execute_reply": "2026-11-13T23:04:08.978227Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "risk ratio, everyone against no one 1.3742 (1.2846, 1.4700) true 1.3442 supported\n", "odds ratio, everyone against no one 2.1379 (1.8207, 2.5104) true 1.9667 supported\n" ] } ], "source": [ "from cleverly import OddsRatio, RiskRatio\n", "\n", "rr_fit = study.identify(RiskRatio(reference=0)).estimate(method=method)\n", "or_fit = study.identify(OddsRatio(reference=0)).estimate(method=method)\n", "line(\"risk ratio, everyone against no one\", rr_fit[\"rr\"], truth[\"rr\"])\n", "line(\"odds ratio, everyone against no one\", or_fit[\"or\"], truth[\"or\"])" ] }, { "cell_type": "markdown", "id": "ratios-reading", "metadata": {}, "source": [ "Offering everyone would make a top box 1.3742 times as likely as offering no one (interval 1.2846\n", "to 1.4700). The odds ratio, 2.1379, is further from 1, as it always is when the rate rises, and the\n", "gap is large because a top box is common here. Like the ATE, both compare everyone with no one." ] }, { "cell_type": "markdown", "id": "direct-heading", "metadata": {}, "source": [ "## Does the offer help beyond the 7-day visit?\n", "\n", "If the program could guarantee every patient a primary-care visit within 7 days, would the offer\n", "still help? `replace(design, intermediate=\"pcp_visit_7d\")` names the visit column, and\n", "`intermediate_learner` predicts it. `ControlledDirectEffect(intermediate=1.0,\n", "contrast=ATE(reference=0))` sets every visit to yes (1.0) and asks for offer minus no offer. The\n", "fit uses every patient for every model (`CrossFitting(enabled=False)`), because that is the setup\n", "its simulation study checks; `cleverly` does not cross-fit this fit with missing outcomes. Its\n", "added conditions include that every kind of patient, offered or not, had a real chance of a visit,\n", "that no unrecorded factor drives both the visit and the outcome, and that answering the survey\n", "does not depend on the visit, as the graph assumes." ] }, { "cell_type": "code", "execution_count": 10, "id": "direct-effect", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:04:08.980614Z", "iopub.status.busy": "2026-11-13T23:04:08.980128Z", "iopub.status.idle": "2026-11-13T23:04:09.025906Z", "shell.execute_reply": "2026-11-13T23:04:09.025064Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "effect with every visit held at yes 0.1153 (0.0592, 0.1724) true 0.1160 supported\n", "effect with the visit left to follow the offer 0.1828 (0.1448, 0.2199) true 0.1649 supported\n" ] } ], "source": [ "from cleverly import ControlledDirectEffect\n", "\n", "visit_study = CausalStudy(\n", " frame, design=replace(design, intermediate=\"pcp_visit_7d\"), protocol=protocol\n", ")\n", "held_at_yes = ControlledDirectEffect(intermediate=1.0, contrast=ATE(reference=0))\n", "in_sample = TMLEMethod(\n", " models=ModelSpec(\n", " outcome_learner=with_products(),\n", " treatment_learner=logistic(),\n", " missingness_learner=logistic(),\n", " intermediate_learner=logistic(),\n", " ),\n", " cross_fitting=CrossFitting(enabled=False),\n", " runtime=Runtime(random_state=2031, n_jobs=1),\n", ")\n", "direct_fit = visit_study.identify(held_at_yes).estimate(method=in_sample)\n", "line(\"effect with every visit held at yes\", direct_fit[\"ate\"], truth[\"cde_ate[visit=1]\"])\n", "line(\"effect with the visit left to follow the offer\", ate_fit[\"ate\"], truth[\"ate\"])" ] }, { "cell_type": "markdown", "id": "direct-reading", "metadata": {}, "source": [ "With every patient's visit set to yes, the offer still raises the top-box rate by 0.1153\n", "(interval 0.0592 to 0.1724), which contains the true 0.1160. So the offer does more than produce\n", "the visit. The ATE beside it lets the visit follow the offer; the two come from different fits, so\n", "the page gives no interval for their difference. Holding the visit at no could give another answer,\n", "so the gap does not measure how much of the effect the visit explains." ] }, { "cell_type": "markdown", "id": "assessment-heading", "metadata": {}, "source": [ "## Check the overlap and the models\n", "\n", "The gain predicts every patient's outcome with the offer, so every kind of patient needs a real\n", "chance of the offer and of answering under it. The correction step divides by those chances, so a\n", "chance near zero gives a few patients huge weights. The fit therefore caps each model's chances at\n", "0.0095 for the offer and 0.01 for answering. The outcome, offer and response models are what the\n", "code calls nuisance models. A model's calibration slope is 1 when its probabilities are right on\n", "average, and below 1 when they are too extreme." ] }, { "cell_type": "code", "execution_count": 11, "id": "assessment", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:04:09.027658Z", "iopub.status.busy": "2026-11-13T23:04:09.027153Z", "iopub.status.idle": "2026-11-13T23:04:09.116230Z", "shell.execute_reply": "2026-11-13T23:04:09.115422Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "gain fit, checks that need attention: none\n", " smallest chance of an option: 0.025\n", " smallest chance of answering under an option: 0.268\n", " smallest chance of an option and answering: 0.0249\n", " share of patients at the caps: 0.0000\n", " offer model calibration slope: 1.00 (standard error 0.05)\n", " response model calibration slope: 0.98 (standard error 0.07)\n", " outcome model calibration slope: 0.95 (standard error 0.07)\n", " problems the model checks found: none\n", " correction step solved its equations: PASS\n", "\n", "direct-effect fit, checks that need attention: none\n", " smallest chance of a visit: 0.119\n", " smallest chance of an option, answering, and a visit: 0.0045\n", " share of patients at the caps: 0.0000\n" ] } ], "source": [ "assessment = gain_fit.assess()\n", "support = assessment.report(\"support\")\n", "nuisance = assessment.report(\"nuisance_models\")\n", "scores = assessment.report(\"score_equations\")\n", "models = {model.name: model.metrics for model in nuisance.models}\n", "attention = tuple(item.name for item in assessment.attention)\n", "# Delta is the 0/1 response indicator, R in the graph.\n", "answering = support.mechanisms[\"P(Delta=1|A,W)\"]\n", "joint = support.mechanisms[\"P(A=a,Delta=1|W)\"]\n", "print(\"gain fit, checks that need attention:\", attention or \"none\")\n", "print(f\" smallest chance of an option: {support.truncated['most_extreme']:.3f}\")\n", "print(f\" smallest chance of answering under an option: {answering['min']:.3f}\")\n", "print(f\" smallest chance of an option and answering: {joint['min']:.4f}\")\n", "print(f\" share of patients at the caps: {joint['clipped_fraction']:.4f}\")\n", "for name, label in ((\"propensity\", \"offer\"), (\"missingness\", \"response\"), (\"outcome\", \"outcome\")):\n", " slope, slope_se = models[name][\"calibration_slope\"], models[name][\"calibration_slope_se\"]\n", " print(f\" {label} model calibration slope: {slope:.2f} (standard error {slope_se:.2f})\")\n", "print(\" problems the model checks found:\", len(nuisance.findings) or \"none\")\n", "print(f\" correction step solved its equations: {'PASS' if scores.passed else 'FAIL'}\")\n", "print()\n", "direct_assessment = direct_fit.assess()\n", "direct_support = direct_assessment.report(\"support\").mechanisms\n", "direct_attention = tuple(item.name for item in direct_assessment.attention)\n", "print(\"direct-effect fit, checks that need attention:\", direct_attention or \"none\")\n", "print(f\" smallest chance of a visit: {direct_support['P(Z=1|A,W)']['min']:.3f}\")\n", "triple = direct_support[\"P(A=a,Delta=1,Z=z|W)\"]\n", "print(f\" smallest chance of an option, answering, and a visit: {triple['min']:.4f}\")\n", "print(f\" share of patients at the caps: {triple['clipped_fraction']:.4f}\")" ] }, { "cell_type": "markdown", "id": "assessment-reading", "metadata": {}, "source": [ "Nothing needs attention in either fit, and no patient reached a cap. For the gain, the smallest\n", "chances are above the caps and the calibration slopes sit near 1. The correction step adjusts the\n", "outcome model until its weighted errors average zero, which the interval relies on, and `PASS`\n", "says it got there. A check that needs attention, or a `FAIL`, would mean fixing the models or the\n", "data before reporting the estimate. The direct-effect fit is thinner: one patient's chance of their\n", "offer, an answer, and a visit together is 0.0045. The caps apply to each model, not to this\n", "product, so a few respondents carry large weights, which widens its interval." ] }, { "cell_type": "markdown", "id": "tilt-heading", "metadata": {}, "source": [ "## What if non-responders differ in ways we can't see?\n", "\n", "The worry is that offered patients with a poor transition skipped the survey more often, and so\n", "did patients without the offer whose transition went well; either makes the true gain smaller. This\n", "check moves the missing outcomes that way step by step and recomputes the gain without refitting\n", "(`missingness_tilt`). At a given `gamma`, the odds of a top box among non-responders are\n", "`exp(gamma)` times lower than among comparable respondents with the offer, and that many times\n", "higher without it. The code calls each option, offer or no offer, an arm." ] }, { "cell_type": "code", "execution_count": 12, "id": "tilt", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:04:09.117893Z", "iopub.status.busy": "2026-11-13T23:04:09.117349Z", "iopub.status.idle": "2026-11-13T23:04:33.461428Z", "shell.execute_reply": "2026-11-13T23:04:33.460770Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " gamma odds factor gain\n", " 0.0 1.0000 0.0956\n", " 0.5 1.6487 0.0676\n", " 1.0 2.7183 0.0403\n", " 1.5 4.4817 0.0162\n", " 2.0 7.3891 -0.0030\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "gamma at which the gain reaches 0: 1.912 (odds factor 6.77)\n", "the same, moving only the missing outcomes with the offer: none in the range searched\n" ] } ], "source": [ "from cleverly.sensitivity import missingness_tilt\n", "\n", "# For your own data, arm_gamma gives each option (arm) its direction: here a positive gamma\n", "# raises the missing outcomes without the offer (0) and lowers those with it (1).\n", "direction = {0: 1.0, 1: -1.0}\n", "curve = missingness_tilt(gain_fit, (0.0, 0.5, 1.0, 1.5, 2.0), arm_gamma=direction).to_frame()\n", "curve[\"gain\"] = -curve[\"psi\"]\n", "curve[\"odds factor\"] = np.exp(curve[\"gamma\"])\n", "print(curve[[\"gamma\", \"odds factor\", \"gain\"]].round(4).to_string(index=False))\n", "print()\n", "both = gain_fit.sensitivity.tipping_gamma(\"par\", arm_gamma=direction)\n", "offered_only = gain_fit.sensitivity.tipping_gamma(\"par\", arm_gamma={0: 0.0, 1: -1.0})\n", "print(f\"gamma at which the gain reaches 0: {both:.3f} (odds factor {np.exp(both):.2f})\")\n", "found = \"none in the range searched\" if offered_only is None else f\"{offered_only:.3f}\"\n", "print(\"the same, moving only the missing outcomes with the offer:\", found)" ] }, { "cell_type": "markdown", "id": "tilt-reading", "metadata": {}, "source": [ "The gain falls as `gamma` grows and reaches zero at 1.912, an odds factor of 6.77 in both\n", "directions. For scale, the offer itself multiplies the odds of a top box by about 2 (the\n", "odds ratio above). Moving only the offered non-responders never erases the gain in the range\n", "searched. Whether the survey could miss that strongly is a judgment about this program.\n", "\n", ":::{dropdown} Details: how the outcomes are moved\n", "This is a pattern-mixture analysis. Within each arm and covariate profile, it adds `gamma` times\n", "the arm's multiplier in `arm_gamma` to the logit of the fitted respondents' mean, so with\n", "`{0: 1.0, 1: -1.0}` a positive `gamma` raises the unobserved mean without the offer and lowers it\n", "with the offer. Each row starts from the main fit's outcome and response models and runs a new\n", "correction step for the moved assumption. The PAR moves through both of its parts, the rate under current\n", "practice and the rate if every patient got the offer. Each value comes from the fitted outcome\n", "model, so it carries that model's error.\n", ":::" ] }, { "cell_type": "markdown", "id": "sensitivity-heading", "metadata": {}, "source": [ "## What if a confounder is missing?\n", "\n", "A missing confounder is an unrecorded factor that drives both the offer and the outcome. Today's\n", "rate compares no options, so a missing confounder cannot bias it, but it can bias the rate if\n", "everyone got the offer. This check bounds that rate (`CounterfactualMean(treatment=1)`) and\n", "subtracts today's. The confounder has two strengths, each a share from 0 to 1: on the outcome side\n", "(`cf_y`), how much of the outcome's remaining variation it explains, and on the weight side\n", "(`cf_d`), how much it changes the correction weights, roughly how strongly it tracks who gets the\n", "offer beyond the recorded characteristics. Each recorded characteristic serves as a yardstick\n", "(`benchmark`, `omitted_confounding`)." ] }, { "cell_type": "code", "execution_count": 13, "id": "sensitivity", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:04:33.463610Z", "iopub.status.busy": "2026-11-13T23:04:33.463443Z", "iopub.status.idle": "2026-11-13T23:04:34.043988Z", "shell.execute_reply": "2026-11-13T23:04:34.043169Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "rate if everyone got the offer: 0.6711, today: 0.5756\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "a confounder as strong as discharge_risk:\n", " outcome-side strength, cf_y 0.041\n", " weight-side strength, cf_d 0.047\n", " range of the gain [0.0623, 0.1289]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "a confounder as strong as age:\n", " outcome-side strength, cf_y 0.000\n", " weight-side strength, cf_d 0.000\n", " range of the gain [0.0956, 0.0956]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "a confounder as strong as prior_utilization:\n", " outcome-side strength, cf_y 0.012\n", " weight-side strength, cf_d 0.008\n", " range of the gain [0.0882, 0.1030]\n", "\n", "weight-side strength that erases the gain at cf_y = 1: 0.016\n" ] } ], "source": [ "from cleverly import CounterfactualMean\n", "\n", "everyone_fit = study.identify(CounterfactualMean(treatment=1)).estimate(method=method)\n", "today = current_fit[\"ey_obs\"].psi\n", "sensitivity = everyone_fit.sensitivity\n", "print(f\"rate if everyone got the offer: {everyone_fit['ey1'].psi:.4f}, today: {today:.4f}\")\n", "\n", "# For your own data, benchmark against every recorded confounder.\n", "benchmarks = {}\n", "for covariate in covariates:\n", " record = sensitivity.benchmark(covariates=(covariate,))\n", " bound = sensitivity.omitted_confounding(benchmark=record)\n", " benchmarks[covariate] = (record, bound)\n", " print()\n", " print(f\"a confounder as strong as {covariate}:\")\n", " print(f\" outcome-side strength, cf_y {record.cf_y:.3f}\")\n", " print(f\" weight-side strength, cf_d {record.cf_d:.3f}\")\n", " print(f\" range of the gain [{bound.lower - today:.4f}, {bound.upper - today:.4f}]\")\n", "\n", "# The weight-side strength at which the lowest everyone-offered rate reaches today's rate, for a\n", "# confounder that explains all the remaining outcome variation (cf_y = 1), found by bisection.\n", "low, high = 0.0, 0.99\n", "for _ in range(40):\n", " middle = (low + high) / 2\n", " if sensitivity.omitted_confounding(cf_y=1.0, cf_d=middle).lower > today:\n", " low = middle\n", " else:\n", " high = middle\n", "tipping_cf_d = (low + high) / 2\n", "print()\n", "print(f\"weight-side strength that erases the gain at cf_y = 1: {tipping_cf_d:.3f}\")" ] }, { "cell_type": "markdown", "id": "sensitivity-reading", "metadata": {}, "source": [ "A confounder as strong as `discharge_risk`, the strongest recorded one, would leave the gain\n", "between 0.0623 and 0.1289. This range ignores sampling error. The recorded characteristics explain\n", "little of the outcome left after the offer (outcome-side strengths of 0.041 or less), so a hidden\n", "factor could be far stronger on that side. One that explained all of it would erase the gain with\n", "a weight-side strength of only 0.016, below the 0.047 of `discharge_risk`. So the gain survives\n", "confounders like the recorded ones but not a much stronger unrecorded cause of the outcome, such\n", "as support at home, that also sways who gets the offer. Only program staff can judge whether one\n", "exists.\n", "\n", ":::{dropdown} Details: what the strengths mean\n", "`cf_y` is the share of the outcome variation, left after the offer and the recorded\n", "characteristics, that a missing confounder explains. `cf_d` is the share of the second moment of\n", "the Riesz representer that only the missing confounder adds. For the rate if everyone got the\n", "offer, the representer combines the inverse offer probability and the inverse response\n", "probability. The bound uses `rho = 1`, the worst case, and it reads the point estimate only.\n", "`benchmark()` refits without one covariate and reports the gain in fit as proxies for these\n", "strengths, clipped at 0; `age` reads 0 because without it the outcome fits no worse and the weights\n", "vary no less. These simulated data have no hidden confounder, so the bounds are stress tests.\n", "[Omitted-variable bounds](../technical-reference/validation-methods.md#omitted-variable-bounds-robustness-value-benchmark-and-contours)\n", "defines each quantity.\n", ":::" ] }, { "cell_type": "markdown", "id": "interpret", "metadata": {}, "source": [ "## What we can and can't conclude\n", "\n", "For the manager: offering navigation to every eligible patient would raise the 30-day top-box rate\n", "by about 0.096 (95% interval 0.074 to 0.117) over current practice, counting patients who never\n", "answer the survey. Current practice already adds about 0.087 over offering no one, which is why\n", "the everyone-against-no-one effect of 0.183 is the wrong number for this decision. A guaranteed\n", "7-day visit would not replace the offer, which still helps with every visit set to yes.\n", "\n", "These answers rest on assumptions the data cannot check. Non-responders must have answered like\n", "comparable respondents; erasing the gain would take a departure with an odds factor of 6.77 in both\n", "arms at once. No unrecorded factor may drive both the offer and the outcome, and one that predicts\n", "the outcome well could erase the gain. The direct effect needs the same for the visit. The page\n", "shows one simulated sample with a known answer, which does not show how the methods perform in\n", "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 fit on other simulated data. They all have outcomes missing at\n", "random and one characteristic with three levels, and they fit decision trees or give the method\n", "the true model predictions:\n", "\n", "| section | study | what it uses |\n", "| --- | --- | --- |\n", "| today's rate | [stacked missing-outcome natural-course CV-TMLE](../technical-reference/method-evidence/stacked-missing-outcome-natural-course-cvtmle.md) | ten folds, as here |\n", "| the gain and what current practice achieves, with their shares | [missing-outcome attributable effects](../technical-reference/method-evidence/missing-outcome-attributable-effects-tmle.md) | ten folds in one scenario, as here |\n", "| the ATE, the ratios, and the rate under the offer | [stacked arm-indexed missing-outcome CV-TMLE](../technical-reference/method-evidence/stacked-arm-indexed-missing-outcome-cvtmle.md) | ten folds, as here |\n", "| the effect with the visit held at yes | [controlled direct-effect TMLE](../technical-reference/method-evidence/controlled-direct-effect-tmle.md) | in sample, as here, against R `tmle` 2.1.1 |\n", "\n", "CV-TMLE is the cross-fitted TMLE used here. No study uses this page's logistic models on\n", "continuous characteristics, so `supported` here means the estimator is checked, not this exact\n", "setup. The direct-effect study gives both implementations the true\n", "model predictions, so it does not check models fitted from data. The confounder bounds and the\n", "checks below print numbers without a pass or fail (`descriptive`), because their studies cover\n", "fits without missing outcomes or fits in sample. The\n", "[technical entry](../technical-reference/point-treatment-tmle.md#validation-issues-special-to-this-method)\n", "lists the methods' evidence and limits." ] }, { "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 20 times each. They run on the ATE fit,\n", "because `cleverly` runs them on a comparison of the two options:\n", "\n", "- `placebo` shuffles the offer, so the estimate should be about zero;\n", "- `random_common_cause` adds a column of noise, so the estimate should barely move;\n", "- `subset` refits on random 70% samples, so the estimates should spread about as much as the\n", " standard error implies for 70% subsamples of these data (0.0126 here)." ] }, { "cell_type": "code", "execution_count": 14, "id": "refutation", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:04:34.045626Z", "iopub.status.busy": "2026-11-13T23:04:34.045136Z", "iopub.status.idle": "2026-11-13T23:04:42.868770Z", "shell.execute_reply": "2026-11-13T23:04:42.867686Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " test original refuted_mean refuted_sd expectation verdict\n", " placebo 0.1828 0.0015 0.0197 ~ 0 descriptive\n", " subset 0.1828 0.1873 0.0114 scatter ~ 0.01256 descriptive\n", "random_common_cause 0.1828 0.1827 0.0009 ~ 0.1828 descriptive\n" ] } ], "source": [ "from cleverly.validation import refute\n", "\n", "refutation = refute(ate_fit, tests=(\"placebo\", \"subset\", \"random_common_cause\"))\n", "columns = [\"test\", \"original\", \"refuted_mean\", \"refuted_sd\", \"expectation\", \"verdict\"]\n", "print(refutation.to_frame()[columns].round(4).to_string(index=False))" ] }, { "cell_type": "markdown", "id": "refutation-reading", "metadata": {}, "source": [ "All three behave as expected: the shuffled offer gives an estimate near zero, the noise column\n", "barely moves it, and the 70% refits spread about as much as the standard error predicts. These\n", "checks test the method, so they cannot detect a hidden confounder or a survey that is not missing\n", "at random. The `verdict` column reads `descriptive`: `cleverly` gives a pass or fail only when a\n", "simulation study backs the check for this kind of fit, and none covers a fit with missing\n", "outcomes.\n", "\n", "The [missing survey answers](survey-nonresponse.ipynb) page tests the method on outcomes with a\n", "known effect when some outcomes are missing. Its limits hold here too: these data record no outcome\n", "before the offer that the offer cannot change, so no negative-control check runs, and `cleverly`\n", "refuses the hidden-confounder simulation (`simulated_confounding`) because the offer changes who\n", "answers ([roadmap item F12](../roadmap.md#f12-missing-outcome-simulated-confounding-replay))." ] }, { "cell_type": "markdown", "id": "evalue-heading", "metadata": {}, "source": [ "### How strong would a confounder be on a risk-ratio scale?\n", "\n", "The E-value asks how strongly a missing confounder would need to be linked to both the offer and\n", "the top-box outcome, as a risk ratio, to explain the risk ratio away. Epidemiology papers often\n", "report it." ] }, { "cell_type": "code", "execution_count": 15, "id": "evalue", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:04:42.870837Z", "iopub.status.busy": "2026-11-13T23:04:42.870251Z", "iopub.status.idle": "2026-11-13T23:04:42.882769Z", "shell.execute_reply": "2026-11-13T23:04:42.882315Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " E-value\n", "==============================================================================\n", "Question: how strong a confounder Estimate: rr\n", " would explain away rr Scale: risk ratio\n", "==============================================================================\n", " risk ratio E-value\n", "------------------------------------------------------------------------------\n", "estimate 1.374 2.09\n", "95% limit nearest the null 1.285 1.89\n", "==============================================================================\n", "An unmeasured confounder would need a risk ratio of 2.09 with both the\n", "treatment and the outcome, beyond the measured covariates, to explain away the\n", "estimate; 1.89 to move the interval to the null.\n", "Notes:\n", "[1] 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" ] } ], "source": [ "evalue = rr_fit.sensitivity.evalue()\n", "print(evalue.summary())" ] }, { "cell_type": "markdown", "id": "evalue-reading", "metadata": {}, "source": [ "A weaker link to one of the offer and the outcome can be offset by a stronger link to the other.\n", "The E-value is about everyone against no one; it is not a bound on the gain over current practice." ] }, { "cell_type": "markdown", "id": "where-next", "metadata": {}, "source": [ "## Where to go next\n", "\n", "The [survey non-response example](survey-nonresponse.ipynb) treats unreturned surveys in more\n", "depth, with a continuous score and the everyone-against-no-one question. The technical entry's\n", "sections on [population interventions](../technical-reference/point-treatment-tmle.md#population-interventions)\n", "and [missing outcomes and controlled direct effects](../technical-reference/point-treatment-tmle.md#missing-outcomes-and-controlled-direct-effects)\n", "give the exact estimators. The [examples index](index.md) lists every example." ] } ], "metadata": { "cleverly_execution": { "command": [ "python", "scripts/execute_notebook.py", "docs/examples/population-impact.ipynb" ], "gated": { "code_source_sha256": "d7856df6c18f7964e7ecbbb563f256a1817747e393abb9f4ce2121a7f1bc1cf1", "execution_payload_sha256": "c9d565a483423862a65c2ad3492f940596716447a1d23c3bccd166e704cac337" }, "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 }