# CAPRE for the Classroom

Can a lower risk score buy a better outcome for the same ICU stay? In this 75-minute workshop, students compare a cut in surveillance counts with a joint mobility and turning visit. They fit observational models to 600 synthetic records, save their predictions, and open a separate simulator answer key. All prices are in simulated effort units.

## Before class

Extract the whole ZIP and start in the extracted folder. In the repository, the same starting folder is `docs/classroom/`. Use the [study guide](study-guide.pdf) for the lesson plan and [slides](slides.pdf) for projection. During the first four exercises, give students the worksheet and cohort. Reveal the oracle key in exercise 5. The command-line labs perform the same sequence automatically and write their comparison at the end.

Allow 8 minutes to introduce the flagged stay, 12 for surveillance proxies, 12 for the graph and mediator response, 10 for shared effort, 10 for model dependence and overlap, 15 for paired coding, and 8 for the oracle audit. For a 60-minute section, distribute the fitted summaries and work the first price example at the board.

## R quick start

From the kit folder, run the following in a terminal.

```sh
cd r-workshop
Rscript class-lab.R output
```

Use standard R with `stats`, `splines`, the base graphics device and `jsonlite`. CAPRE source is included. If this machine lacks `jsonlite`, install it once with `install.packages("jsonlite")`. In RStudio open `student-worksheet.Rmd` and run the chunks from the workshop directory. Knitting to HTML is optional and uses the usual R Markdown tools.

```r
source("class-lab.R")
summary_table <- run_class_lab(output_dir = "output")
print(summary_table)
source("capre-exercise.R")
higher_price <- run_capre_exercise(proxy_cost = 0.8)
higher_price$summary
```

## Python quick start

From the kit folder, run the following in a terminal.

```sh
cd python-workshop
python class_lab.py --output-dir output
```

Use Python 3.10 or newer with NumPy, pandas and scikit-learn 1.3 or newer. To supply them to a fresh environment, run `python -m pip install numpy pandas "scikit-learn>=1.3"`. These are the only analysis dependencies to install directly. The PNG writer uses NumPy and the standard library. In an existing Jupyter environment open `student_workshop.ipynb` with the workshop directory as the kernel working directory.

```python
from class_lab import run_class_lab
from capre_exercise import run_capre_exercise

summary_table = run_class_lab("output")
print(summary_table)
higher_price = run_capre_exercise(proxy_cost=0.8)
print(higher_price["summary"])
```

## What enters the analysis

The seed is 20261128. Sort by ID, train on the first 480 rows and reserve the last 120 for testing. Among those 120, take the first six by ID with mobility at most 2, turning at most 65%, and at least 36 lab tests. This classroom flag uses observations available before knowing the injury outcome. It can include a stay that already scores below the cutoff. Keep all six in the denominator.

The columns of `data/icu-ward-cohort.csv` are in this order.

- `patient_id` is an arbitrary stay identifier, ICU-0001 through ICU-0600. It determines the split.
- `bmi` is baseline body mass index in kg/m². It is fixed over the simulated shift.
- `braden_mobility` is a simulated ordinal mobility score from 1 to 4. Larger values denote greater mobility. The classroom action represents assisted mobilization.
- `turning_q2h_pct` is the percentage of scheduled two-hour turns completed, from 0 to 100.
- `enteral_nutrition_pct` is the percentage of the scheduled enteral nutrition target delivered, from 0 to 100.
- `serum_albumin` is simulated serum albumin in g/dL, a physiological mediator of nutrition.
- `tissue_tolerance` is a continuous simulated tissue-resilience index in arbitrary units. Higher values lower injury risk in the generator.
- `lab_count_48h` counts laboratory testing over 48 hours.
- `lactate_draws_48h` counts lactate tests over 48 hours.
- `hapri` is the observed binary hospital-acquired pressure injury outcome, coded 1 for an injury and 0 otherwise.

The eight predictors run from BMI through the two counts. The first six are observed causal ancestors in the supplied graph. BMI, albumin and tissue tolerance can enter a prediction while being locked against direct intervention. Latent severity and the unit-level risks are absent from the cohort.

## Compare the four searches

Each lab fits two three-fold SuperLearners to the training rows and fits the structural equations there. Each solver searches single actions and pairs with up to three prioritized levers for pairs. The output retains its first ranked proposal. A search that finds no acceptable proposal counts as `no_option`.

- `flat_unpriced` edits any predictive input. Its search cost is the sum of absolute changes in training SDs and it ignores the three-unit effort budget. It can propose a direct change to a locked physiological value.
- `flat_priced` (cost-only search) locks BMI and physiology, charges directional prices, and scores all eight predictors. Reducing a cheap surveillance count can imitate a less ill patient on that fitted surface.
- `flat_locked_priced` also excludes both surveillance variables and scores the six observed ancestors. It holds each unedited predictor at its factual value.
- `causal_priced` allows the same direct actions and recomputes affected descendants. It retains each stay's fitted residual as its parents change and clips propagated mediators to the training range.

