Skip to content

Evaluation

score_fold scores one held-out fold exactly as the study's code of record does, and pool_folds pools folds. Golden tests require identical output.

from symphony_dt.evaluate import ScoringSpec, freeze_spec, score_fold
spec = ScoringSpec.default()
frozen = freeze_spec(spec, "frozen_spec.json")   # before any target is scored
scores = score_fold(split.fit.data, split.targets.data, split.meta, forecast.draws,
                    split.test_index, spec=spec, frozen=frozen)
scores.write("scores")

Three methods are scored on the same targets. They are the twin, LOCF with horizon-binned training residuals and the linear mixed model, fitted by EM on training participants only. Metrics are 50% and 95% interval coverage, CRPS and the absolute error of the median. Windows are the next visit, one year, two years and all horizons. Intervals come from a participant-cluster bootstrap with 1,000 replicates.

pool_folds adds event metrics: Brier, Brier skill and AUC. It adds strata by sex, cohort, age band, visits before the anchor and follow-up. It suppresses any cell with fewer than 10 participants.

Calibration by subgroup (TESTED)

A twin can be calibrated overall and miscalibrated in a subgroup, such as older participants or one site. subgroup_calibration scores the per-target table within each level of any grouping you name. It reports 50% and 95% interval coverage and CRPS for the twin, LOCF and the mixed model, each with a participant-cluster bootstrap interval. For the twin it adds the mean and spread of the PIT values and a Kolmogorov-Smirnov test of uniformity.

from symphony_dt.evaluate import age_band, subgroup_calibration
ts = scores.target_scores
site = {i: site_of[i] for i in ts["i"].unique()}   # your own participant-to-site lookup
result = subgroup_calibration(
    ts,
    {"sex": "sex", "cohort": "cohort", "age band": age_band(ts["age"]), "site": site},
    twin_draws=forecast.draws,
)
print(result.to_markdown(metric="c95"))
result.plot(metric="c95", endpoint="moca")

A grouping is a column of the table, a mapping from participant index to label, or one label per row. Genotype groups and sites come as mappings, because the scoring table does not hold them. An overall row is always included, so each level can be read against the whole fold.

Three cautions apply. A cell with fewer than min_cell participants, 10 by default, is suppressed in the table, the Markdown and the plot. The PIT values of one participant are correlated, so the uniformity p-values are approximate. Many cells mean many tests, so the p-values are adjusted by Benjamini-Hochberg by default; pass multiplicity="bonferroni" or "none" to change this.

pool_folds already reports twin coverage by sex, cohort and age band for the study. subgroup_calibration extends that check to any grouping, to CRPS and PIT, and to both baselines.

Decision curve analysis (TESTED)

Brier scores and AUC summarise the event forecasts. They do not say whether flagging a participant at a given risk would be worth it. decision_curve reports net benefit across threshold probabilities, as proposed by Vickers and Elkin (2006). A target is flagged when its forecast event probability is at least the threshold. Net benefit is the share of true flags minus the share of false flags, weighted by the odds of the threshold.

from symphony_dt.evaluate import decision_curve
curve = decision_curve(scores.target_scores)
print(curve.to_markdown(thresholds=(0.05, 0.1, 0.2, 0.3)))
curve.plot(endpoint="updrs3")

The twin, LOCF and the mixed model are scored on the same targets. Two references are always included: flag every target ("all") and flag none ("none"). The literature calls these "treat all" and "treat none". A forecast is of use at a threshold only where its curve lies above both references. Each estimate carries a participant-cluster bootstrap interval, and the same resamples serve every curve of an endpoint.

The events follow the scoring code of record. They are a UPDRS-III worsening of 5 points or more and a MoCA decline of 2 points or more. An endpoint with fewer than min_cell participants, events or non-events is suppressed. Net benefit describes forecasts against observed events. It does not show that acting on a flag changes any outcome. net_benefit scores a single threshold for your own probabilities.

Quantile recalibration for an external cohort (TESTED)

A forecast can be too narrow or too wide on a cohort it was not developed on. recalibrate_quantiles learns a correction on part of that cohort and scores it on the rest. The method is the quantile recalibration of Kuleshov, Fenner and Ermon (2018).

from symphony_dt.evaluate import recalibrate_quantiles
res = recalibrate_quantiles(forecast.draws, forecast.targets, calibration_fraction=0.5, seed=20261021)
print(res.to_markdown())
res.plot(endpoint="updrs3")              # coverage against the nominal level
res.plot(endpoint="updrs3", kind="pit")  # PIT histograms
new_draws = res.apply(later.draws, later.targets)

