symphony_dt.evaluate¶
symphony_dt.evaluate ¶
Evaluation: the scoring code of record, its metrics and the pre-registration freeze.
DecisionCurve
dataclass
¶
Net benefit per endpoint, strategy and threshold probability.
table has one row per endpoint, strategy and threshold. It holds the net benefit with its
participant-cluster bootstrap interval, the target and participant counts and the observed event
rate. Suppressed endpoints hold no counts or scores.
Validation: TESTED.
to_markdown ¶
to_markdown(
*, thresholds: Sequence[float] = (0.05, 0.1, 0.2, 0.3)
) -> str
Return a Markdown table of net benefit at selected thresholds, one column per strategy.
Validation: TESTED.
plot ¶
plot(*, endpoint: str | None = None, ax: Any = None) -> Any
Plot net benefit against threshold probability; see plots.plot_decision_curve.
Validation: TESTED.
AnchorDraws
dataclass
¶
Forecast draws of the observation mean and noise for the targets of one anchor.
targets has one row per target with at least i (participant), k (endpoint index 1 to
3) and y (the observed value). mu and sigma are (draws, targets). lower, upper and
censored hold one value per endpoint, in endpoint order.
Validation: TESTED.
log_density ¶
log_density() -> NDArray[np.float64]
Return the (draws, targets) log density of each target under each draw.
Validation: TESTED.
LFOScores
dataclass
¶
Leave-future-out log predictive densities: per target, per participant block and summed.
pointwise has one row per anchor and target, with elpd (the log predictive density) and
its Monte Carlo standard error mcse. joint has one row per anchor and participant: the
joint log density of all that participant's targets, and the sum of their pointwise values.
summary sums elpd by anchor and endpoint, with a participant-cluster standard error.
Rows with anchor "all" pool every anchor and cluster on participant across anchors.
Validation: TESTED.
compare ¶
compare(other: LFOScores) -> pd.DataFrame
Return the paired difference in elpd, self minus other, by anchor and endpoint.
Targets are matched on anchor, participant, endpoint and time, and only shared targets are compared. The standard error clusters the differences on participant.
Validation: TESTED.
LOOResult
dataclass
¶
PSIS-LOO estimates: totals, their standard errors and one row per left-out unit.
pointwise has one row per left-out observation or group, with unit, elpd_loo, p_loo,
lpd (the in-sample log predictive density), pareto_k, n_eff and reliable. A unit is
reliable when its k is at most k_threshold. elpd_loo is the summed estimate and se its
standard error. p_loo is the effective number of parameters, lpd minus elpd_loo.
Validation: TESTED.
looic
property
¶
looic: float
Return -2 times elpd_loo, the information criterion scale.
Validation: TESTED.
n_unreliable
property
¶
n_unreliable: int
Return the number of units whose Pareto k exceeds the threshold.
Validation: TESTED.
k_table ¶
k_table() -> pd.DataFrame
Return counts and shares of units by Pareto k band: good, at most 1, and above 1.
Validation: TESTED.
to_markdown ¶
to_markdown() -> str
Return the estimates and the Pareto k table as Markdown.
Validation: TESTED.
PSISResult
dataclass
¶
Pareto smoothed log weights with their diagnostics, one column per set of ratios.
log_weights is (draws, columns), normalised so each column's weights sum to one. pareto_k
is the fitted tail shape of each column. n_eff is the effective sample size of the weights,
1 / sum(w^2) times the relative efficiency. tail_length is the number of smoothed draws.
Validation: TESTED.
LMMFit
dataclass
¶
A fitted linear mixed model: fixed effects, random-effect covariance, residual variance.
Validation: VALIDATED.
as_dict ¶
as_dict() -> dict[str, Any]
Return the fit in the layout of the study's scores file.
Validation: VALIDATED.
DeltaAdjustment
dataclass
¶
Cohort summaries per endpoint, assessment time and delta, under delta-adjusted imputations.
table has one row per endpoint, time and delta. It holds the participant counts, the share of
outcomes that are imputed, the mean score and the share meeting the event rule. Each summary has a
central interval over imputation draws at level. A positive delta is a shift towards worse
health in points of the endpoint's scale. Delta 0 is the missing at random summary. Suppressed
cells hold no counts or summaries.
Validation: TESTED.
tipping_point ¶
tipping_point(
reference: float,
*,
endpoint: str,
time: float,
summary: str = "mean",
direction: str = "worse",
) -> float | None
Return the smallest delta at which summary reaches reference, or None in the grid.
The search starts at delta 0 and moves through the grid towards worse health, or towards
better health with direction="better". Between neighbouring grid points the summary is
interpolated linearly. A delta 0 summary equal to the reference returns 0.
Validation: TESTED.
to_markdown ¶
to_markdown(*, endpoint: str | None = None) -> str
Return a Markdown table of the summaries by endpoint, time and delta.
Validation: TESTED.
plot ¶
plot(
*,
endpoint: str | None = None,
summary: str = "mean",
reference: float | None = None,
ax: Any = None,
) -> Any
Plot a summary against delta, one line per time; see plots.plot_delta_adjustment.
Validation: TESTED.
PowerScaleSensitivity
dataclass
¶
Power-scaling sensitivity of each variable to the prior and to the likelihood.
table has one row per variable with prior and likelihood sensitivity and a diagnosis.
A missing component gives nan and an empty diagnosis. pareto_k has one row per component and
alpha, with the Pareto k of its weights and whether that k is at most k_threshold. Values above
threshold count as sensitive.
Validation: TESTED.
flagged
property
¶
flagged: DataFrame
Return the rows whose diagnosis names a potential problem.
Validation: TESTED.
reliable
property
¶
reliable: bool
Return True when every set of weights has a Pareto k at most the threshold.
Validation: TESTED.
to_markdown ¶
to_markdown() -> str
Return the sensitivity table and the Pareto k checks as Markdown.
Validation: TESTED.
PrognosticTrial
dataclass
¶
A simulated two-arm trial analysed with and without adjustment for a prognostic score.
table has one row per estimator: the estimate, its standard error and t interval, and the variance
ratio against the unadjusted estimate. It adds the control-arm correlation rho and R^2 of outcome and
covariates, the theoretical ratio 1 - R^2 and the implied sample size reduction R^2. With replicate
randomisations it also holds the empirical mean, SD, variance ratio and bias of each estimator.
participants holds the arm, outcome and covariates of each participant.
Validation: TESTED.
RecalibrationMap
dataclass
¶
A recalibration map: the empirical quantile function of calibration PIT values, on a grid.
endpoint is an endpoint name or "pooled" and window a horizon window or "all". The map sends a
nominal level in levels to the level in values at which the original forecast is read.
Validation: TESTED.
max_shift ¶
max_shift() -> float
Return the largest distance between the map and the identity, a summary of miscalibration.
Validation: TESTED.
RecalibrationResult
dataclass
¶
Recalibration maps fitted on a calibration subset and scores on a separate evaluation subset.
table has one row per endpoint and metric: interval coverage at each level and mean CRPS. Each row
holds the score before and after recalibration and the difference after minus before. Every value
carries a participant-cluster bootstrap interval. Suppressed endpoints hold no counts or scores.
pit_histogram holds PIT densities of the evaluation subset per endpoint, before and after.
calibration_ids and evaluation_ids identify participants and must stay where the data are
governed.
Validation: TESTED.
apply ¶
apply(
draws: ArrayLike,
targets: DataFrame,
*,
strict: bool = True,
) -> NDArray[np.float64]
Return recalibrated draws of the same shape for new forecasts of the same kind.
targets needs the column k, and the horizon column when maps are stratified by horizon.
A target without a map, such as one of a suppressed endpoint, raises an error. With
strict=False its draws are returned unchanged instead.
Validation: TESTED.
to_markdown ¶
to_markdown() -> str
Return a Markdown table of each score before and after, with bootstrap intervals.
Validation: TESTED.
plot ¶
plot(
*,
endpoint: str | None = None,
kind: str = "coverage",
ax: Any = None,
) -> Any
Plot coverage against the nominal level, or PIT histograms; see plots.plot_recalibration.
Validation: TESTED.
FoldScores
dataclass
¶
The scores of one fold: the aggregate cells, the per-target table and forecast quantiles.
scores has the layout of the study's scores.json. target_scores is participant-level and
must stay where the data are governed.
Validation: VALIDATED.
PooledScores
dataclass
¶
DeviationRecord
dataclass
¶
An explicit, signed record of a change to a frozen specification.
Validation: TESTED.
FrozenSpec
dataclass
¶
A specification hash with the time it was frozen.
Validation: TESTED.
ScoringSpec ¶
Bases: BaseModel
Every choice the scoring makes, fixed before any target is scored.
ScoringSpec.default() reproduces the SYMPHONY v2 code of record: anchor 2.0 years, nine
horizon bins, 30 residuals per bin, windows next, 1y, 2y and all, events of +5 UPDRS-III and
-2 MoCA, B = 1000 bootstrap replicates and no cell from fewer than 10 participants.
Validation: TESTED.
SubgroupCalibration
dataclass
¶
Calibration scores per grouping, level, endpoint and method.
table has one row per cell with the participant and target counts, each metric with its
bootstrap interval, and for the twin the PIT mean, standard deviation and Kolmogorov-Smirnov
p-value. Suppressed cells hold no counts or scores.
Validation: TESTED.
to_markdown ¶
to_markdown(*, metric: str = 'c95') -> str
Return one Markdown table of a metric, with a column per method and the PIT test.
Validation: TESTED.
plot ¶
plot(
*,
metric: str = "c95",
endpoint: str | None = None,
ax: Any = None,
) -> Any
Plot a metric per subgroup with bootstrap intervals; see plots.plot_subgroup_calibration.
Validation: TESTED.
decision_curve ¶
decision_curve(
target_scores: DataFrame,
*,
thresholds: Sequence[float] = DEFAULT_THRESHOLDS,
methods: Sequence[str] = ("twin", "locf", "lmm"),
min_cell: int = 10,
bootstrap_replicates: int = 1000,
seed: int = 20261021,
) -> DecisionCurve
Score net benefit of the event forecasts across threshold probabilities, per endpoint.
target_scores is FoldScores.target_scores or the pooled per-target table. It needs the
columns i, k and ev, and one probability column per method: p_tw, p_lo or p_lm.
Only rows with an observed event and a finite probability for every method are scored, so all
strategies share the same targets. The references "all" and "none" are always included.
Intervals come from a participant-cluster bootstrap. The same resamples serve every strategy
and threshold of an endpoint, so the curves can be compared pointwise. An endpoint is
suppressed when it has fewer than min_cell participants, events or non-events.
Validation: TESTED.
net_benefit ¶
net_benefit(
p: ArrayLike, e: ArrayLike, threshold: float
) -> float
Return the net benefit of flagging targets whose event probability is at least threshold.
Net benefit is TP / n - FP / n * threshold / (1 - threshold), as in Vickers and Elkin (2006).
p holds forecast event probabilities and e the observed events, 0 or 1.
Validation: TESTED.
anchor_draws ¶
anchor_draws(forecast: Any, split: Any) -> AnchorDraws
Return the AnchorDraws of an exact-route forecast and the HoldoutSplit it forecast.
The mean and noise come from the thinned draws that forecast_exact wrote, so they belong
to the same posterior draws as forecast.draws.
Validation: TESTED.
leave_future_out ¶
leave_future_out(
anchors: Mapping[float, AnchorDraws]
| Sequence[tuple[float, AnchorDraws]],
) -> LFOScores
Score exact leave-future-out log predictive density over one or more anchors.
anchors maps each anchor time in years to the AnchorDraws of a fit that saw data up to that
anchor only. Each target scores log mean_s p(y | mu_s, sigma_s), with the model's truncated or
censored density. Each participant's block of targets also scores its joint density, which
keeps the dependence induced by the shared latent path. See Bürkner, Gabry and Vehtari (2020).
Validation: TESTED.
observation_draws ¶
observation_draws(
fitted_params: str | Path | DataFrame, targets: Any
) -> tuple[NDArray[np.float64], NDArray[np.float64]]
Return (draws, targets) arrays of the observation mean and noise sd for each target.
fitted_params is a CmdStan CSV of a pd_v2 fit, such as the thinned file of
forecast_exact, or that file read as a frame. targets is the target data block of a
HoldoutSplit, as StanData or a mapping. The latent path is rebuilt from each draw's s0,
b_raw and eps, as in forecast_gq.stan. The mean therefore equals that program's mu_c,
and the sd is the noise the program draws y_rep_c with.
Validation: TESTED.
predictive_log_density ¶
predictive_log_density(
y: ArrayLike,
mu: ArrayLike,
sigma: ArrayLike,
lower: ArrayLike,
upper: ArrayLike,
censored: ArrayLike,
) -> NDArray[np.float64]
Return the log density of each observation under each draw of its mean and noise.
mu and sigma are (draws, targets). y, lower, upper and censored hold one value
per target, or a scalar for all. The density matches endpoint_log_density in pd_v2's
model.stan. With censored 0 it is a normal renormalised to the bounds. With censored 1 an
interior value keeps the normal density, and a value at a bound gets the mass beyond it.
Validation: TESTED.
fit_generalized_pareto ¶
fit_generalized_pareto(x: ArrayLike) -> tuple[float, float]
Return the shape k and scale sigma of a generalized Pareto fit to non-negative exceedances.
The fit is the empirical Bayes estimate of Zhang and Stephens (2009). The shape is then shrunk
towards 0.5 by a weakly informative prior worth ten observations, as in Vehtari and colleagues
(2024). The result matches gpdfit in the loo R package and ArviZ. A sample whose first
quartile equals its minimum is far from Pareto, and returns nan for both values.
Validation: TESTED.
fit_log_likelihood ¶
fit_log_likelihood(
fitted_params: str | Path | DataFrame, data: Any
) -> tuple[NDArray[np.float64], pd.DataFrame]
Return the (draws, observations) log likelihood of a pd_v2 fit at its own data, and a table.
fitted_params is a CmdStan CSV of the fit, or that file read as a frame. Concatenate the
chains first for a multi-chain fit. data is the StanData or mapping the model was fitted
to. The density is the model's truncated or censored density, as in predictive_log_density.
The table has one row per observation with i (participant), k (endpoint), endpoint and
y. Pass groups=table["i"] to psis_loo for leave-one-participant-out.
Validation: TESTED.
loo_compare ¶
loo_compare(scores: Mapping[str, Any]) -> pd.DataFrame
Rank models by summed pointwise score, with paired differences from the best.
scores takes the same inputs as stacking_weights. The table has one row per model, best
first, with elpd, se, elpd_diff, se_diff and the stacking weight. The difference
standard error uses the paired pointwise differences on the shared units.
Validation: TESTED.
pareto_k_threshold ¶
pareto_k_threshold(n_draws: int) -> float
Return the sample-size dependent threshold above which a Pareto k is unreliable.
The threshold is min(1 - 1 / log10(S), 0.7) for S draws, from Vehtari and colleagues (2024).
Validation: TESTED.
pseudo_bma_weights ¶
pseudo_bma_weights(
scores: Mapping[str, Any],
n_boot: int = 1000,
seed: int = 0,
) -> pd.Series
Return pseudo-BMA+ weights over models, stabilised by the Bayesian bootstrap.
Each bootstrap replicate reweights the shared units by a flat Dirichlet draw and scales the
total to the number of units. The weights are the mean over replicates of the softmax of those
totals. Set n_boot to 0 for plain pseudo-BMA. See Yao and colleagues (2018).
Validation: TESTED.
psis ¶
psis(
log_ratios: ArrayLike, r_eff: ArrayLike = 1.0
) -> PSISResult
Pareto smooth the importance ratios of each column of a (draws, columns) array.
A 1D input is one column. Within a column the largest 3 sqrt(S / r_eff) ratios, or S / 5 when
that is smaller, are replaced by expected order statistics of a generalized Pareto fit. Smoothed
values never exceed the largest raw ratio. r_eff is the relative efficiency of the draws, one
value or one per column. See Vehtari and colleagues (2024).
Validation: TESTED.
psis_loo ¶
psis_loo(
log_lik: ArrayLike,
r_eff: ArrayLike = 1.0,
groups: ArrayLike | None = None,
) -> LOOResult
Estimate leave-one-out expected log predictive density by Pareto smoothed importance sampling.
log_lik is (draws, observations), or (chains, draws, observations) with chains pooled. With
groups, the log likelihoods of each group are summed first, so a whole group is left out at
once. Grouping by participant gives leave-one-participant-out. Each unit's ratios are
1 / p(y_i | theta_s), smoothed by psis. See Vehtari, Gelman and Gabry (2017).
Validation: TESTED.
relative_efficiency ¶
relative_efficiency(
log_lik: ArrayLike,
) -> NDArray[np.float64]
Return the relative efficiency of exp(log_lik) for each observation of (chains, draws, n).
It is the effective sample size of the likelihood values over the total number of draws, as in
relative_eff of the loo R package. The effective sample size uses the multi-chain
autocorrelation estimate and Geyer's initial monotone sequence, as in Stan.
Validation: TESTED.
stacking_weights ¶
stacking_weights(scores: Mapping[str, Any]) -> pd.Series
Return stacking weights over models from their pointwise log predictive densities.
scores maps each model name to a LOOResult, an LFOScores or a 1D array of pointwise log
densities. Units are matched by name, and only shared units count. The weights maximise
sum_i log(sum_k w_k exp(lpd_ik)) over the simplex, following Yao and colleagues (2018).
Validation: TESTED.
auc_with_ties ¶
auc_with_ties(
p: ArrayLike, e: ArrayLike, w: ArrayLike | None = None
) -> float
Return the weighted AUC, Mann-Whitney with ties counted one half.
w holds target weights, one per row; None gives equal weights. Returns NaN when either class
has no weight.
Validation: VALIDATED.
bootstrap_mean ¶
bootstrap_mean(
values: ArrayLike,
cluster: ArrayLike,
W: NDArray[float64],
*,
nan_aware: bool = False,
) -> list[float]
Return the mean of values with a participant-cluster bootstrap percentile interval.
cluster holds each row's cluster position, 0 to n - 1; W comes from
cluster_bootstrap_weights.
Validation: VALIDATED.
bootstrap_ratio_skill ¶
bootstrap_ratio_skill(
numerator: ArrayLike,
denominator: ArrayLike,
cluster: ArrayLike,
W: NDArray[float64],
) -> list[float]
Return a Brier skill 1 - mean(num) / mean(den) with the same participant resampling.
Validation: VALIDATED.
brier ¶
brier(p: ArrayLike, e: ArrayLike) -> float
Return the Brier score, the mean of (p - e) squared.
Validation: VALIDATED.
brier_skill ¶
brier_skill(
brier_model: float, brier_reference: float
) -> float
Return the Brier skill score 1 - Brier_model / Brier_reference.
Validation: VALIDATED.
central_interval ¶
central_interval(
samples: ArrayLike, level: float
) -> tuple[float, float]
Return the central interval of the samples at level, by numpy's default quantiles.
Validation: VALIDATED.
cluster_bootstrap_weights ¶
cluster_bootstrap_weights(
n_clusters: int, B: int = 1000, seed: int = 20261021
) -> NDArray[np.float64]
Return a (B, n_clusters) matrix of resampling counts for a participant-cluster bootstrap.
Validation: VALIDATED.
crps_ensemble ¶
crps_ensemble(samples: ArrayLike, y: float) -> float
Return the CRPS of an ensemble against one observation.
Empirical-distribution estimator, mean|X - y| - 0.5 mean|X - X'| over all pairs including
i = j. Equal to properscoring.crps_ensemble.
Validation: VALIDATED.
event_indicator ¶
event_indicator(
y: float,
last_value: float,
k: int,
thresholds: Mapping[
int, tuple[str, float]
] = EVENT_THRESHOLDS,
) -> float
Return 1.0 when the observed change from last_value meets the event rule of endpoint k.
Validation: VALIDATED.
event_probability ¶
event_probability(
samples: ArrayLike,
last_value: float,
k: int,
thresholds: Mapping[
int, tuple[str, float]
] = EVENT_THRESHOLDS,
) -> float
Return the share of samples, rounded to the integer scale, that meet the event rule.
Validation: VALIDATED.
fit_lmm_em ¶
fit_lmm_em(
groups: Sequence[
tuple[NDArray[float64], NDArray[float64]]
],
max_iter: int = 20000,
tol: float = 1e-12,
) -> LMMFit
Fit y = (b0 + u0) + (b1 + u1) t + e by maximum likelihood with EM.
groups holds one (t, y) pair of arrays per participant. u ~ N(0, G) and e ~ N(0, s2).
Validation: VALIDATED.
interval_coverage ¶
interval_coverage(
samples: ArrayLike, y: float, level: float
) -> float
Return 1.0 when y lies inside the inclusive central interval at level, else 0.0.
Validation: VALIDATED.
lmm_condition ¶
lmm_condition(
fit: LMMFit, t: NDArray[float64], y: NDArray[float64]
) -> tuple[NDArray[np.float64], NDArray[np.float64]]
Condition one participant's random effects on its observations at the fitted parameters.
Returns the posterior mean and covariance of (u0, u1). With no observations, the prior.
Validation: VALIDATED.
mae_median ¶
mae_median(samples: ArrayLike, y: float) -> float
Return the absolute error of the predictive median.
Validation: VALIDATED.
percentile_interval ¶
percentile_interval(
estimate: float,
replicates: ArrayLike,
*,
nan_aware: bool = False,
) -> list[float]
Return [estimate, 2.5% quantile, 97.5% quantile], each rounded to four decimals.
Validation: VALIDATED.
delta_adjustment ¶
delta_adjustment(
observed: DataFrame,
draws: ArrayLike,
imputed: DataFrame,
*,
deltas: Sequence[float]
| Mapping[str, Sequence[float]] = DEFAULT_DELTAS,
time: str = "horizon",
level: float = 0.95,
thresholds: Mapping[
int, tuple[str, float]
] = EVENT_THRESHOLDS,
min_cell: int = 10,
) -> DeltaAdjustment
Recompute cohort summaries with imputed outcomes shifted by each delta in a grid.
observed holds the observed outcomes, with columns i, k, the time column and y. imputed
holds one row per outcome missing after dropout, with columns i, k and the time column.
draws is (draws, imputed rows): forecast draws under missing at random, such as Forecast.draws.
Each cell of endpoint and time pools the observed and imputed rows that share that time.
For a delta d, every imputed draw of endpoint k moves by d times WORSE_DIRECTION[k]. It is then
clipped to the endpoint's scale bounds. deltas is one grid for every endpoint, in points of each
scale, or a mapping from endpoint name to its own grid. An endpoint left out of a mapping gets
delta 0 only. Delta 0 is always added to a grid.
With a column last in both frames, the share meeting the event rule is reported for endpoints in
thresholds. An observed outcome follows event_indicator. An imputed draw is first rounded to
the integer scale, as in event_probability. Intervals are central over draws at level. They
carry imputation uncertainty only. A cell with fewer than min_cell participants is suppressed.
Validation: TESTED.
cjs_distance ¶
cjs_distance(draws: ArrayLike, weights: ArrayLike) -> float
Return the cumulative Jensen-Shannon distance between equally weighted and weighted draws.
The distance compares the empirical CDF of the draws with the weighted empirical CDF of the same draws. It follows Nowozin and colleagues (2017) and is normalised by the summed integrals of the two CDFs, so it lies in 0 to 1. The formula matches priorsense and ArviZ.
Validation: TESTED.
pd_v2_global_columns ¶
pd_v2_global_columns(
data: Any, blocks: Sequence[str] | None = None
) -> list[str]
Return the CmdStan column names of the pd_v2 global parameters in the named prior blocks.
data is the StanData or mapping of the fit, which fixes the number of pathway columns.
blocks defaults to all of PD_V2_PRIOR_BLOCKS.
Validation: TESTED.
pd_v2_log_prior ¶
pd_v2_log_prior(
fitted_params: str | Path | DataFrame,
data: Any,
blocks: Sequence[str] | None = None,
) -> NDArray[np.float64]
Return the log density of the declared pd_v2 priors of the global parameters, per draw.
fitted_params is a CmdStan CSV of a pd_v2 fit, or that file read as a frame. data is the
StanData or mapping it was fitted to, which carries the prior means and scales. The densities
are those of model.stan, normalised, with half-normals for the positive scales. blocks
picks the priors to include and defaults to all of PD_V2_PRIOR_BLOCKS. The latent
terms s0, b_raw and eps are never included.
Validation: TESTED.
pd_v2_powerscale_sensitivity ¶
pd_v2_powerscale_sensitivity(
fitted_params: str | Path | DataFrame,
data: Any,
*,
variables: Sequence[str] | None = None,
prior_blocks: Sequence[str] | None = None,
alphas: tuple[float, float] = (0.99, 1.01),
threshold: float = 0.05,
r_eff: float = 1.0,
) -> PowerScaleSensitivity
Diagnose the prior and likelihood sensitivity of the pd_v2 global parameters.
The log prior comes from pd_v2_log_prior over prior_blocks, and the log likelihood from
fit_log_likelihood summed over observations. variables lists the columns to report and
defaults to every global parameter. Concatenate the chains of a multi-chain fit first.
Validation: TESTED.
powerscale_log_weights ¶
powerscale_log_weights(
log_component: ArrayLike,
alpha: float,
r_eff: float = 1.0,
) -> PSISResult
Return Pareto smoothed log weights that power scale one component of the posterior by alpha.
log_component is the log prior or log likelihood of each draw. A (draws, observations)
array is summed over observations first. The raw log ratios are (alpha - 1) times the
component, and psis smooths them. The result's pareto_k says whether the perturbed
posterior can be trusted. See Kallioinen and colleagues (2024).
Validation: TESTED.
powerscale_moments ¶
powerscale_moments(
draws: Any,
log_component: ArrayLike,
alphas: Sequence[float] = (
0.5,
0.8,
0.9,
1.0,
1.1,
1.25,
2.0,
),
r_eff: float = 1.0,
) -> pd.DataFrame
Return the weighted mean and sd of each variable as one component is power scaled.
The table has one row per alpha and variable, with mean, sd, the Pareto k of the weights and
reliable. It shows the direction and size of a shift that powerscale_sensitivity flags.
Alphas far from one need well behaved weights, which the k column checks.
Validation: TESTED.
powerscale_sensitivity ¶
powerscale_sensitivity(
draws: Any,
log_prior: ArrayLike | None = None,
log_lik: ArrayLike | None = None,
*,
alphas: tuple[float, float] = (0.99, 1.01),
threshold: float = 0.05,
r_eff: float = 1.0,
) -> PowerScaleSensitivity
Diagnose the prior and likelihood sensitivity of each variable by power scaling.
draws is a (draws, variables) frame, a mapping of name to draws, or an array. log_prior and
log_lik give one value per draw, or a (draws, ...) array that is summed per draw. Give the log
prior of only the priors to perturb. Each sensitivity is the mean over the two alphas of the
distance divided by the absolute log2 alpha, as in Kallioinen and colleagues (2024).
Validation: TESTED.
prognostic_scores ¶
prognostic_scores(
data: Forecast | Sequence[Forecast] | TwinDataset,
population: Any = None,
*,
horizon_years: float,
endpoints: Sequence[str] | None = None,
statistic: str = "mean",
baseline_days: int = 0,
standardisation: Standardisation | None = None,
n_particles: int = 1000,
n_samples: int = 1000,
seed: int = 0,
pathway: Sequence[str] = (),
) -> pd.DataFrame
Return one prognostic score per participant and endpoint: the predictive mean or median at a horizon.
data is a Forecast, a list of them, or a TwinDataset. A forecast's targets need participant_id,
horizon and endpoint or k; its horizon must count from baseline. The caller must ensure the
forecast used baseline data only.
For a TwinDataset, every visit after baseline_days is dropped first. A twin is then built per
participant on population (a PopulationDraws, a FitResult, or one parameter dict). It forecasts
horizon_years after day baseline_days. standardisation should be the population fit's; when
None it is fitted on the baseline data alone. So no post-baseline value enters any score.
The table has one row per participant and endpoint, with the score, the predictive SD and the draw count. A score is a prediction under the model, not an outcome.
Validation: TESTED.
prognostic_trial ¶
prognostic_trial(
frame: DataFrame,
*,
effect: float,
outcome: str = "outcome",
adjust: Mapping[str, Sequence[str]] | None = None,
n_replicates: int = 200,
se: str = "model",
level: float = 0.95,
seed: int = 0,
) -> PrognosticTrial
Randomise the participants of frame 1:1, add effect to the treated arm and compare estimators.
frame has one row per participant, with participant_id, the outcome without the effect and
one column per covariate. adjust maps an estimator name to its covariate columns. By default it
adjusts for score and, when present, for baseline. The unadjusted difference in means is always
the reference.
Each estimate is the treatment coefficient of an ordinary least squares fit with an intercept. Its
standard error is model based (se="model") or HC1 (se="hc1"); intervals use the t distribution.
n_replicates further randomisations of the same participants give empirical variances.
Validation: TESTED.
simulate_prognostic_trial ¶
simulate_prognostic_trial(
n_participants: int = 200,
*,
endpoint: str = "updrs3",
horizon_years: float = 2.0,
effect: float = -3.0,
population: Any = None,
theta: Mapping[str, Any] | None = None,
standardisation: Standardisation | None = None,
adjust_baseline: bool = True,
statistic: str = "mean",
n_particles: int = 500,
n_samples: int = 500,
n_replicates: int = 200,
se: str = "model",
level: float = 0.95,
seed: int = 0,
) -> PrognosticTrial
Simulate a two-arm trial from pd_v2 and compare unadjusted and prognostic-score-adjusted estimates.
Each participant is seen at baseline and once more at horizon_years, both visits scoring every
endpoint. Parameters are drawn from the prior unless theta is given. The prognostic score is the
twin's predictive statistic at the horizon from baseline data only. By default the twin runs on the
generating parameters (an oracle population) and the generator's own standardisation. Pass a
population from a fit on other data, with its standardisation, for a realistic score.
Participants are randomised 1:1 and effect is added to the treated arm's outcome at the horizon,
without clipping to the scale, so the simulated effect is known exactly. The estimators are the
difference in means, ANCOVA on the score and, if adjust_baseline, ANCOVA on the baseline value.
Validation: TESTED.
recalibrate_quantiles ¶
recalibrate_quantiles(
draws: ArrayLike,
targets: DataFrame,
*,
calibration_fraction: float = 0.5,
calibration_ids: Sequence[Any] | None = None,
levels: Sequence[float] = (0.5, 0.8, 0.95),
smoothing: str = "kernel",
pool_endpoints: bool = False,
horizon_edges: Sequence[float] | None = None,
horizon_column: str = "horizon",
grid_size: int = 201,
min_cell: int = 10,
bootstrap_replicates: int = 1000,
seed: int = DEFAULT_SEED,
) -> RecalibrationResult
Fit quantile recalibration maps on one part of a cohort and score them on the other part.
draws is (draws, targets) on the bounded scale of each endpoint, as Forecast.draws. targets
has one row per target with the participant i, the endpoint index k and the observed value y.
Participants are split by split_participants, or calibration_ids names the calibration subset.
One map is fitted per endpoint. pool_endpoints fits one map for all endpoints, and horizon_edges
fits one per horizon window, closed below. A map needs min_cell calibration participants.
grid_size sets the number of nominal levels the map is stored at. Coverage at each of levels
and CRPS are scored on the evaluation subset, before and after, with a participant-cluster bootstrap.
Validation: TESTED.
split_participants ¶
split_participants(
participants: ArrayLike,
*,
calibration_fraction: float = 0.5,
seed: int = DEFAULT_SEED,
) -> tuple[NDArray[Any], NDArray[Any]]
Split participant identifiers into a calibration subset and an evaluation subset.
Duplicates are dropped first, so a per-target column can be passed. The split is a seeded random permutation. Each subset holds at least one participant. Returns both subsets, each sorted.
Validation: TESTED.
obs_table ¶
obs_table(d: Mapping[str, Any]) -> pd.DataFrame
Return one row per observation of a Stan data block: participant, endpoint, time, value.
Validation: VALIDATED.
pool_folds ¶
pool_folds(
folds: Sequence[
tuple[DataFrame | None, Mapping[str, Any] | None]
],
*,
spec: ScoringSpec,
frozen: FrozenSpec | None,
deviation: DeviationRecord | None = None,
) -> PooledScores
Pool fold scores: primary cells, per-fold spread, events, strata and the O-20 decomposition.
folds holds, in fold order, (target_scores, fit_record) per fold. A fold enters only when
its fit record says converged. Every participant may be a test participant in one fold only.
No stratum or event cell is reported from fewer than spec.min_cell_participants people.
Validation: VALIDATED.
score_fold ¶
score_fold(
fit_data: Mapping[str, Any],
target_data: Mapping[str, Any],
targets_meta: DataFrame,
twin_draws: ArrayLike,
test_index: set[int] | Sequence[int],
*,
spec: ScoringSpec,
frozen: FrozenSpec | None,
deviation: DeviationRecord | None = None,
age: ArrayLike | None = None,
fold: int = 1,
) -> FoldScores
Score one held-out fold: twin draws against LOCF and the LMM, as the code of record does.
twin_draws is (draws, targets), the y_rep_c draws in target order. targets_meta has
columns i, k, t, horizon, y, cohort and sex. test_index holds the zero-based indices of test
participants. frozen must be the freeze of spec; see freeze_spec.
Validation: VALIDATED.
freeze_spec ¶
freeze_spec(
spec: ScoringSpec, path: str | Path | None = None
) -> FrozenSpec
Freeze a specification: hash it and, when path is given, write spec and hash to disk.
The file holds the canonical specification and its sha256, so a reader can check the freeze without the package.
Validation: TESTED.
load_frozen_spec ¶
load_frozen_spec(
path: str | Path,
) -> tuple[ScoringSpec, FrozenSpec]
Read a frozen specification file and check its hash.
Validation: TESTED.
require_frozen ¶
require_frozen(
spec: ScoringSpec,
frozen: FrozenSpec | None,
deviation: DeviationRecord | None = None,
) -> dict[str, Any]
Check spec against its freeze and return the record that travels with the scores.
Raises UnfrozenSpecificationError when frozen is None, or when the hashes differ and no
deviation record is given.
Validation: TESTED.
age_band ¶
age_band(
age: ArrayLike,
edges: Sequence[float] = (55.0, 65.0, 75.0),
) -> NDArray[np.str_]
Label each age with its band, such as "55 to 64", for use as a grouping.
Bands are closed below and open above. A missing age is labelled "unknown".
Validation: TESTED.
subgroup_calibration ¶
subgroup_calibration(
target_scores: DataFrame,
groups: Mapping[
str, str | Mapping[Any, Any] | ArrayLike
],
*,
twin_draws: ArrayLike | None = None,
pit: ArrayLike | None = None,
methods: Sequence[str] = ("twin", "locf", "lmm"),
min_cell: int = 10,
multiplicity: str = "bh",
bootstrap_replicates: int = 1000,
seed: int = 20261021,
pit_seed: int = 0,
) -> SubgroupCalibration
Score interval coverage, CRPS and PIT uniformity within each level of each grouping.
target_scores is FoldScores.target_scores or the pooled per-target table, one row per
target. Each entry of groups names a grouping and gives its labels in one of three ways:
a column of target_scores, such as "sex" or "cohort"; a mapping from participant index i to
a label, for site or genotype group; or an array with one label per row, for example from
age_band(target_scores["age"]). An overall row with grouping "all" is always included.
PIT values come from pit, one per row, or from twin_draws, shaped (draws, rows) in row
order, as passed to score_fold. Rows score their own target, so PITs of one participant are
correlated and the Kolmogorov-Smirnov p-values are approximate. multiplicity adjusts them
across all cells by "bh" (Benjamini-Hochberg), "bonferroni" or "none".
Cells with fewer than min_cell participants are suppressed: no counts and no scores.
Validation: TESTED.