In this simulator, hidden severity causes both more testing and higher injury risk. Neither surveillance count has a directed path to injury. Changing the price can move a proxy edit up or down the ranking. Its true effect remains zero. On this cohort both languages select surveillance edits in five of six cost-only searches, and none of the five qualifies as oracle recourse.

## Price, dispersion and support

For an allowed change, divide its magnitude by the feature's training SD. Variable effort is the directional price times that standardized magnitude raised to the effort exponent. A shared mobility-team visit adds 0.45 once. The signed square root of each variable effort gives its warped coordinate. The sum of squared coordinates plus all active setups recovers total effort. For ICU-0486 the joint visit costs 2.903. Pricing two visits separately gives 3.353.

The ensemble learns nonnegative weights summing to one using out-of-fold binary log loss. The fitted risk uses those weights. For dispersion, CAPRE averages each learned weight with an equal share and calculates the weighted SD of learner predictions about their own blended center. With the factual mean above 0.45, a candidate passes the model test when its mean risk plus 0.5 times its dispersion is at most 0.45. A larger penalty makes the test stricter for a fixed candidate. This spread measures sensitivity to the chosen library and has no confidence level. King and Zeng explain why counterfactual predictions away from the data admit greater model dependence; see [King and Zeng (2006)](https://doi.org/10.1093/pan/mpj004) and [van der Laan, Polley and Hubbard (2007)](https://doi.org/10.2202/1544-6115.1309).

Kish effective sample size is `sum(w)^2 / sum(w^2)` for Gaussian kernel weights on regularized Mahalanobis distance from the candidate to the training profiles. Concentration on one stay gives ESS near one. Uniform weights across all 480 training stays give ESS 480. A common rescaling cancels, so a large value alone cannot establish proximity or sufficient causal overlap. Compare profiles within the same feature set and kernel settings. The default lab reports ESS without applying a minimum. The guide includes the sampling reference.

R uses a main-effects logistic model, ridge interactions, a spline model and a quantile smoother. Python uses penalized interactions, an additive spline model, boosted trees (24 iterations) and a random forest (16 trees) for classroom speed. The implementations also use different covariance regularization and kernel bandwidth conventions. Compare actions, denominators and the shared truth. Numerical scores and ESS can differ by language or package version.

## Read the results

The output directory contains the following four files. Supplying a different directory keeps a previous run available.

- `summary.csv` gives the number of flags, model flips, initial scores at or below cutoff, searches with no proposal, plans with a proxy edit, infeasible plans and budget-valid oracle recourse. Median disagreement and ESS summarize returned proposals. An empty median means the mode returned none.
- `plans.csv` has one row per flagged stay and mode (24 rows). It records the actual action targets as JSON, status, fitted risks, search cost, spread and ESS. After reveal it adds factual and replayed oracle risks, reference cost, and audit indicators. A locked or forbidden edit has infinite true cost and a missing replay risk. A search with no action leaves post-action values empty.
- `fixed-plans.csv` has one row per stay and prescribed plan (12 rows). It compares the flat eight-feature prediction for the proxy cut and the propagated six-feature prediction for the turning bundle with the corresponding key. The `model_flip` column tests the score crossing. Check `estimated_cost` separately for these prescribed plans.
- `comparison.png` plots classifier flips and budget-valid oracle recourse by mode using all six flags. The R version uses base graphics.

### Match the action before grading it

The key contains `patient_id`, `oracle_risk_factual`, `oracle_risk_proxy_cut`, `oracle_risk_turn_bundle`, and `oracle_true_cost_turn_bundle`. These are conditional probabilities for that synthetic stay and the reference effort for its prescribed bundle. The observed zero or one in `hapri` is a single outcome realization.

The proxy cut subtracts 12 laboratory tests and 3 lactate tests, with a floor of zero. The turning bundle raises mobility to at least 3 and turning to at least 80%. These values stay fixed across languages. The key is joined by ID only after prediction and search. For an optimized action, the audit takes that stay's factual oracle log odds and adds the structural log-odds change for the action actually selected. Fixed physiological disturbances and severity cancel in this difference. It prices this action at the reference rates. Assigning the prescribed bundle's risk to an arbitrary proposed action would misgrade it.

A successful oracle crossing requires factual risk above 0.45, post-action risk at or below 0.45, and true cost at most 3.0. The prescribed bundle passes for ICU-0486 and ICU-0515. It gets ICU-0517 below the threshold at a cost of 3.478. On these six stays the causal searches lower fitted scores, but neither track's selected plans pass all three oracle checks.

### Paired sensitivity exercises

Both exercise functions accept the same five arguments. They return the summary, optimized plan detail, and prescribed contrast detail under `summary`, `plans`, and `fixed`.

- `seed` selects the synthetic cohort, the folds and the random stream used for prices. The default with `gamma_u=1` uses the two supplied CSVs.
- `proxy_cost` changes each surveillance slope used during search. The reference audit retains 0.08.
- `gamma_u` scales how strongly severity influences observed care and physiological states. A different value regenerates the cohort and its matching key in memory. At zero, severity still affects testing and the outcome. The flag can select different IDs.
- `price_noise_sd` multiplies each mutable slope or setup by its own log-normal factor with log-scale SD as specified. Hold the seed fixed to compare ratings using the same shocks. The reference budget uses unperturbed prices.
- `lambda_md` controls the margin for disagreement. Its default is 0.5. Try 0 and 1 on the same candidates.

## File map

- `index.html` is the classroom page of the CAPRE primer. Its material links also work in the extracted kit. The primer, shared site stylesheet and download navigation belong to the hosted site.
- `study-guide.tex` and `study-guide.pdf` are the editable six-page educator guide and its printable version. `references.bib` supplies the three readings.
- `slides.tex` and `slides.pdf` are the editable 13-frame Beamer deck and its projection copy. Timings and discussion prompts appear in the source as speaker notes.
- `figures/proxy-paths.drawio` is the editable teaching graph. `figures/proxy-paths.pdf` is its vector export, included by both TeX files. Open the source in diagrams.net to move boxes, edit labels or reconnect arrows. Use **File → Export as → PDF**, select **Crop**, and save over the vector PDF before recompiling.
- `data/workshop-design.json` specifies the graph, directional prices, structural coefficients, case flag, cutoffs and fixed action targets. The two CSVs hold the observations and the matched key described above.
- `r-workshop/class-lab.R` and `python-workshop/class_lab.py` run the fixed-cohort analyses. `r-workshop/design.R` and `python-workshop/class_design.py` read the shared design, generate paired simulations and replay the oracle. `python-workshop/plot_counts.py` renders the labeled count plot.
- `r-workshop/capre-exercise.R` and `python-workshop/capre_exercise.py` expose the five scenario controls. The function calls leave the packaged cohort untouched.
- `r-workshop/student-worksheet.Rmd` and `python-workshop/student_workshop.ipynb` contain the five exercises. `r-workshop/instructor-solutions.Rmd` and `python-workshop/instructor_solutions.ipynb` supply executable solutions and interpretation.
- `r-workshop/R/capre.R` implements graphs, pricing, structural propagation and search. `superlearner.R` fits the ensemble and scores overlap. `datasets.R` contains the R package's separate demo generator.
- In `python-workshop/capre/`, `__init__.py` exposes the API, `spec.py` defines graphs and prices, `scm.py` fits structural equations, `solver.py` searches for recourse, and `superlearner.py` fits ensembles and measures overlap. `datasets.py` contains a separate package demo. `credence.py` and `navigator.py` are the upstream simulator and graph-import utilities.
- `LICENSE` supplies the MIT terms. `provenance.json` maps every payload file to its SHA-256 digest and identifies the upstream sources of the vendored code. The ZIP comment contains the SHA-256 of the complete manifest itself.
- The ZIP includes `package_classroom_kit.py` at its top level. In the repository the same builder lives in `scripts/`. Its inputs are the maintained teaching files and the original CAPRE sources in the [CAPRE repository](https://github.com/andystats/capre).

## Rebuild

From the repository root, run `python scripts/package_classroom_kit.py`. From the extracted kit folder, run `python package_classroom_kit.py`. R, the three Python analysis dependencies, pdfLaTeX and BibTeX must be available. The builder uses the specified Windows R and MiKTeX locations when present and otherwise looks on PATH.

The builder stages the sources, generates the two CSVs, compiles both PDFs twice, checks the final logs, and runs both labs from fresh working directories with a 45-second limit per process. It checks each matched oracle comparison, hashes the explicit payload, and writes `capre-classroom-kit.zip` in the sibling `downloads/` folder. Sorted file names, fixed ZIP metadata and stable PDF metadata permit byte-for-byte rebuilds with the same toolchain. Edit the TeX, notebooks, or diagram source directly. The builder reads these files on each run. In the repository it refreshes vendored code from the upstream R and Python folders.

To compile the teaching documents by hand from the kit directory, use the following commands.

```sh
pdflatex -interaction=nonstopmode -halt-on-error study-guide.tex
bibtex study-guide
pdflatex -interaction=nonstopmode -halt-on-error study-guide.tex
pdflatex -interaction=nonstopmode -halt-on-error study-guide.tex
pdflatex -interaction=nonstopmode -halt-on-error slides.tex
pdflatex -interaction=nonstopmode -halt-on-error slides.tex
```