The targets need the participant i, the endpoint index k and the observed value y. Participants, never targets, are split at random into a calibration subset and an evaluation subset. calibration_ids names the calibration subset instead. On the calibration subset each observation gets its PIT value under its forecast. Ties at a scale floor or ceiling are randomised, so point masses are handled. The empirical quantile function of these PIT values is the map. A recalibrated forecast reads the original forecast at the mapped levels.

A plain ensemble cannot place a quantile beyond its most extreme draw. A forecast that is too narrow could then be widened only so far. By default each interior draw is therefore dressed with a Gaussian kernel, as in Bröcker and Smith (2008). Kernel mass beyond a scale bound is moved onto that bound, and draws on a bound keep their mass. smoothing="none" uses the plain ensemble. Either way the recalibrated draws stay inside the scale bounds.

One map is fitted per endpoint. pool_endpoints=True fits one map for all endpoints, and horizon_edges fits one per horizon window. The table gives interval coverage at 50%, 80% and 95% and the mean CRPS on the evaluation subset. Each comes before and after, with the difference after minus before. All carry participant-cluster bootstrap intervals. An endpoint with fewer than min_cell participants in either subset is suppressed and gets no map.

Recalibration corrects the calibration of the forecast distribution on one cohort. It does not validate the model on that cohort. Its scores are only fair on participants kept apart from the calibration subset, as evaluation_ids records. A map fitted on one cohort says nothing about another. calibration_ids and evaluation_ids identify participants, so keep them where the data are governed.

Leave-future-out predictive density (TESTED)

Coverage and CRPS judge the forecast draws one target at a time. The log predictive density scores the whole forecast distribution at the observed value, and it is the natural criterion for comparing models. A forecast should only be scored on data later than the history it saw. leave_future_out therefore scores exact leave-future-out density, as set out by Bürkner, Gabry and Vehtari (2020). At each anchor the model is refitted on the data up to that anchor, so no importance sampling is needed.

from symphony_dt.evaluate import anchor_draws, leave_future_out
from symphony_dt.fit import fit
from symphony_dt.forecast import forecast_exact, split_at_anchor

per_anchor = {}
for anchor in (1.0, 2.0, 3.0):
    split = split_at_anchor(stan_data, test_index, anchor_years=anchor)
    result = fit(split.fit, chains=4, output_dir=f"lfo/fit_{anchor:g}")
    forecast = forecast_exact(result, split, output_dir=f"lfo/forecast_{anchor:g}")
    per_anchor[anchor] = anchor_draws(forecast, split)
scores = leave_future_out(per_anchor)
print(scores.to_markdown())

Each target scores the log of the mean, over posterior draws, of its observation density. The density is the one in the model. A truncated endpoint gets a normal renormalised to the scale bounds. A censored endpoint gets a tobit density with point masses at the bounds. anchor_draws rebuilds the observation mean and noise of every draw from the thinned fit. The rebuilt mean matches the mu_c output of the generated-quantities program, and a slow test checks this.

scores.pointwise holds one row per anchor and target, with a Monte Carlo standard error. scores.joint holds the joint density of each participant's future block. Given a latent path the targets are independent, so the joint density keeps the dependence that the shared path induces. scores.summary sums by anchor and endpoint, with a standard error clustered on participant. Rows with anchor "all" pool the anchors. scores.compare(other) gives the paired difference between two models or arms on their shared targets.

The densities are on the scale of the data, so they compare models fitted to the same targets. They describe the fit of forecasts to later observations and do not support a causal or treatment claim. For your own forecasts, build AnchorDraws directly from draws of the mean and noise, or call predictive_log_density.

PSIS-LOO and stacking (TESTED)

Leave-one-out cross-validation asks how well a model predicts each observation when it has not seen it. Exact leave-one-out needs a refit per observation. psis_loo instead reweights the full-data posterior draws by Pareto smoothed importance sampling. The method is set out by Vehtari, Gelman and Gabry (2017) and Vehtari and colleagues (2024). The implementation follows the loo R package and ArviZ, and the tests reproduce ArviZ on its eight schools example.

import pandas as pd
from symphony_dt.evaluate import fit_log_likelihood, psis_loo

draws = pd.concat([pd.read_csv(f, comment="#") for f in result.csv_files], ignore_index=True)
log_lik, obs = fit_log_likelihood(draws, split.fit)
by_visit = psis_loo(log_lik)
by_participant = psis_loo(log_lik, groups=obs["i"])
print(by_participant.to_markdown())

