{ "cells": [ { "cell_type": "markdown", "id": "title", "metadata": {}, "source": [ "# More contacts and more service time: TMLE for policy effects\n", "\n", "## At a glance\n", "\n", "A transition program follows patients home from hospital. Its discharge team puts each patient on\n", "a low, medium, or high schedule of follow-up contacts, and sets their hours of navigator time and\n", "minutes of pharmacist review. The program's owner has two ideas. The first nudges the team, for\n", "example with a default or a prompt, so that each patient's odds of the high schedule double while\n", "the team still chooses: a patient with a 20% chance of it would have about 33%. The second raises\n", "both service times.\n", "\n", "Doubling each patient's odds of the high schedule would raise the average 30-day transition score (0\n", "is worst, 1 is best) by 0.021, with a 95% confidence interval of 0.019 to 0.023: about an eighth of\n", "the true 0.17 gap between putting every patient on the high schedule and every patient on the low\n", "one. Adding half an hour of navigator time and five minutes of pharmacist review would raise the\n", "share of successful transitions (a score of at least 0.7) by 0.075 (7.5 percentage points, interval\n", "0.062 to 0.087). In these data the two services help each other, so that is more than the two raises\n", "give apart; the size of that extra is checked only by the page's own repeated draws (Details), not\n", "by a simulation study of the method.\n", "\n", "Simple comparisons understate both answers several times over, because the team gives more to\n", "higher-risk patients, who do worse. Both answers assume the recorded characteristics capture\n", "everything that drove the team's choices.\n", "\n", "The data are simulated, so we know the true effects (0.021 and 0.073), and each interval contains\n", "its value." ] }, { "cell_type": "markdown", "id": "plan", "metadata": {}, "source": [ "## The question\n", "\n", "The team will keep choosing schedules, so the first question is what happens if each patient's\n", "chances shift toward the intensive schedules. Service time is a dose, a number of hours or minutes,\n", "so the second question is what happens if each patient's own dose goes up a little.\n", "\n", "The first answer changes odds. A patient with a 20% chance of the high schedule and a 50% chance\n", "of the low one has odds of 0.4 for high against low; doubling makes them 0.8. Every patient keeps\n", "a chance of every schedule. The second answer adds a fixed amount to each patient's recorded dose,\n", "up to a limit.\n", "\n", "In the graph, an arrow means \"affects\". W is the recorded characteristics, A the schedule (or the\n", "two doses), Y the outcome, and U any unrecorded factor.\n", "\n", "```text\n", " W ──▶ A ──▶ Y ◀── U\n", " │ ▲\n", " └───────────┘\n", "\n", " W = discharge_risk, age, and baseline_support_need (first question);\n", " discharge_risk, age, and medication_burden (second question)\n", " A = cadence, the contact schedule (first question);\n", " navigator_hours and pharmacist_minutes (second question)\n", " Y = transition_score at day 30 (first question);\n", " transition_success at day 30 (second question)\n", " U = anything unrecorded that affects the outcome\n", "```\n", "\n", "The characteristics affect both what the team gives and how the patient does, so they are\n", "confounders, and the analysis adjusts for them. U has no arrow into A: we assume nothing\n", "unrecorded drove the team's choices." ] }, { "cell_type": "markdown", "id": "setup-heading", "metadata": {}, "source": [ "## The data\n", "\n", "Every fit sets its seeds, so a rerun prints the same numbers. Another version of `cleverly` can\n", "print slightly different numbers." ] }, { "cell_type": "code", "execution_count": 1, "id": "setup", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:04:46.355705Z", "iopub.status.busy": "2026-11-13T23:04:46.355553Z", "iopub.status.idle": "2026-11-13T23:04:47.999930Z", "shell.execute_reply": "2026-11-13T23:04:47.998590Z" } }, "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 LinearRegression, LogisticRegression\n", "from sklearn.pipeline import make_pipeline\n", "from sklearn.preprocessing import PolynomialFeatures, StandardScaler\n", "\n", "import cleverly\n", "\n", "pd.set_option(\"display.width\", 130)\n", "pd.set_option(\"display.max_columns\", 20)\n", "print(\"cleverly\", cleverly.__version__)" ] }, { "cell_type": "markdown", "id": "data-heading", "metadata": {}, "source": [ "`make_contact_schedules` draws 3,000 simulated discharges and the true answers. `TILTS` names each\n", "odds change (also called a tilt) and the factor on each schedule's odds. Current practice\n", "multiplies nothing, written as a factor of 1 on the low schedule." ] }, { "cell_type": "code", "execution_count": 2, "id": "data", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:04:48.002426Z", "iopub.status.busy": "2026-11-13T23:04:48.001622Z", "iopub.status.idle": "2026-11-13T23:04:48.306032Z", "shell.execute_reply": "2026-11-13T23:04:48.304540Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "rows and columns: (3000, 5)\n", "column names: ['transition_score', 'cadence', 'discharge_risk', 'age', 'baseline_support_need']\n", " transition_score cadence discharge_risk age baseline_support_need\n", "0 0.135 medium 1.351 0.343 -1.163\n", "1 0.458 medium -0.187 -0.339 -0.228\n", "2 0.511 high 0.597 -1.279 0.967\n", "3 0.332 low -1.128 -0.188 0.887\n", "4 0.274 low 0.664 -0.691 1.769\n", "\n", "true average score if every patient got one schedule:\n", " low 0.478\n", " medium 0.544\n", " high 0.652\n", "true change in the average score under each odds change:\n", " medium and high doubled +0.0147\n", " high doubled +0.0208\n" ] } ], "source": [ "from cleverly.datasets import make_contact_schedules\n", "\n", "# Each odds change names the schedules whose odds it multiplies, compared with the low schedule.\n", "# A schedule it leaves out keeps its current odds. For your own data, use your own labels.\n", "# Results are named by kind: ey[low] is the average if every patient got that schedule,\n", "# ey_ipsi[name] the average under an odds change, and ate_ipsi[name vs current practice] its\n", "# change against current practice (ate: average treatment effect; ipsi: incremental propensity-score\n", "# intervention, where a propensity score is a patient's chance of each schedule).\n", "TILTS = {\n", " \"current practice\": {\"low\": 1.0},\n", " \"medium and high doubled\": {\"medium\": 2.0, \"high\": 2.0},\n", " \"high doubled\": {\"high\": 2.0},\n", "}\n", "SCHEDULES = [\"low\", \"medium\", \"high\"]\n", "# With your own data, load your data frame here, such as frame = pd.read_csv(...).\n", "# Real data have no `truth`: delete the lines that print only it, and remove it from the rest.\n", "frame, truth = make_contact_schedules(n=3_000, seed=24, tilts=TILTS)\n", "print(\"rows and columns:\", frame.shape)\n", "print(\"column names:\", list(frame.columns))\n", "print(frame.head().round(3).to_string())\n", "print()\n", "print(\"true average score if every patient got one schedule:\")\n", "for level in SCHEDULES:\n", " print(f\" {level:7s} {truth[f'ey[{level}]']:.3f}\")\n", "print(\"true change in the average score under each odds change:\")\n", "for name in list(TILTS)[1:]:\n", " print(f\" {name:24s} {truth[f'ate_ipsi[{name} vs current practice]']:+.4f}\")" ] }, { "cell_type": "markdown", "id": "data-reading", "metadata": {}, "source": [ "Each row is one discharge: the day-30 score, the schedule (`cadence`), and three characteristics\n", "measured before the schedule was set, each scaled to average 0 and spread 1. An odds change alters\n", "the schedule of only some patients, so its true effect is far smaller than the gap between\n", "all-high and all-low." ] }, { "cell_type": "markdown", "id": "association-heading", "metadata": {}, "source": [ "## Why a simple comparison misleads\n", "\n", "A first guess applies the odds change to the overall share on each schedule and keeps each\n", "schedule's raw average." ] }, { "cell_type": "code", "execution_count": 3, "id": "association", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:04:48.307900Z", "iopub.status.busy": "2026-11-13T23:04:48.307692Z", "iopub.status.idle": "2026-11-13T23:04:48.327751Z", "shell.execute_reply": "2026-11-13T23:04:48.327170Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " share average_score discharge_risk age true_average\n", "cadence \n", "low 0.331 0.532 -0.430 0.076 0.478\n", "medium 0.316 0.568 -0.014 -0.245 0.544\n", "high 0.352 0.571 0.432 0.165 0.652\n", "\n", "change in the average score: the simple answer, and the true change\n", " medium and high doubled simple +0.0050 true +0.0147\n", " high doubled simple +0.0036 true +0.0208\n" ] } ], "source": [ "observed = frame.groupby(\"cadence\").agg(\n", " share=(\"transition_score\", \"size\"),\n", " average_score=(\"transition_score\", \"mean\"),\n", " discharge_risk=(\"discharge_risk\", \"mean\"),\n", " age=(\"age\", \"mean\"),\n", ")\n", "observed = observed.loc[SCHEDULES]\n", "observed[\"share\"] = observed[\"share\"] / len(frame)\n", "observed[\"true_average\"] = [truth[f\"ey[{level}]\"] for level in SCHEDULES] # simulated data only\n", "print(observed.round(3).to_string())\n", "print()\n", "\n", "\n", "def simple_answer(factors):\n", " \"\"\"Apply the odds change to the overall shares, and keep each schedule's raw average.\"\"\"\n", " weight = observed[\"share\"] * np.array([factors.get(level, 1.0) for level in SCHEDULES])\n", " return float((weight * observed[\"average_score\"]).sum() / weight.sum())\n", "\n", "\n", "simple = {\n", " name: simple_answer(TILTS[name]) - simple_answer(TILTS[\"current practice\"]) for name in TILTS\n", "}\n", "print(\"change in the average score: the simple answer, and the true change\")\n", "for name in list(TILTS)[1:]:\n", " true_change = truth[f\"ate_ipsi[{name} vs current practice]\"]\n", " print(f\" {name:24s} simple {simple[name]:+.4f} true {true_change:+.4f}\")" ] }, { "cell_type": "markdown", "id": "association-reading", "metadata": {}, "source": [ "The simple answers are about a third and a sixth of the true changes. The high-schedule patients\n", "have the highest discharge risk (0.432 on average, against -0.430 on the low schedule), and higher\n", "risk lowers the score. So the high schedule's raw average is barely above the low one's, because\n", "it goes to patients who would do worse anyway: this is confounding by discharge risk." ] }, { "cell_type": "markdown", "id": "protocol-heading", "metadata": {}, "source": [ "## Set up the analysis\n", "\n", "The study description (`StudyProtocol`) is optional and does not change the estimate. It writes\n", "down who the answer is about, what is compared, and how deaths count, and every result keeps a\n", "link to it. `replace` changes the fields this\n", "question changes." ] }, { "cell_type": "code", "execution_count": 4, "id": "protocol", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:04:48.329814Z", "iopub.status.busy": "2026-11-13T23:04:48.329647Z", "iopub.status.idle": "2026-11-13T23:04:48.336565Z", "shell.execute_reply": "2026-11-13T23:04:48.335580Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Population: Adults with a discharge-home order at a participating hospital during the enrollment period\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 schedule is set\n", "Strategies: Keep each patient's current chances of the three contact schedules; Double each patient's odds of the medium and the high schedule against the low one; Double each patient's odds of the high schedule against the other two\n", "Versions: The schedule as the discharge team assigns it today; A schedule drawn at random with the changed chances, given the recorded characteristics; A schedule drawn at random with the changed chances, given the recorded characteristics\n", "Outcome: Patient-reported transition score at day 30, from 0 (worst) to 1 (best)\n", "Horizon: 30 days after discharge\n", "Intercurrent events: Use the transition score regardless of readmission; Analyze the assigned schedule regardless of completed contacts; A death before day 30 counts as a score of 0 (composite strategy)\n", "Interference unit: Individual patient\n", "Rationale: The recorded characteristics cover the common causes of the schedule and the score; Every schedule uses the same scripts and access rules, so each schedule is one well-defined action and a patient's recorded score is the score they would have had under the schedule 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 cleverly.StudyProtocol(...). It needs all ten fields, each a short\n", "# text or a list of texts:\n", "# target_population, eligibility: who the answer is about, and the entry rules;\n", "# time_zero, horizon: when follow-up starts, and when the outcome is measured;\n", "# treatment_strategies, treatment_versions: the options compared, and their variants;\n", "# outcome: the measured result;\n", "# intercurrent_event_handling: how events such as death before the horizon count;\n", "# interference_unit: the unit whose treatment can affect only its own outcome;\n", "# assumption_rationale: why the design makes the causal assumptions believable.\n", "# Here the program's own description supplies the fields this question keeps (the program.*\n", "# values, printed below). For your own study, write every field as your own text.\n", "program = navigation_protocol()\n", "protocol = replace(\n", " program,\n", " time_zero=\"Discharge-home order, after baseline measurement and before the schedule is set\",\n", " treatment_strategies=(\n", " \"Keep each patient's current chances of the three contact schedules\",\n", " \"Double each patient's odds of the medium and the high schedule against the low one\",\n", " \"Double each patient's odds of the high schedule against the other two\",\n", " ),\n", " treatment_versions=(\n", " \"The schedule as the discharge team assigns it today\",\n", " \"A schedule drawn at random with the changed chances, given the recorded characteristics\",\n", " \"A schedule drawn at random with the changed chances, given the recorded characteristics\",\n", " ),\n", " outcome=\"Patient-reported transition score at day 30, from 0 (worst) to 1 (best)\",\n", " intercurrent_event_handling=(\n", " program.intercurrent_event_handling[0],\n", " \"Analyze the assigned schedule regardless of completed contacts\",\n", " \"A death before day 30 counts as a score of 0 (composite strategy)\",\n", " ),\n", " assumption_rationale=(\n", " \"The recorded characteristics cover the common causes of the schedule and the score\",\n", " \"Every schedule uses the same scripts and access rules, so each schedule is one \"\n", " \"well-defined action and a patient's recorded score is the score they would have had \"\n", " \"under the schedule they got\",\n", " program.assumption_rationale[2],\n", " ),\n", ")\n", "print(\"\\n\".join(protocol.summary_lines()))" ] }, { "cell_type": "markdown", "id": "protocol-reading", "metadata": {}, "source": [ "Under \"high doubled\" a patient is not promised the high schedule: the schedule is drawn with the\n", "changed chances. \"Regardless of completed contacts\" means the analysis compares assigned schedules,\n", "whether or not each patient completed every contact. A death before day 30 counts as a score of 0;\n", "the output calls this way of folding an event into the outcome the composite strategy." ] }, { "cell_type": "markdown", "id": "identify-heading", "metadata": {}, "source": [ "## What must be true for a causal answer\n", "\n", "Name the outcome, the treatment, and the characteristics to adjust for (`PointTreatment`, for one\n", "treatment decision per patient). `IncrementalEffect` takes the odds changes, each an `Incremental`\n", "with its factors and name, and the first is the comparison. `study.identify(...)` writes down what\n", "must be true for the answers to be causal." ] }, { "cell_type": "code", "execution_count": 5, "id": "identify", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:04:48.342606Z", "iopub.status.busy": "2026-11-13T23:04:48.342377Z", "iopub.status.idle": "2026-11-13T23:04:48.357394Z", "shell.execute_reply": "2026-11-13T23:04:48.356624Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "conditions the answer rests on:\n", " - consistency\n", " - no interference\n", " - no unmeasured confounding\n", " - no positivity assumption\n", " - the intervention is a functional of the observed-data law\n" ] } ], "source": [ "from cleverly import CausalStudy, IncrementalEffect, PointTreatment\n", "from cleverly.interventions import Incremental\n", "\n", "# For your own data, change the outcome and treatment names and the covariates.\n", "covariates = (\"discharge_risk\", \"age\", \"baseline_support_need\")\n", "study = CausalStudy(\n", " frame,\n", " design=PointTreatment(outcome=\"transition_score\", treatment=\"cadence\", adjustment=covariates),\n", " protocol=protocol,\n", ")\n", "tilts = study.identify(\n", " IncrementalEffect(tuple(Incremental(factors, name=name) for name, factors in TILTS.items()))\n", ")\n", "print(\"conditions the answer rests on:\")\n", "for condition in tilts.identification.assumptions:\n", " print(\" -\", condition.split(\":\")[0].replace(\"*\", \"\"))" ] }, { "cell_type": "markdown", "id": "identify-reading", "metadata": {}, "source": [ "The first three conditions need judgment, and the data cannot check them. \"Consistency\" means a\n", "schedule means the same contacts for every patient. \"No interference\" means one patient's schedule\n", "does not change another's score. \"No unmeasured confounding\" means the three characteristics\n", "capture everything that drove both the team's choice and the score.\n", "\n", "The fourth line is good news. Putting everyone on the high schedule would need every kind of\n", "patient to have a real chance of it (positivity), but doubling odds never gives a patient a\n", "schedule they had no chance of. The last line says the changed chances are built from the current\n", "chances, which the treatment model estimates." ] }, { "cell_type": "markdown", "id": "estimate-heading", "metadata": {}, "source": [ "## Estimate the effect of each odds change\n", "\n", "The method, targeted maximum likelihood estimation (TMLE), fits two models. The outcome model\n", "predicts the score from the schedule and the characteristics. The treatment model predicts each\n", "patient's chances of the three schedules, which the odds changes act on. A correction step then\n", "weights each patient by how much more likely the odds change makes their own schedule, which\n", "removes the bias the outcome model leaves. So this answer leans on the treatment model.\n", "\n", "- `outcome_learner`: a plain linear regression, deliberately too simple, as any outcome model may\n", " be. When the treatment model is right, the correction keeps the estimate on target (the Details\n", " cover the interval).\n", "- `treatment_learner`: a logistic regression that predicts all three schedules at once. It\n", " matches how the simulated data were made. On your own data, refit with a flexible learner, such\n", " as gradient boosting with `CrossFitting(n_folds=5)`. If the two estimates differ by more than\n", " about a standard error, the simple model missed part of how the team chooses; report the\n", " flexible fit." ] }, { "cell_type": "code", "execution_count": 6, "id": "estimate", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:04:48.359057Z", "iopub.status.busy": "2026-11-13T23:04:48.358898Z", "iopub.status.idle": "2026-11-13T23:04:48.763343Z", "shell.execute_reply": "2026-11-13T23:04:48.762342Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " Effect estimate (TMLE)\n", "==============================================================================\n", "Question: effect of cadence on Rows: 3,000\n", " transition_score; each Arm shares: high=0.352, low=0.331,\n", " row is defined below medium=0.316\n", "Outcome: transition_score Out-of-fold predictions: no\n", " (continuous) Outcome model: linear regression\n", "Adjusted for: discharge_risk, age, Treatment model: logistic regression\n", " baseline_support_need\n", "Method: targeted maximum\n", " likelihood (TMLE)\n", "==============================================================================\n", " estimate std. error 95% CI p-value\n", "------------------------------------------------------------------------------\n", "ate_ipsi[medium and high 0.01461 0.00084 [0.01295, 0.01628] <0.0001\n", "doubled vs current\n", "practice]\n", "ate_ipsi[high doubled vs 0.02090 0.00096 [0.01901, 0.02279] <0.0001\n", "current practice]\n", "==============================================================================\n", "What each row estimates\n", " meaning\n", "------------------------------------------------------------------------------\n", "ate_ipsi[medium and high doubled vs current practice] contrast of each tilt\n", " against the reference\n", " tilt\n", "ate_ipsi[high doubled vs current practice] contrast of each tilt\n", " against the reference\n", " tilt\n", "==============================================================================\n", "Simultaneous 95% bands\n", " band\n", "------------------------------------------------------------------------------\n", "ate_ipsi[medium and high doubled vs current practice] [0.01276, 0.01646]\n", "ate_ipsi[high doubled vs current practice] [0.01880, 0.02300]\n", "==============================================================================\n", "Notes:\n", "[1] The interval of ate_ipsi[medium and high doubled vs current practice],\n", " ate_ipsi[high doubled vs current practice] is widened on the side where a\n", " skewed outcome makes misses more likely, so it need not be centred on the\n", " estimate. Its t distribution has 250 or more degrees of freedom, so it is\n", " close to the normal one. The p-value is the level at which the interval\n", " would just reach the null value.\n", "[2] The bands cover all 2 rows at once with 95% probability; use them when you\n", " read several rows together. No validation study covers the bands for this\n", " kind of fit, so cleverly marks them experimental.\n", "\n", "medium and high doubled estimate +0.0146 95% CI (+0.0130, +0.0163) true +0.0147 supported\n", "high doubled estimate +0.0209 95% CI (+0.0190, +0.0228) true +0.0208 supported\n" ] } ], "source": [ "from cleverly import CrossFitting, Inference, ModelSpec, Runtime, Targeting, TMLEMethod\n", "\n", "# For your own data, swap in your own learners. CrossFitting(enabled=False) trains and uses each\n", "# model on all rows, which is safe for simple models; a flexible learner needs out-of-fold\n", "# predictions (CrossFitting(n_folds=5)). q_bounds declares the known range of the outcome, here\n", "# 0 to 1, so the correction keeps every prediction inside it. alpha=0.05 asks for 95% intervals.\n", "method = TMLEMethod(\n", " models=ModelSpec(\n", " outcome_learner=LinearRegression(),\n", " treatment_learner=LogisticRegression(max_iter=1000),\n", " ),\n", " cross_fitting=CrossFitting(enabled=False),\n", " targeting=Targeting(q_bounds=(0.0, 1.0)),\n", " inference=Inference(alpha=0.05),\n", " runtime=Runtime(random_state=24, n_jobs=1),\n", ")\n", "tilt_result = tilts.estimate(method=method)\n", "print(tilt_result.summary())\n", "print()\n", "for name in list(TILTS)[1:]:\n", " key = f\"ate_ipsi[{name} vs current practice]\"\n", " point = tilt_result[key]\n", " low, high = point.ci\n", " print(\n", " f\"{name:24s} estimate {point.psi:+.4f} 95% CI ({low:+.4f}, {high:+.4f}) \"\n", " f\"true {truth[key]:+.4f} {point.support.label}\"\n", " )" ] }, { "cell_type": "markdown", "id": "estimate-reading", "metadata": {}, "source": [ "Doubling the high odds raises the average score by 0.0209 (interval 0.0190 to 0.0228), and\n", "doubling the medium and high odds by 0.0146 (0.0130 to 0.0163). Both intervals contain the true\n", "values. In the summary, \"arm shares\" are the shares on each schedule (an arm is one treatment\n", "option), and the simultaneous bands cover both rows at once. The answers read `supported`: a validation\n", "study covers this kind of fit, though it does not check that this fit's models are right. A fit\n", "outside every study reads `experimental`.\n", "\n", ":::{dropdown} Details: which model must be right, and a repeated-draw check\n", "For an odds change, the error left after the correction step is a product of two errors: the\n", "error in the predicted average under the changed chances, which uses both models, and the\n", "treatment model's error. The [technical\n", "entry](../technical-reference/point-treatment-tmle.md#incremental-propensity-score-interventions)\n", "gives the exact form. A correct treatment model keeps the estimate centered on the truth whatever\n", "the outcome model. A correct outcome model alone does not, because the changed chances are built\n", "from the treatment model. A wrong outcome model can still make the interval too narrow: in the\n", "validation study, a right treatment model with a constant outcome model covered the truth on 89\n", "to 91% of draws.\n", "\n", "A simulation we ran for this page (`reviews/notebook-review/probes/schedules-and-intensity/sweep.py`\n", "in the `cleverly` repository) repeats this fit on 400 draws of the same simulated data. The\n", "interval contained the true change on 377 draws for doubling the medium and high odds and on 378\n", "for doubling the high odds (a 95% interval should contain it on about 380). The mean standard\n", "error was 1.03 and 0.99 times the spread of the estimates, and every draw read `supported`. So\n", "coverage held for this page's models.\n", ":::" ] }, { "cell_type": "markdown", "id": "assessment-heading", "metadata": {}, "source": [ "## Check the weights and the models\n", "\n", "Weights that divide by small chances can let a few patients decide the answer. An odds change\n", "never divides by a chance, and the check confirms it." ] }, { "cell_type": "code", "execution_count": 7, "id": "assessment", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:04:48.765121Z", "iopub.status.busy": "2026-11-13T23:04:48.764945Z", "iopub.status.idle": "2026-11-13T23:04:48.803850Z", "shell.execute_reply": "2026-11-13T23:04:48.803154Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "checks that need attention: none\n", "\n", "medium and high doubled: every weight lies between 0.5 and 2; effective sample size 2,788 of 3,000\n", "high doubled: every weight lies between 0.5 and 2; effective sample size 2,712 of 3,000\n", "\n", "treatment model, high schedule against the other two: AUC 0.72\n", "treatment model, low schedule against the other two: AUC 0.70\n", "treatment model, medium schedule against the other two: AUC 0.62\n" ] } ], "source": [ "# \"support\" reports the weights; \"nuisance_models\" reports the outcome and treatment models.\n", "tilt_assessment = tilt_result.assess()\n", "attention = tuple(item.name for item in tilt_assessment.attention)\n", "print(\"checks that need attention:\", attention or \"none\")\n", "print()\n", "for name, row in tilt_assessment.report(\"support\").items():\n", " if name == \"current practice\":\n", " continue\n", " low, high = row.guaranteed\n", " print(\n", " f\"{name}: every weight lies between {low:g} and {high:g}; \"\n", " f\"effective sample size {row.effective_sample_size:,.0f} of {len(frame):,}\"\n", " )\n", "print()\n", "nuisance = tilt_assessment.report(\"nuisance_models\")\n", "for model in nuisance.models:\n", " if model.name.startswith(\"propensity[\"): # the treatment model, one schedule at a time\n", " level = model.name.removeprefix(\"propensity[\").removesuffix(\"]\")\n", " auc = model.metrics[\"auc\"]\n", " print(f\"treatment model, {level} schedule against the other two: AUC {auc:.2f}\")" ] }, { "cell_type": "markdown", "id": "assessment-reading", "metadata": {}, "source": [ "Nothing needs attention. Each weight is the factor on the patient's own schedule over their\n", "average factor, so it lies between 0.5 and 2. The effective sample size, how many\n", "equally weighted patients the weighted group is worth, is 2,788 and 2,712 of 3,000. The AUC\n", "measures how well the treatment model tells one schedule's patients from the rest (0.5 is chance,\n", "1 is perfect): the characteristics shape the team's choices only in part. An odds change needs no\n", "positivity (overlap), so no AUC is a problem here." ] }, { "cell_type": "markdown", "id": "dose-heading", "metadata": {}, "source": [ "## The second question: more navigator and pharmacist time\n", "\n", "The proposal adds 0.5 navigator hours and 5 pharmacist minutes, up to limits of 7 hours and 70\n", "minutes; a patient whose raised dose would pass a limit keeps their current dose. This part uses a\n", "second simulated sample, with a yes-or-no outcome (a successful transition) and medication burden,\n", "which drives pharmacist time, as its third characteristic. Your own data would use the same patients\n", "for both questions." ] }, { "cell_type": "code", "execution_count": 8, "id": "dose-data", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:04:48.805378Z", "iopub.status.busy": "2026-11-13T23:04:48.805209Z", "iopub.status.idle": "2026-11-13T23:04:49.566605Z", "shell.execute_reply": "2026-11-13T23:04:49.565675Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "rows and columns: (3000, 6)\n", " transition_success navigator_hours pharmacist_minutes discharge_risk age medication_burden\n", "0 0.0 4.019 35.319 0.553 0.218 -0.058\n", "1 1.0 3.726 16.099 -2.319 0.431 -2.126\n", "2 0.0 4.259 48.825 0.910 0.606 0.830\n", "3 0.0 3.541 42.822 0.828 0.299 -0.535\n", "4 0.0 2.062 39.119 -0.307 1.508 -0.582\n", "\n", " navigator_hours pharmacist_minutes\n", "mean 4.0 40.0\n", "std 1.1 11.1\n", "min 0.1 4.2\n", "max 8.3 80.9\n", "\n", "true values of the simulated data:\n", " ey_policy[current practice] 0.4423\n", " ey_policy[more navigator time] 0.4705\n", " ey_policy[more pharmacist time] 0.4698\n", " ey_policy[both] 0.5155\n", " ate_policy[more navigator time vs current practice] 0.0282\n", " ate_policy[more pharmacist time vs current practice] 0.0275\n", " ate_policy[both vs current practice] 0.0731\n" ] } ], "source": [ "from cleverly.datasets import make_navigation_doses\n", "\n", "# With your own data, load the frame here. Real data have no dose_truth: delete the lines that\n", "# print only it, and remove it from the rest.\n", "dose_frame, dose_truth = make_navigation_doses(n=3_000, seed=23)\n", "# For your own data, name your dose columns and the characteristics to adjust for.\n", "DOSES = [\"navigator_hours\", \"pharmacist_minutes\"]\n", "dose_covariates = (\"discharge_risk\", \"age\", \"medication_burden\")\n", "print(\"rows and columns:\", dose_frame.shape)\n", "print(dose_frame.head().round(3).to_string())\n", "print()\n", "print(dose_frame[DOSES].describe().loc[[\"mean\", \"std\", \"min\", \"max\"]].round(1).to_string())\n", "print()\n", "print(\"true values of the simulated data:\")\n", "for name, value in dose_truth.items():\n", " print(f\" {name:52s} {value:.4f}\")" ] }, { "cell_type": "markdown", "id": "dose-data-reading", "metadata": {}, "source": [ "Each row holds success (1 or 0), the two doses, and three characteristics. Patients average 4.0\n", "navigator hours and 40.0 pharmacist minutes. In the true values, `ey_policy` is the share of\n", "successful transitions under each plan, and `ate_policy` its change against current practice.\n", "\n", "### Why a simple regression misleads" ] }, { "cell_type": "code", "execution_count": 9, "id": "dose-association", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:04:49.567882Z", "iopub.status.busy": "2026-11-13T23:04:49.567748Z", "iopub.status.idle": "2026-11-13T23:04:49.586773Z", "shell.execute_reply": "2026-11-13T23:04:49.586308Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "change in success for 0.5 more hours and 5 more minutes:\n", " regression on the two doses only: +0.0049\n", " regression that adds the characteristics: +0.0616\n", " true change: +0.0731\n", "\n", " navigator_hours pharmacist_minutes transition_success\n", "discharge_risk \n", "lower 3.45 35.44 0.54\n", "middle 3.96 39.86 0.44\n", "higher 4.47 44.69 0.36\n" ] } ], "source": [ "# One CPU thread for this plain scikit-learn fit, as cleverly uses for its own fits, so a rerun\n", "# prints the same digits.\n", "with cleverly.learners.thread_limit():\n", " simple_fit = LinearRegression().fit(dose_frame[DOSES], dose_frame[\"transition_success\"])\n", " adjusted_fit = LinearRegression().fit(\n", " dose_frame[[*DOSES, *dose_covariates]], dose_frame[\"transition_success\"]\n", " )\n", "simple_both = simple_fit.coef_[0] * 0.5 + simple_fit.coef_[1] * 5.0\n", "adjusted_both = adjusted_fit.coef_[0] * 0.5 + adjusted_fit.coef_[1] * 5.0\n", "true_both = dose_truth[\"ate_policy[both vs current practice]\"] # simulated data only\n", "print(\"change in success for 0.5 more hours and 5 more minutes:\")\n", "print(f\" regression on the two doses only: {simple_both:+.4f}\")\n", "print(f\" regression that adds the characteristics: {adjusted_both:+.4f}\")\n", "print(f\" true change: {true_both:+.4f}\")\n", "print()\n", "risk_band = pd.qcut(dose_frame[\"discharge_risk\"], 3, labels=[\"lower\", \"middle\", \"higher\"])\n", "print(\n", " dose_frame.groupby(risk_band, observed=True)[[*DOSES, \"transition_success\"]]\n", " .mean()\n", " .round(2)\n", " .to_string()\n", ")" ] }, { "cell_type": "markdown", "id": "dose-association-reading", "metadata": {}, "source": [ "The regression on the doses alone gives one fifteenth of the true change: higher-risk patients get\n", "more of both doses (4.47 hours against 3.45 in the lowest third) and succeed less often (0.36\n", "against 0.54), the same confounding as before. Adding the characteristics brings it to +0.0616,\n", "still short of +0.0731, because a straight-line model has no room for the two doses helping each\n", "other. The method below adds products in its outcome model, then uses weights as a safeguard in\n", "case that model is wrong." ] }, { "cell_type": "markdown", "id": "dose-protocol-heading", "metadata": {}, "source": [ "### Record the dose question\n", "\n", "The study description changes the same fields as before, now for doses." ] }, { "cell_type": "code", "execution_count": 10, "id": "dose-protocol", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:04:49.588040Z", "iopub.status.busy": "2026-11-13T23:04:49.587851Z", "iopub.status.idle": "2026-11-13T23:04:49.594610Z", "shell.execute_reply": "2026-11-13T23:04:49.591116Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Population: Adults with a discharge-home order at a participating hospital during the enrollment period\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 doses are set\n", "Strategies: Keep the navigator hours and pharmacist minutes that current practice gives; Add 0.5 navigator hours unless that passes 7 hours; Add 5 pharmacist minutes unless that passes 70 minutes; Add both, each with its own limit\n", "Versions: The doses as the discharge team sets them today; Navigator contact time within 30 days, raised for each patient; Pharmacist medication-review time within 30 days, raised for each patient; Both raises for each patient\n", "Outcome: Successful transition: a 30-day transition score of at least 0.7 of the maximum\n", "Horizon: 30 days after discharge\n", "Intercurrent events: Use the success indicator regardless of readmission; Analyze the assigned doses regardless of how much contact was completed; The protocol counts death before day 30 as an unsuccessful transition (composite strategy)\n", "Interference unit: Individual patient\n", "Rationale: The recorded characteristics cover the common causes of the doses and success; 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": [ "# For your own study, write these fields for your dose question, as in the protocol cell.\n", "dose_protocol = replace(\n", " program,\n", " time_zero=\"Discharge-home order, after baseline measurement and before the doses are set\",\n", " treatment_strategies=(\n", " \"Keep the navigator hours and pharmacist minutes that current practice gives\",\n", " \"Add 0.5 navigator hours unless that passes 7 hours\",\n", " \"Add 5 pharmacist minutes unless that passes 70 minutes\",\n", " \"Add both, each with its own limit\",\n", " ),\n", " treatment_versions=(\n", " \"The doses as the discharge team sets them today\",\n", " \"Navigator contact time within 30 days, raised for each patient\",\n", " \"Pharmacist medication-review time within 30 days, raised for each patient\",\n", " \"Both raises for each patient\",\n", " ),\n", " outcome=\"Successful transition: a 30-day transition score of at least 0.7 of the maximum\",\n", " intercurrent_event_handling=(\n", " \"Use the success indicator regardless of readmission\",\n", " \"Analyze the assigned doses regardless of how much contact was completed\",\n", " \"The protocol counts death before day 30 as an unsuccessful transition \"\n", " \"(composite strategy)\",\n", " ),\n", " assumption_rationale=(\n", " \"The recorded characteristics cover the common causes of the doses and success\",\n", " *program.assumption_rationale[1:],\n", " ),\n", ")\n", "print(\"\\n\".join(dose_protocol.summary_lines()))" ] }, { "cell_type": "markdown", "id": "dose-protocol-reading", "metadata": {}, "source": [ "As before, the plans assign doses and the analysis ignores how much contact was completed. A\n", "death before day 30 counts as unsuccessful." ] }, { "cell_type": "markdown", "id": "dose-identify-heading", "metadata": {}, "source": [ "### What the dose answer rests on\n", "\n", "Each plan is a `JointPolicy`, which can raise one dose or both. `Shift(0.5, cap=7.0)` adds 0.5\n", "unless the result passes 7, and current practice raises nothing (`components={}`).\n", "`policy_kind=\"known\"` says the raise is a fixed rule written in advance. In `PointTreatment`,\n", "`continuous_treatment` marks both doses as numbers rather than categories." ] }, { "cell_type": "code", "execution_count": 11, "id": "dose-identify", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:04:49.596233Z", "iopub.status.busy": "2026-11-13T23:04:49.595820Z", "iopub.status.idle": "2026-11-13T23:04:49.617695Z", "shell.execute_reply": "2026-11-13T23:04:49.616596Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "conditions the answer rests on:\n", " - consistency\n", " - no interference\n", " - no unmeasured confounding\n", " - positivity for the assigned dose\n", " - the policy is a known function of (A, W), and of a randomizer of known law when it is randomized\n", " - on a continuous treatment, d is piecewise smooth invertible (Diaz, Williams, Hoffman & Schenck 2023, Assumption 4)\n" ] } ], "source": [ "from cleverly import ModifiedTreatmentPolicyEffect\n", "from cleverly.interventions import JointPolicy, Shift\n", "\n", "# For your own data, change the dose columns, the amounts added, and each dose's limit (cap).\n", "more_hours = Shift(0.5, cap=7.0)\n", "more_minutes = Shift(5.0, cap=70.0)\n", "plans = [\n", " JointPolicy(\"current practice\", components={}, policy_kind=\"known\"),\n", " JointPolicy(\n", " \"more navigator time\", components={\"navigator_hours\": more_hours}, policy_kind=\"known\"\n", " ),\n", " JointPolicy(\n", " \"more pharmacist time\", components={\"pharmacist_minutes\": more_minutes}, policy_kind=\"known\"\n", " ),\n", " JointPolicy(\n", " \"both\",\n", " components={\"navigator_hours\": more_hours, \"pharmacist_minutes\": more_minutes},\n", " policy_kind=\"known\",\n", " ),\n", "]\n", "dose_study = CausalStudy(\n", " dose_frame,\n", " design=PointTreatment(\n", " outcome=\"transition_success\",\n", " treatment=DOSES,\n", " continuous_treatment=DOSES,\n", " adjustment=dose_covariates,\n", " ),\n", " protocol=dose_protocol,\n", ")\n", "raises = dose_study.identify(ModifiedTreatmentPolicyEffect(plans, reference=\"current practice\"))\n", "print(\"conditions the answer rests on:\")\n", "for condition in raises.identification.assumptions:\n", " name = condition.split(\":\")[0].replace(\"*\", \"\")\n", " if not name.startswith(\"with \"): # missing outcomes or a mediator: not used here\n", " print(\" -\", name)" ] }, { "cell_type": "markdown", "id": "dose-identify-reading", "metadata": {}, "source": [ "The first three conditions are those of the first question. \"Positivity for the assigned dose\"\n", "means similar patients sometimes receive the raised dose; the limits help, by keeping raises\n", "inside the observed range. The fifth line says the raise is a fixed rule of the recorded doses and\n", "characteristics. The last is a condition on the rule, which you check by reading it: on each piece\n", "(raised, or kept because the raise would pass the limit) the original dose can be recovered from\n", "the new one." ] }, { "cell_type": "markdown", "id": "dose-estimate-heading", "metadata": {}, "source": [ "### Estimate the effects of the raises\n", "\n", "TMLE again fits two models. The outcome model, a logistic regression on the doses, the\n", "characteristics, their squares and their products, lets the effect of one dose depend on the\n", "other. The weights now say how much more common the raised doses are than the current ones among\n", "patients with the same characteristics (the density ratio). `ratio=\"classifier\"` estimates them\n", "with a classifier, here a logistic regression passed as `treatment_learner`." ] }, { "cell_type": "code", "execution_count": 12, "id": "dose-estimate", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:04:49.619094Z", "iopub.status.busy": "2026-11-13T23:04:49.618953Z", "iopub.status.idle": "2026-11-13T23:04:50.039773Z", "shell.execute_reply": "2026-11-13T23:04:50.038682Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "ate_policy[more navigator time vs current practice] +0.0284 (+0.0194, +0.0374) true +0.0282 supported\n", "ate_policy[more pharmacist time vs current practice] +0.0289 (+0.0203, +0.0375) true +0.0275 supported\n", "ate_policy[both vs current practice] +0.0747 (+0.0625, +0.0868) true +0.0731 supported\n" ] } ], "source": [ "# The outcome model: a logistic regression on the doses, the characteristics, their squares and\n", "# their products, still a simple fixed-form model. The weights (also called the density ratio):\n", "# a logistic classifier, which treatment_learner names on this route (ratio=\"classifier\"). A 0/1\n", "# outcome needs no declared range, so Targeting() drops q_bounds. Swap in your own learners.\n", "dose_method = replace(\n", " method,\n", " models=ModelSpec(\n", " outcome_learner=make_pipeline(\n", " StandardScaler(), PolynomialFeatures(2), LogisticRegression(max_iter=1000)\n", " ),\n", " treatment_learner=LogisticRegression(max_iter=1000),\n", " ratio=\"classifier\",\n", " ),\n", " targeting=Targeting(),\n", " runtime=Runtime(random_state=23, n_jobs=1),\n", ")\n", "dose_result = raises.estimate(method=dose_method)\n", "HOURS, MINUTES, BOTH = (f\"ate_policy[{plan.name} vs current practice]\" for plan in plans[1:])\n", "for key in (HOURS, MINUTES, BOTH):\n", " point = dose_result[key]\n", " low, high = point.ci\n", " print(\n", " f\"{key:52s} {point.psi:+.4f} ({low:+.4f}, {high:+.4f}) \"\n", " f\"true {dose_truth[key]:+.4f} {point.support.label}\"\n", " )" ] }, { "cell_type": "markdown", "id": "dose-estimate-reading", "metadata": {}, "source": [ "Both raises together add 0.075 to the share of successful transitions (interval 0.062 to 0.087),\n", "and each raise alone adds about 0.03. All three intervals contain the true values, and all three\n", "read `supported`.\n", "\n", ":::{dropdown} Details: how the classifier gives the weights, and a repeated-draw check\n", "The code stacks two copies of the data, one with the current doses and one with the raised doses,\n", "and trains the classifier to tell the copies apart. Where it tells them apart easily, the raise\n", "moves patients to doses that patients like them rarely get, and the weights grow. The fit never\n", "computes a patient's original dose from the raised one. Here the classifier's logistic form nearly\n", "matches the simulated doses, which are normal around a straight line in the characteristics. A\n", "classifier of the wrong form would give wrong weights.\n", "\n", "The same simulation repeats this fit on 400 draws. The interval contained the true change on 384\n", "draws for more navigator time, 379 for more pharmacist time, and 372 for both (380 is expected;\n", "372 is within simulation noise). The mean standard errors were 1.04, 1.02, and 0.98 times the\n", "spread of the estimates.\n", ":::" ] }, { "cell_type": "markdown", "id": "dose-support-heading", "metadata": {}, "source": [ "### Check the weights\n", "\n", "A raise that moves patients to doses rare among similar patients gives those patients large\n", "weights, so a few of them carry the answer." ] }, { "cell_type": "code", "execution_count": 13, "id": "dose-support", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:04:50.041223Z", "iopub.status.busy": "2026-11-13T23:04:50.041067Z", "iopub.status.idle": "2026-11-13T23:04:50.065004Z", "shell.execute_reply": "2026-11-13T23:04:50.064144Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "checks that need attention: none\n", "\n", "plan moved kept own dose mean weight max weight effective n\n", "more navigator time 98.4% 1.6% 1.00 6.8 2,318\n", "more pharmacist time 98.4% 1.6% 1.00 8.7 2,280\n", "both 100.0% 3.2% 1.01 14.3 1,780\n" ] } ], "source": [ "dose_assessment = dose_result.assess()\n", "attention = tuple(item.name for item in dose_assessment.attention)\n", "print(\"checks that need attention:\", attention or \"none\")\n", "print()\n", "header = (\"plan\", \"moved\", \"kept own dose\", \"mean weight\", \"max weight\", \"effective n\")\n", "print(\"{:22s} {:>6s} {:>14s} {:>12s} {:>11s} {:>12s}\".format(*header))\n", "for name, row in dose_result.diagnostics.support().items():\n", " if name == \"current practice\":\n", " continue\n", " print(\n", " f\"{name:22s} {row.moved_fraction:6.1%} {row.capped_fraction:14.1%} \"\n", " f\"{row.mean_ratio:12.2f} {row.max_ratio:11.1f} {row.effective_sample_size:12,.0f}\"\n", " )" ] }, { "cell_type": "markdown", "id": "dose-support-reading", "metadata": {}, "source": [ "Nothing needs attention. Under \"both\", every patient had at least one dose raised; the patients\n", "who kept a dose were those whose raise would pass its limit. The weights average 1 when the\n", "classifier is right, and they do, so a mean far from 1 would warn of a poor classifier. `cleverly`\n", "reports the effective sample size without a pass mark. The joint raise is worth about 60% of the rows\n", "(1,780 of 3,000), which helps explain its wider interval. If yours falls much lower, a few patients\n", "carry the answer: try smaller raises or tighter limits." ] }, { "cell_type": "markdown", "id": "failure-heading", "metadata": {}, "source": [ "### Why the two raises can't be added up\n", "\n", "A tempting shortcut estimates each raise alone and adds the two effects. `result.contrast` gives\n", "the estimate and interval of both raises minus the two single raises." ] }, { "cell_type": "code", "execution_count": 14, "id": "failure-mode", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:04:50.067087Z", "iopub.status.busy": "2026-11-13T23:04:50.066452Z", "iopub.status.idle": "2026-11-13T23:04:50.072662Z", "shell.execute_reply": "2026-11-13T23:04:50.072015Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "two separate raises, added up: +0.0573 true +0.0556\n", "both raises together: +0.0747 true +0.0731\n", "together minus added up: +0.0175 95% CI (+0.0135, +0.0214)\n", "validation status of that difference: experimental\n" ] } ], "source": [ "added_up = dose_result[HOURS].psi + dose_result[MINUTES].psi\n", "true_added_up = dose_truth[HOURS] + dose_truth[MINUTES] # simulated data only\n", "print(f\"two separate raises, added up: {added_up:+.4f} true {true_added_up:+.4f}\")\n", "print(f\"both raises together: {dose_result[BOTH].psi:+.4f} true {dose_truth[BOTH]:+.4f}\")\n", "extra = dose_result.contrast(lambda p: p[0] - p[1] - p[2], [BOTH, HOURS, MINUTES])\n", "low, high = extra.ci\n", "print(f\"together minus added up: {extra.psi:+.4f} 95% CI ({low:+.4f}, {high:+.4f})\")\n", "print(f\"validation status of that difference: {extra.support.label}\")" ] }, { "cell_type": "markdown", "id": "failure-reading", "metadata": {}, "source": [ "Together the raises add about 0.0175 more than the two single raises added up (interval 0.0135 to\n", "0.0214). In these simulated data the two services help each other: more navigator time helps more\n", "when the patient also gets more pharmacist time. Adding up single raises misses this, and so does\n", "any analysis that changes one dose at a time. The difference reads `experimental`, because no\n", "validation study covers a contrast built from several estimates on this kind of fit; the three\n", "plan estimates read `supported`. Measuring the joint raise has a price: its weights are larger, which\n", "helps make its interval wider.\n", "\n", ":::{dropdown} Details: how often the shortcut falls short\n", "In the 400 repeated draws, the interval for the difference contained its true value (0.0175) on\n", "379 draws, and its standard error was 0.97 times the spread of the estimates. The added-up\n", "estimate fell below the lower end of the interval for both raises on 394 draws, so on these data\n", "the shortcut almost always misses.\n", ":::" ] }, { "cell_type": "markdown", "id": "refutation-heading", "metadata": {}, "source": [ "## Try to break both results\n", "\n", "These checks change the data in a known way and refit, for the high-odds change and for both\n", "raises. They look for signs of a broken fit, but none of them can detect a missing confounder." ] }, { "cell_type": "code", "execution_count": 15, "id": "refutation", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:04:50.074047Z", "iopub.status.busy": "2026-11-13T23:04:50.073625Z", "iopub.status.idle": "2026-11-13T23:05:25.140030Z", "shell.execute_reply": "2026-11-13T23:05:25.139254Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "high doubled\n", " test original refuted_mean refuted_sd expectation verdict\n", " placebo 0.0209 -0.0000 0.0010 ~ 0 descriptive\n", "random_common_cause 0.0209 0.0209 0.0000 ~ 0.0209 descriptive\n", " subset 0.0209 0.0206 0.0008 scatter ~ 0.0006292 descriptive\n", " placebo: t = -0.17\n", " random_common_cause: paired shift in standard errors = -0.01\n", " subset: scatter ratio rho = 1.26\n", "\n", "both raises\n", " test original refuted_mean refuted_sd expectation verdict\n", " placebo 0.0747 -0.0001 0.0055 ~ 0 descriptive\n", "random_common_cause 0.0747 0.0747 0.0003 ~ 0.07471 descriptive\n", " subset 0.0747 0.0739 0.0033 scatter ~ 0.004064 descriptive\n", " placebo: t = -0.07\n", " random_common_cause: paired shift in standard errors = 0.00\n", " subset: scatter ratio rho = 0.80\n", "\n" ] } ], "source": [ "from cleverly.validation import refute\n", "\n", "# placebo shuffles the treatment (the estimate should be about zero); random_common_cause adds a\n", "# column of noise (it should barely move); subset refits on random 70% samples (their scatter\n", "# should match what the standard error predicts).\n", "TILT = \"ate_ipsi[high doubled vs current practice]\"\n", "columns = [\"test\", \"original\", \"refuted_mean\", \"refuted_sd\", \"expectation\", \"verdict\"]\n", "tilt_refutation = refute(tilt_result, estimand=TILT, random_state=24)\n", "dose_refutation = refute(dose_result, estimand=BOTH, random_state=23)\n", "for label, report in ((\"high doubled\", tilt_refutation), (\"both raises\", dose_refutation)):\n", " print(label)\n", " print(report.to_frame()[columns].round(4).to_string(index=False))\n", " for test in report.tests:\n", " print(f\" {test.name}: {test.statistic_name} = {test.statistic:.2f}\")\n", " print()" ] }, { "cell_type": "markdown", "id": "refutation-reading", "metadata": {}, "source": [ "None of the six checks shows a problem. The shuffled treatment gives estimates near zero (t of\n", "-0.17 and -0.07; beyond about 2 would be a warning), and the noise column moves neither estimate by\n", "more than 0.01 standard errors on average. The 70% refits spread 1.26 and 0.80 times as much as predicted,\n", "where 1 is a perfect match; a ratio from 20 refits is noisy, and only a ratio well above 1 would\n", "suggest too narrow an interval. The `verdict` column reads `descriptive`:\n", "`cleverly` gives a pass or fail only when a simulation study backs the check." ] }, { "cell_type": "markdown", "id": "sensitivity-heading", "metadata": {}, "source": [ "## What if the records are wrong?\n", "\n", "No check on this page tests the no-unmeasured-confounding condition. These checks test recording\n", "errors instead: the tool draws a hidden variable and lets it corrupt the recorded treatment, and\n", "here it leaves the outcome alone. The code's comments give the size of each corruption." ] }, { "cell_type": "code", "execution_count": 16, "id": "sensitivity", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:05:25.141721Z", "iopub.status.busy": "2026-11-13T23:05:25.141560Z", "iopub.status.idle": "2026-11-13T23:05:26.512644Z", "shell.execute_reply": "2026-11-13T23:05:26.511529Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "high doubled: estimate +0.0165, moved -4.6 standard errors\n", "both raises: estimate +0.0735, moved -0.2 standard errors\n" ] } ], "source": [ "from cleverly.sensitivity import ConfounderStrengthGrid\n", "\n", "# simulated_confounding draws a hidden variable for each patient. With outcome=(0.0,) it leaves the\n", "# outcome alone and corrupts only the recorded treatment, so here it tests recording errors.\n", "# arm_pair names the two schedules that swap. 0.1 picks the 10% of patients with the largest hidden\n", "# values; among them high becomes low, low becomes high, and medium stays (about 7% of patients\n", "# change). For your own data, choose sizes you find plausible for your records.\n", "tilt_surface = tilt_result.sensitivity.simulated_confounding(\n", " estimand=TILT,\n", " arm_pair=(\"high\", \"low\"),\n", " grid=ConfounderStrengthGrid(treatment=(0.0, 0.1), outcome=(0.0,)),\n", ")\n", "dose_surface = dose_result.sensitivity.simulated_confounding(\n", " estimand=BOTH,\n", " # Dose strengths are in each dose's units per unit of the hidden variable: 0.1 hours and\n", " # 1 minute, about a tenth of each dose's spread among similar patients.\n", " grid=ConfounderStrengthGrid(\n", " treatment={\"navigator_hours\": (0.0, 0.1), \"pharmacist_minutes\": (0.0, 1.0)},\n", " outcome=(0.0,),\n", " ),\n", ")\n", "for label, surface, fit, name in (\n", " (\"high doubled\", tilt_surface, tilt_result, TILT),\n", " (\"both raises\", dose_surface, dose_result, BOTH),\n", "):\n", " strongest = surface.cells[-1]\n", " moved = strongest.displacement / fit[name].std_error\n", " print(f\"{label}: estimate {strongest.estimate:+.4f}, moved {moved:+.1f} standard errors\")" ] }, { "cell_type": "markdown", "id": "sensitivity-reading", "metadata": {}, "source": [ "Swapping high and low within a tenth of patients (about 7% of all patients change) moves the\n", "high-odds estimate by 4.6 standard errors, because the swapped records blur the difference in scores between the two schedules. The\n", "estimate stays positive (+0.0165), so the finding that the nudge helps survives a swap of this\n", "size, though its size does not. Small noise in the doses moves the estimate for both raises by 0.2 standard errors. The\n", "two corruptions differ in kind and size, so they do not rank the two answers.\n", "\n", "`cleverly`'s bound on a missing confounder, which says how strong one would have to be to change\n", "the answer, is not available here: an odds change is defined by the team's current chances, which\n", "a missing confounder would also change, and dose raises have no bound yet. So \"no unmeasured\n", "confounding\" rests on knowing how the team chooses." ] }, { "cell_type": "markdown", "id": "interpret", "metadata": {}, "source": [ "## What we can and can't conclude\n", "\n", "For the program's owner: if a nudge doubles each patient's odds of the high schedule, the average\n", "day-30 transition score would rise by about 0.021 on the 0-to-1 scale (95% interval 0.019 to\n", "0.023); doubling the medium and high odds, by about 0.015. Whether a given nudge doubles\n", "the odds is a separate question. Adding half an hour of navigator time and five pharmacist\n", "minutes, within the limits, would raise successful transitions by about 7.5 percentage points (6.2\n", "to 8.7). These answers are about adults going home from a participating hospital. Plan the two\n", "raises together.\n", "\n", "The intervals cover sampling variation only. Both answers rest on the three conditions that need\n", "judgment. The schedule answer also needs a treatment model flexible enough for how the team\n", "chooses; the dose answer needs raised doses that similar patients get, and the weights or the\n", "outcome model close to right. These are not the effects of putting everyone on the high schedule,\n", "or of doses beyond the observed range. One simulated sample cannot show how the method does in\n", "general." ] }, { "cell_type": "markdown", "id": "method-evidence", "metadata": {}, "source": [ "## Go deeper\n", "\n", "### How we know the method works\n", "\n", "| fit | simulation study | the study's data |\n", "| --- | --- | --- |\n", "| TMLE of odds changes on a three-level treatment, in sample and out of fold | [Categorical incremental policies](../technical-reference/method-evidence/categorical-incremental.md). No package fits this, so it compares with exact truths only | a simulated continuous outcome with four kinds of patient and 8,000 rows, fitted with models that estimate each kind's chances and means directly |\n", "| TMLE of raises of two doses, with a classifier for the weights | [Vector modified treatment policies](../technical-reference/method-evidence/vector-modified-treatment-policies.md). It also agrees with the R package `lmtp` on the same samples | a simulated binary outcome with a yes-or-no treatment and one dose, at 2,000 rows |\n", "\n", "Neither study uses this page's data. The first study's models were exact for its data, where this\n", "page fits simple parametric models. The second study gave its classifier the true log of the\n", "weight as its only input, so it says nothing about a classifier that learns the weights, as this\n", "page's does. The repeated-draw checks above cover that only partly, because here the outcome model has the\n", "simulated data's form. The [vector\n", "treatments](../technical-reference/point-treatment-tmle.md#vector-treatments) section states the\n", "conditions of the dose fit." ] }, { "cell_type": "markdown", "id": "where-next", "metadata": {}, "source": [ "## Where to go next\n", "\n", "The [interventions](interventions.ipynb) example compares fixed rules, odds changes, and dose\n", "raises for a yes-or-no treatment and a single dose. The [MSM projections](msm-projections.ipynb)\n", "example fits a trend across three schedules. The [point-treatment TMLE\n", "reference](../technical-reference/point-treatment-tmle.md) gives the exact conditions of both\n", "estimators, and the [examples index](index.md) lists every example." ] } ], "metadata": { "cleverly_execution": { "command": [ "python", "scripts/execute_notebook.py", "docs/examples/schedules-and-intensity.ipynb" ], "gated": { "code_source_sha256": "eea5dc3559bf4842f60ea0002d75f607f6613d8fef50b85b50160df097c4d497", "execution_payload_sha256": "23714358241531d161e2b871e9d618d6e897271500ab78360aa9cf8e2caccca9" }, "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 }