{ "cells": [ { "cell_type": "markdown", "id": "title", "metadata": {}, "source": [ "# A small pilot with outside records: adaptive TMLE\n", "\n", "## At a glance\n", "\n", "A health plan ran a randomized pilot of its transition-navigation offer, with 560 patients. It also\n", "holds records of 2,440 patients from other hospitals, some offered navigation and some not, with no\n", "randomization. Did navigation raise the pilot patients' 30-day transition score, and can the records\n", "tighten the answer?\n", "\n", "Borrowing the records, navigation raised the score of pilot patients by 6.07 points, with a 95%\n", "confidence interval of 5.16 to 6.99. The pilot alone gives 6.68 (5.37 to 8.00), so the records cut\n", "the standard error from 0.67 to 0.46. The data are simulated, so we know the true effect, 6.05, and\n", "both intervals contain it. The main caveat is that the interval is valid for the effect inside a\n", "simple description of how the records differ from the pilot, a description the fit chooses from the\n", "data. It is also valid for the pilot's own effect when that description is rich enough, and the data\n", "cannot check that." ] }, { "cell_type": "markdown", "id": "plan", "metadata": {}, "source": [ "## The question\n", "\n", "This page is the sequel to [a randomized pilot](randomized-pilot.ipynb). That page analyzes a pilot\n", "alone, and this one adds outside records to a pilot of the same kind.\n", "\n", "The plan wants to know whether to roll out navigation, and it has one small randomized pilot to\n", "answer with. In the pilot, patients were offered navigation or usual discharge support by a coin\n", "flip. The records come from hospitals that did not randomize: sicker patients were offered\n", "navigation more often, and their scores run higher or lower than the pilot's for reasons other than\n", "the offer. The quantity to estimate is the average difference in 30-day transition score between\n", "offering navigation and not offering it, among the kind of patients the pilot enrolled.\n", "\n", "Pooling everyone would be wrong, because the records mix the offer's effect with who was offered and\n", "with how their hospitals differ. Dropping the records is safe but wasteful. The method here,\n", "adaptive TMLE (a variant of targeted maximum likelihood estimation, a method that corrects a\n", "prediction-based estimate so its interval is valid), learns how the records' outcomes differ from\n", "the pilot's as a function of patient characteristics. It describes that difference with a short\n", "formula, such as a fixed offset plus a trend in prior utilization, and removes it. After that, it\n", "uses the records as extra patients for the effect. The pilot's own randomization is the only thing\n", "the method trusts outright." ] }, { "cell_type": "markdown", "id": "setup-heading", "metadata": {}, "source": [ "## The data and the setup" ] }, { "cell_type": "code", "execution_count": 1, "id": "setup", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:08:35.968682Z", "iopub.status.busy": "2026-11-13T23:08:35.968364Z", "iopub.status.idle": "2026-11-13T23:08:37.527141Z", "shell.execute_reply": "2026-11-13T23:08:37.526330Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "cleverly 0.2.4\n" ] } ], "source": [ "import numpy as np\n", "import pandas as pd\n", "from scipy.special import expit\n", "from sklearn.linear_model import LinearRegression, LogisticRegression\n", "\n", "import cleverly\n", "from cleverly import (\n", " ATE,\n", " AdaptiveTMLEMethod,\n", " CausalStudy,\n", " CrossFitting,\n", " ModelSpec,\n", " PointTreatment,\n", " Runtime,\n", " TMLEMethod,\n", " TrialATE,\n", " TrialWithExternalData,\n", ")\n", "\n", "print(\"cleverly\", cleverly.__version__)" ] }, { "cell_type": "markdown", "id": "data-heading", "metadata": {}, "source": [ "## The pilot and the records" ] }, { "cell_type": "code", "execution_count": 2, "id": "data", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:08:37.529900Z", "iopub.status.busy": "2026-11-13T23:08:37.529564Z", "iopub.status.idle": "2026-11-13T23:08:38.288088Z", "shell.execute_reply": "2026-11-13T23:08:38.287214Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['in_pilot', 'transition_navigation', 'transition_score', 'discharge_risk', 'age', 'prior_utilization']\n", "transition_navigation 0 1\n", "in_pilot \n", "0 1237 1203\n", "1 298 262\n", "{'pilot patients': 6.05, 'all patients': 5.0}\n" ] } ], "source": [ "def simulate(n, seed):\n", " \"\"\"Patients of a hospital network, some in a navigation pilot and some in its records.\"\"\"\n", " rng = np.random.default_rng(seed)\n", " discharge_risk = rng.normal(size=n)\n", " age = rng.normal(size=n)\n", " prior_utilization = rng.normal(size=n)\n", " in_pilot = rng.binomial(1, expit(-1.6 + 0.7 * discharge_risk))\n", " navigation = np.where(\n", " in_pilot == 1,\n", " rng.binomial(1, 0.5, n), # the pilot drew the offer at random\n", " rng.binomial(1, expit(0.8 * discharge_risk)), # in the records, sicker patients got it more\n", " )\n", " effect = 5 + 2 * discharge_risk # the offer helps higher-risk patients more\n", " records_shift = 3 + 2 * prior_utilization # records score higher than the pilot would\n", " score = (\n", " 50\n", " + effect * navigation\n", " + 3 * discharge_risk\n", " + 2 * age\n", " + (1 - in_pilot) * records_shift\n", " + rng.normal(0, 8, n)\n", " )\n", " return pd.DataFrame(\n", " {\n", " \"in_pilot\": in_pilot,\n", " \"transition_navigation\": navigation,\n", " \"transition_score\": score,\n", " \"discharge_risk\": discharge_risk,\n", " \"age\": age,\n", " \"prior_utilization\": prior_utilization,\n", " }\n", " )\n", "\n", "\n", "frame = simulate(3000, seed=11)\n", "\n", "# The known answers come from a very large simulated network.\n", "large = simulate(2_000_000, seed=99)\n", "truth = {\n", " \"pilot patients\": float(5 + 2 * large.loc[large[\"in_pilot\"] == 1, \"discharge_risk\"].mean()),\n", " \"all patients\": 5.0,\n", "}\n", "print(list(frame.columns))\n", "print(frame.groupby([\"in_pilot\", \"transition_navigation\"]).size().unstack())\n", "print({name: round(value, 2) for name, value in truth.items()})" ] }, { "cell_type": "markdown", "id": "data-reading", "metadata": {}, "source": [ "Each row is one patient. `in_pilot` is 1 for the 560 pilot patients and 0 for the 2,440 records, and\n", "the offer split of the pilot (298 usual support, 262 navigation) is close to even because it was\n", "drawn at random. Among the records, 1,203 patients were offered navigation, more often the\n", "higher-risk ones. Higher-risk patients are also more likely to be in the pilot, and the offer helps\n", "them more, so the true effect among pilot patients (6.05) is larger than the effect among all\n", "patients (5.00). The simulated characteristics are centered at zero, so a negative value is below\n", "the network average, and scores are in simulated units." ] }, { "cell_type": "markdown", "id": "association-heading", "metadata": {}, "source": [ "## Why pooling the rows misleads" ] }, { "cell_type": "code", "execution_count": 3, "id": "association", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:08:38.289592Z", "iopub.status.busy": "2026-11-13T23:08:38.289174Z", "iopub.status.idle": "2026-11-13T23:08:38.296125Z", "shell.execute_reply": "2026-11-13T23:08:38.295481Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "difference in mean score, all rows: 7.57\n", "difference in mean score, pilot only: 6.87\n", "true effect among pilot patients: 6.05\n" ] } ], "source": [ "treated = frame[\"transition_navigation\"] == 1\n", "pooled_gap = (\n", " frame.loc[treated, \"transition_score\"].mean() - frame.loc[~treated, \"transition_score\"].mean()\n", ")\n", "pilot = frame[frame[\"in_pilot\"] == 1]\n", "pilot_treated = pilot[\"transition_navigation\"] == 1\n", "pilot_gap = (\n", " pilot.loc[pilot_treated, \"transition_score\"].mean()\n", " - pilot.loc[~pilot_treated, \"transition_score\"].mean()\n", ")\n", "print(f\"difference in mean score, all rows: {pooled_gap:.2f}\")\n", "print(f\"difference in mean score, pilot only: {pilot_gap:.2f}\")\n", "print(f\"true effect among pilot patients: {truth['pilot patients']:.2f}\")" ] }, { "cell_type": "markdown", "id": "association-reading", "metadata": {}, "source": [ "Comparing offered with other patients across all rows gives 7.57, well above the true 6.05, because\n", "the records' offered patients are sicker and their hospitals score differently. The pilot alone\n", "gives 6.87, which has no such bias but is rough with only 560 patients. The next sections keep the\n", "pilot's randomization and use the records only after the fit has learned how they differ." ] }, { "cell_type": "markdown", "id": "identify-heading", "metadata": {}, "source": [ "## Tell cleverly which rows are the pilot" ] }, { "cell_type": "code", "execution_count": 4, "id": "identify", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:08:38.297485Z", "iopub.status.busy": "2026-11-13T23:08:38.297099Z", "iopub.status.idle": "2026-11-13T23:08:38.318789Z", "shell.execute_reply": "2026-11-13T23:08:38.318319Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " Causal question (ate)\n", "==============================================================================\n", "Question: trial effect averaged Rows: 3,000\n", " over the trial Answered by: adjusting for covariates\n", " covariates, E[Y^1 - Y^0\n", " | S = 1]\n", "Outcome: transition_score\n", " (continuous)\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 the\n", " outcome it would have had under the\n", " treatment it actually received. This\n", " needs the treatment to be well defined:\n", " every way of getting the same level has\n", " the same effect.\n", "no interference no One unit's treatment does not change\n", " another unit's outcome.\n", "randomized trial no Among trial units with the same\n", " adjusted-for values, which arm a unit got\n", " is unrelated to the outcomes it would\n", " have had, as randomization ensures. The\n", " design declares this, and the data cannot\n", " show it.\n", "both arms in the trial partly Every group of trial units that share the\n", " adjusted-for values had some chance of\n", " either arm.\n", "==============================================================================\n", "Methods\n", "method name\n", "------------------------------------------------------------------------------\n", "atmle adaptive TMLE for a trial with external data\n", "==============================================================================\n", "Notes:\n", "[1] The data cannot confirm these conditions. Overlap (marked partly) can be\n", " probed: after a fit, result.diagnostics.support() shows where the fitted\n", " treatment model gives units little chance of a compared treatment. That\n", " check reads a fitted model, so a clean result does not prove overlap.\n", "[2] The methods table lists the methods that fit. 11 other methods cannot\n", " estimate this question; the full summary says why.\n" ] } ], "source": [ "covariates = (\"discharge_risk\", \"age\", \"prior_utilization\")\n", "design = TrialWithExternalData(\n", " outcome=\"transition_score\",\n", " treatment=\"transition_navigation\",\n", " adjustment=covariates,\n", " source=\"in_pilot\", # 1 on pilot rows, 0 on record rows\n", ")\n", "study = CausalStudy(frame, design=design)\n", "effect = study.identify(TrialATE(population=\"trial\"))\n", "print(effect.summary())" ] }, { "cell_type": "markdown", "id": "identify-reading", "metadata": {}, "source": [ "`TrialWithExternalData` tells `cleverly` the outcome, the treatment, the covariates to adjust for,\n", "and which column marks pilot rows. `TrialATE(population=\"trial\")` asks for the effect among the\n", "pilot's patients. The conditions table lists what the answer rests on: the pilot's offer was random\n", "given the covariates (the setup states this, and the data cannot show it), and every kind of pilot\n", "patient could get either arm (the data can check this partly). Nothing is assumed about the records.\n", "The methods list holds one method, because every other method would treat the pooled rows as one\n", "population." ] }, { "cell_type": "markdown", "id": "estimate-heading", "metadata": {}, "source": [ "## Estimate the effect with and without the records" ] }, { "cell_type": "code", "execution_count": 5, "id": "estimate", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:08:38.320190Z", "iopub.status.busy": "2026-11-13T23:08:38.319996Z", "iopub.status.idle": "2026-11-13T23:08:40.719384Z", "shell.execute_reply": "2026-11-13T23:08:40.718339Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "pilot alone estimate 6.68, standard error 0.67, 95% interval 5.37 to 8.00\n", "pilot with records estimate 6.07, standard error 0.46, 95% interval 5.16 to 6.99\n", "true effect among pilot patients: 6.05\n", "label on the pilot-with-records interval: experimental\n" ] } ], "source": [ "fast = ModelSpec(\n", " outcome_learner=LinearRegression(),\n", " treatment_learner=LogisticRegression(max_iter=1000),\n", ")\n", "\n", "# Pilot rows alone: the usual estimate for a randomized trial.\n", "alone = (\n", " CausalStudy(\n", " pilot,\n", " design=PointTreatment(\n", " outcome=\"transition_score\",\n", " treatment=\"transition_navigation\",\n", " adjustment=covariates,\n", " ),\n", " )\n", " .identify(ATE())\n", " .estimate(method=TMLEMethod(models=fast, cross_fitting=CrossFitting(enabled=False)))\n", ")\n", "\n", "# Pilot and records together.\n", "borrowed = effect.estimate(method=AdaptiveTMLEMethod(models=fast, runtime=Runtime(random_state=1)))\n", "\n", "for label, fit in ((\"pilot alone\", alone), (\"pilot with records\", borrowed)):\n", " low, high = fit.estimate.ci\n", " print(\n", " f\"{label:19s} estimate {fit.estimate.psi:.2f}, standard error \"\n", " f\"{fit.estimate.std_error:.2f}, 95% interval {low:.2f} to {high:.2f}\"\n", " )\n", "print(f\"true effect among pilot patients: {truth['pilot patients']:.2f}\")\n", "print(f\"label on the pilot-with-records interval: {borrowed.estimate.support.label}\")" ] }, { "cell_type": "markdown", "id": "estimate-reading", "metadata": {}, "source": [ "The first fit is the usual estimate for a randomized trial, on the pilot rows alone. The second\n", "passes all 3,000 rows to `AdaptiveTMLEMethod`. Both use a linear model for the score and a logistic\n", "model for the offer, so the comparison shows the records' contribution and not a change of models.\n", "The `random_state` fixes how the rows are split into five groups, and each row's prediction comes\n", "from models trained on the other groups.\n", "\n", "With the records, the estimate is 6.07 and the standard error falls from 0.67 to 0.46, so the\n", "interval is about a third narrower. The narrowing happens here because the records differ from the\n", "pilot by the same amount in both arms, an offset plus a trend in prior utilization, which the fit\n", "can learn. Once that difference is removed, the records' comparison of offered and other patients\n", "adds to the pilot's. A gain is not guaranteed: if the records differed in a way the fit could not\n", "describe simply, the interval would stay near the pilot's width. The method labels every fit\n", "experimental, because its interval is for the fit's own description of the difference, and the data\n", "cannot confirm that this description is rich enough." ] }, { "cell_type": "markdown", "id": "assessment-heading", "metadata": {}, "source": [ "## Check what the fit used" ] }, { "cell_type": "code", "execution_count": 6, "id": "assessment", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:08:40.722173Z", "iopub.status.busy": "2026-11-13T23:08:40.721999Z", "iopub.status.idle": "2026-11-13T23:08:40.726085Z", "shell.execute_reply": "2026-11-13T23:08:40.725352Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "pilot rows: 560; record rows: 2440\n", "record rows that were offered navigation: 1203\n", "lowest chance that a record row is a pilot row: 0.014\n", "terms kept for the effect in fold 0: 11 of 22\n", "terms kept for the records' difference: 3 of 44\n" ] } ], "source": [ "report = borrowed.support_report()\n", "print(f\"pilot rows: {report.n_trial}; record rows: {report.n_external}\")\n", "print(f\"record rows that were offered navigation: {report.n_external_treated}\")\n", "print(f\"lowest chance that a record row is a pilot row: {report.external_source_min:.3f}\")\n", "fold = borrowed.working_models[0]\n", "effect_terms = len(fold.effect.selected)\n", "records_terms = len(fold.bias.selected)\n", "print(f\"terms kept for the effect in fold 0: {effect_terms} of {len(fold.dictionary.phi_keep)}\")\n", "print(f\"terms kept for the records' difference: {records_terms} of {len(fold.dictionary.psi_keep)}\")" ] }, { "cell_type": "markdown", "id": "assessment-reading", "metadata": {}, "source": [ "The record rows include 1,203 patients who were offered navigation, so the fit could learn the\n", "difference in both arms. The lowest estimated chance that a record row could be a pilot row is\n", "0.014. For the effect among pilot patients this number is information only, because the pilot covers\n", "itself.\n", "\n", "The fit builds two short formulas from a list of candidate terms: each covariate, bent-line pieces\n", "of it, and products of two covariates. One formula describes the effect and the other describes how\n", "the records differ from the pilot. It keeps a term only when the data support it. In the first of\n", "the five groups of rows (fold 0), it kept 11 of 22 candidate terms for the effect and only 3 of 44\n", "for the records' difference. Each group selects its own terms, and `borrowed.working_models` (the\n", "working models, which are these fitted formulas) lists them for every fold. A short description of\n", "the difference is what lets the records add information." ] }, { "cell_type": "markdown", "id": "interpret", "metadata": {}, "source": [ "## What we can and can't conclude\n", "\n", "Among pilot-like patients, navigation raised the 30-day transition score by about 6.07 points, with\n", "a 95% interval of 5.16 to 6.99, and borrowing the records cut the pilot's own standard error by\n", "about a third. The answer rests on three conditions. The pilot's offer was random given the\n", "covariates, every kind of pilot patient could get either arm, and the fit described the records'\n", "difference from the pilot well enough. The data cannot check the first or the third, and the\n", "interval covers only the effect inside the fit's own description of that difference.\n", "\n", "The page shows one simulated draw, so it does not show how often such an interval covers the truth.\n", "The result says nothing about patients unlike the pilot's. Simple learners are for trying the\n", "workflow. When trial enrollment depends on the covariates, an interval from misfit learners can miss\n", "the effect badly, so report a fit with flexible learners. If the pilot is the only sound evidence\n", "the plan has, report the pilot-alone interval beside this one. The fit refuses every\n", "sensitivity analysis and the refutation and truncation checks, because no bound is derived for it\n", "and each refit would pick its own description of the difference, so its fit checks are\n", "`result.diagnostics.support()`, `score_equations()`, `nuisance_models()` and `corrections()`." ] }, { "cell_type": "markdown", "id": "method-evidence", "metadata": {}, "source": [ "## How we know the method works\n", "\n", "A registered simulation study checks this method. It draws many simulated data sets in each of\n", "several settings, compares the 95% interval with the known truth, and reports how often the interval\n", "covers it and how well the standard error matches the real spread of the estimates. It includes\n", "control fits that should fail, such as a pooled comparison that ignores the difference, and a stress\n", "setting where the outside rows differ from the trial in a way the fit's simple model cannot\n", "describe. Its page lists every setting and its result, so read the numbers there. They are\n", "regenerated with the study and are not copied here.\n", "\n", "The study used its own simple models and sample sizes, not this page's, and a second study\n", "covers selective enrollment. The label stays experimental for every fit whatever such studies\n", "find, because the data cannot confirm that the fit's description of the difference is rich enough.\n", "The [study page](../technical-reference/method-evidence/adaptive-tmle-trial.md) holds the results,\n", "and the [technical reference](../technical-reference/adaptive-tmle.md) states the estimator and\n", "lists the unit tests that check the formulas on exact finite laws." ] }, { "cell_type": "markdown", "id": "comparison-heading", "metadata": {}, "source": [ "## Go deeper\n", "\n", "### The effect for all patients" ] }, { "cell_type": "code", "execution_count": 7, "id": "comparison", "metadata": { "execution": { "iopub.execute_input": "2026-11-13T23:08:40.727489Z", "iopub.status.busy": "2026-11-13T23:08:40.727314Z", "iopub.status.idle": "2026-11-13T23:08:43.579313Z", "shell.execute_reply": "2026-11-13T23:08:43.578321Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "effect among all patients: 5.10, 95% interval 4.25 to 5.96; true 5.00\n" ] } ], "source": [ "everyone = study.identify(TrialATE(population=\"pooled\"))\n", "pooled_fit = everyone.estimate(\n", " method=AdaptiveTMLEMethod(models=fast, runtime=Runtime(random_state=1))\n", ")\n", "low, high = pooled_fit.estimate.ci\n", "print(\n", " f\"effect among all patients: {pooled_fit.estimate.psi:.2f}, \"\n", " f\"95% interval {low:.2f} to {high:.2f}; true {truth['all patients']:.2f}\"\n", ")" ] }, { "cell_type": "markdown", "id": "comparison-reading", "metadata": {}, "source": [ "The effect among all patients is 5.10, close to the true 5.00, with a 95% interval of 4.25 to 5.96.\n", "It is the effect for all patients only if a pilot patient and a record patient with the same\n", "characteristics would respond to the offer alike, which the data cannot check. It differs from the\n", "effect among pilot patients because the offer helps sicker patients more and the pilot enrolled\n", "sicker patients. This question needs every record row to resemble some pilot patients, because the\n", "pilot's effect is carried over to the records' kind of patient. The lowest chance printed above\n", "(0.014) stays above the 0.01 level at which the fit warns, so the fit raised no warning." ] }, { "cell_type": "markdown", "id": "where-next", "metadata": {}, "source": [ "## Where to go next\n", "\n", "- [One treatment, one outcome](point-treatment-tmle.ipynb) explains the ordinary estimate used\n", " above for the pilot alone.\n", "- [A randomized pilot](randomized-pilot.ipynb) shows a trial whose offer chances are recorded.\n", "- [A small trial with external data](../user-guide/trial-with-external-data.md) lists the options\n", " of this method.\n", "- [Adaptive TMLE](../technical-reference/adaptive-tmle.md) states the quantity estimated, the\n", " conditions and the evidence.\n" ] } ], "metadata": { "cleverly_execution": { "command": [ "python", "scripts/execute_notebook.py", "docs/examples/trial-with-external-data.ipynb" ], "gated": { "code_source_sha256": "2c5014ed165d2c7c6c13a0dc90529a80d9650ff803284d94d969f7fa227a8d6d", "execution_payload_sha256": "201dbed5b9136283a6fdc9a9e2464a670a0d200bf4146fbd79421f3c234b593e" }, "recorded": { "cleverly_commit": "26d6a178ddefa6268fe222aaf6736c0c74094b45", "cleverly_version": "0.2.4", "cleverly_worktree_clean": false, "dependency_lock_sha256": "97129a1a44cd0790553fb022322da2d2f02b173723c6e8fadda8a84544278c22", "generator_files": [ "scripts/execute_notebook.py", "tests/notebooks.py" ], "generator_sha256": "f247771ab390b23e7e092d7eb35794e241c2ac84fc0526695df1cee1fc457a83", "package_source_sha256": "762ad45f627caef5bd6105008bf165b1bfe26fced79a24becb6f0276f9c804a9" }, "schema_version": 5 }, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.13.14" } }, "nbformat": 4, "nbformat_minor": 5 }