fit_log_likelihood scores each observation under each draw with the model's own truncated or censored density. psis_loo takes any (draws, observations) log likelihood, so other models can be scored in the same way. With groups, the log likelihoods of a group are summed first, so the whole group is left out. Grouping by participant asks how well the population part of the model predicts a new person. Pass r_eff, for example from relative_efficiency, when chains are autocorrelated. It sets the length of the smoothed tail.

Each unit carries a Pareto k. Above the threshold min(1 - 1 / log10(S), 0.7) for S draws, the estimate for that unit is unreliable, and reliable is false. Participant-level parameters make many observations influential. High k values are therefore to be expected for pd_v2, more so when whole participants are left out. Exact refits or leave-future-out scores are then the safer route. k_table counts units by band, and n_eff gives the effective sample size of the weights.

Stacking combines models rather than choosing one. stacking_weights finds the weights of a mixture of the predictive distributions that maximise its summed log score, following Yao, Vehtari, Simpson and Gelman (2018). pseudo_bma_weights gives the pseudo-BMA+ weights of the same paper, stabilised by the Bayesian bootstrap. loo_compare ranks models, gives paired differences from the best with their standard errors, and adds the stacking weights.

from symphony_dt.evaluate import loo_compare, stacking_weights

print(loo_compare({"primary": loo_primary, "a01": loo_a01}))
weights = stacking_weights({"primary": lfo_primary, "a01": lfo_a01})   # LFOScores also work

Each input is a LOOResult, an LFOScores or a plain array of pointwise log densities. Units are matched by name, so leave-future-out scores of two arms are stacked on their shared targets only. Weights describe which mixture of forecasts best matched the observations. They do not show that one model is the true one.

Prior sensitivity by power scaling (TESTED)

A posterior can lean on its prior more than intended, or the prior can pull against the data. Power scaling checks both without a refit. It raises the prior, or the likelihood, to a power alpha near one and measures how far each posterior variable moves. The method is set out by Kallioinen, Paananen, Bürkner and Vehtari (2024). It is the one in the priorsense R package and in ArviZ, and the tests reproduce ArviZ on its eight schools example.

import pandas as pd
from symphony_dt.evaluate import pd_v2_powerscale_sensitivity

draws = pd.concat([pd.read_csv(f, comment="#") for f in result.csv_files], ignore_index=True)
sens = pd_v2_powerscale_sensitivity(draws, split.fit)
print(sens.to_markdown())
noise = pd_v2_powerscale_sensitivity(draws, split.fit, prior_blocks=["sigma_xi"])

The perturbed posteriors come from Pareto smoothed importance sampling, with log ratios (alpha - 1) times the log prior or log likelihood. cjs_distance measures each shift as the cumulative Jensen-Shannon distance between the original and the reweighted draws. The sensitivity is that distance per unit of log2 alpha, averaged over alpha 0.99 and 1.01. Values at or above 0.05 count as sensitive. Prior and likelihood sensitivity together suggest prior-data conflict. Prior sensitivity alone suggests a strong prior or a weak likelihood. pareto_k checks each set of weights, and reliable is false when any k is too high to trust.

pd_v2 is frozen, so its program cannot gain a log prior variable. pd_v2_log_prior computes the declared priors of the global parameters in Python, from the draws and the prior settings in the data block. A slow test checks it against Stan's own log density. prior_blocks power scales a subset, such as the process noise sigma_xi, whose prior the model card notes. The participant terms s0, b_raw and eps belong to the hierarchy and are never scaled, as the paper advises.

For any other model, pass draws, a log prior and a log likelihood to powerscale_sensitivity. powerscale_moments shows how the mean and sd of each variable move over a wider range of alpha. A flag is a prompt to look again at a prior or at the data. It does not by itself show that either is wrong.

Sensitivity to data missing not at random (TESTED)

A participant who drops out leaves outcomes that were never measured. A forecast of those outcomes assumes they follow the same model as the observed ones, given the history. This is the missing at random assumption. It fails when the reason for leaving is the unseen worsening itself. delta_adjustment asks how far the cohort summaries move if the missing outcomes were worse than the model predicts. The method is delta adjustment, as set out by Carpenter, Roger and Kenward (2013) and in the tutorial of Cro and colleagues (2020). The National Research Council (2010) advises such an analysis.

import numpy as np
from symphony_dt.evaluate import delta_adjustment

# observed: columns i, k, horizon, y and last, one row per outcome seen at an assessment time.
# forecast: draws for the outcomes missing after dropout; its targets hold i, k, horizon and last.
mnar = delta_adjustment(observed, forecast.draws, forecast.targets, deltas=np.arange(0, 11))
print(mnar.to_markdown(endpoint="updrs3"))
mnar.tipping_point(30.0, endpoint="updrs3", time=2.0)
mnar.plot(endpoint="updrs3", reference=30.0)

Each delta shifts every imputed draw towards worse health, in points of the endpoint's scale. Worse is higher for UPDRS-III and SCOPA-AUT and lower for MoCA. The shifted draws are clipped to the scale bounds. Each draw then joins the observed outcomes to give a cohort mean per endpoint and assessment time. With a column last, the share meeting the event rule of the scoring code is also reported. Delta 0 is the missing at random summary and is always in the grid. Pass a mapping, such as {"updrs3": [0, 2, 4], "moca": [0, 1, 2]}, to give each endpoint its own grid.

Away from the bounds, the mean moves by delta times the share of outcomes imputed. The table reports that share, so a large shift can be traced to heavy dropout. tipping_point returns the smallest delta at which a summary reaches a reference value, interpolated between grid points. It returns None when the grid holds no such delta. Use the lower or upper interval limit, such as summary="mean_lo", to ask when an interval would first reach the reference.

The intervals are central over imputation draws. They describe this cohort's outcomes, not a wider population, and carry no sampling uncertainty. A cell with fewer than min_cell participants, 10 by default, is suppressed. The analysis does not estimate the true missingness mechanism. It reports associational summaries under named departures from missing at random, with no causal or treatment claim. Whether a delta is plausible is a clinical judgement.

The building blocks are public: crps_ensemble, interval_coverage, fit_lmm_em, event_probability, auc_with_ties, net_benefit, predictive_log_density, bootstrap_mean, psis and fit_generalized_pareto, powerscale_log_weights and cjs_distance.

Prognostic scores for trial adjustment (TESTED)

A randomised comparison of two arms is unbiased without adjustment. Its precision can still improve when the analysis adjusts for a good prediction of each participant's outcome. Schuler and colleagues (2022) call this prognostic covariate adjustment. The EMA qualified the procedure, as PROCOVA, in a CHMP opinion of September 2022.

prognostic_scores gives one score per participant and endpoint. It is the mean, or the median, of the twin's predictive distribution at a fixed horizon after baseline. From a dataset it first drops every visit after baseline_days. It then builds a twin per participant on the population you pass. Pass the population fit's standardisation, so no post-baseline value enters a score. A Forecast, or a list of them, also works, as long as its horizons count from baseline.

from symphony_dt.evaluate import prognostic_scores, simulate_prognostic_trial
from symphony_dt.twin import PopulationDraws

population = PopulationDraws.from_fit(fit)            # fitted on data independent of the trial
scores = prognostic_scores(dataset, population, horizon_years=2.0, endpoints=["updrs3"],
                           standardisation=fit_standardisation)

trial = simulate_prognostic_trial(200, endpoint="updrs3", horizon_years=2.0, effect=-3.0, seed=0)
print(trial.to_markdown())
trial.plot()

simulate_prognostic_trial simulates a cohort from pd_v2, with one visit at baseline and one at the horizon. The twin scores each participant from baseline data only. By default it runs on the generating parameters, an oracle population as in the benchmark. Participants are randomised 1:1 and a known constant is added to the treated arm's outcome. Three estimators are compared: the difference in means, ANCOVA on the score and ANCOVA on the baseline value. prognostic_trial runs the same comparison on your own simulated frame.

Each row of the table gives the estimate, its standard error and a t interval. Standard errors are model based by default; se="hc1" gives the HC1 sandwich. The variance ratio compares each standard error with the unadjusted one. The table also gives rho, the correlation of covariate and outcome in the control arm. The theoretical ratio is 1 minus rho squared, and rho squared is the implied share of sample size saved. Further randomisations of the same participants give an empirical variance ratio and the bias against the simulated effect.

The tests check the estimators against closed forms. A score equal to the outcome's noise-free mean reaches a variance ratio of 1 minus rho squared, without bias. A score of pure noise leaves the variance unchanged on average. Changing any post-baseline value leaves every score unchanged.

The output is a precision gain in a simulated trial under the model. The effect, the outcomes and the randomisation are all simulated. It is not a claim about any real trial, treatment or intervention. An oracle score is a best case, and a score from a fit on other data will correlate less with the outcome.