symphony_dt.twin¶
symphony_dt.twin ¶
Living digital twins: sequential updating, calibration monitoring, recalibration and relearning.
Everything in this package is EXPERIMENTAL. Forecasts are associational; nothing here recommends a treatment.
ParticipantTwin ¶
A self-updating twin of one participant over a fixed set of population draws.
Build it with ParticipantTwin.create(population, history, standardisation=...); the history is replayed
visit by visit through observe, so creation and updating share one code path and one audit log.
Validation: EXPERIMENTAL.
create
classmethod
¶
create(
population: PopulationDraws | Any,
history: TwinDataset,
*,
standardisation: Standardisation | None = None,
config: ModelConfig | None = None,
n_particles: int = 1000,
seed: int = 0,
monitor: CalibrationMonitor | None = None,
conformal: AdaptiveConformal | None = None,
pathway: Sequence[str] = (),
) -> ParticipantTwin
Create a twin for the single participant in history and replay their visits.
population is a PopulationDraws or a FitResult. standardisation must be the population fit's.
Validation: EXPERIMENTAL.
observe ¶
observe(
visit: Visit | Mapping[str, Any],
*,
monitor_outcomes: bool = True,
) -> dict[str, Any]
Absorb one visit and return its audit entry.
With monitor_outcomes, the one-step-ahead PIT of each score is computed before the update and passed to
the attached monitor and conformal layer.
Validation: EXPERIMENTAL.
forecast ¶
forecast(
horizons_years: Sequence[float],
*,
n_samples: int = 1000,
seed: int = 1,
ledd_std: float | None = None,
) -> Forecast
Forecast every endpoint at each horizon (years after the latest visit).
The forecast's metadata carries the uncertainty decomposition per target.
Validation: EXPERIMENTAL.
milestone_curve ¶
milestone_curve(
endpoint: str,
threshold: float,
*,
years: float = 5.0,
step_years: float = 0.25,
seed: int = 2,
) -> pd.DataFrame
Probability that the expected score of endpoint has crossed threshold by each time.
For MoCA, crossing means falling to or below the threshold; for the others, rising to or above it.
Validation: EXPERIMENTAL.
next_visit ¶
next_visit(
candidates_years: Sequence[float],
*,
target_years: float = 2.0,
endpoint: str = "updrs3",
n_outcomes: int = 32,
seed: int = 3,
) -> pd.DataFrame
Rank candidate visit times by expected reduction in forecast variance at target_years.
For each candidate, outcomes are simulated from the twin's predictive distribution, the cloud is reweighted by each, and the posterior variance of the expected score at the target is averaged. The result reports prior and expected posterior variance, their ratio, and a Gaussian information gain.
Validation: EXPERIMENTAL.
plan_visits ¶
plan_visits(
candidates_years: Sequence[float],
*,
target_years: float = 2.0,
endpoints: Sequence[str] | None = None,
weights: Mapping[str, float] | None = None,
visit_cost: VisitCost = 1.0,
assessment_cost: Mapping[str, float] | None = None,
assess: Sequence[str] | None = None,
subsets: bool = False,
n_outcomes: int = 32,
seed: int = 3,
) -> VisitPlan
Rank candidate visits over several endpoints by expected variance reduction per unit cost.
See symphony_dt.twin.schedule.plan_visits for the arguments and the method.
Validation: EXPERIMENTAL.
status ¶
status() -> dict[str, Any]
Return the twin's state in brief: visits, time, effective sample sizes and monitors.
Validation: EXPERIMENTAL.
save ¶
save(path: str | Path) -> Path
Save the twin: arrays to .npz and the audit, history and settings to a sidecar .json.
Validation: EXPERIMENTAL.
load
classmethod
¶
load(path: str | Path) -> ParticipantTwin
Load a twin saved by save.
Validation: EXPERIMENTAL.
PopulationDraws
dataclass
¶
K draws of the pd_v2 global parameters, stacked as arrays for vectorised updates.
Validation: EXPERIMENTAL.
from_thetas
classmethod
¶
from_thetas(
thetas: Sequence[Mapping[str, Any]], source: str = ""
) -> PopulationDraws
Stack parameter dicts, as returned by global_draws_from_csv or draw_prior.
Validation: EXPERIMENTAL.
from_fit
classmethod
¶
from_fit(
fit: Any, *, n_draws: int = 200, n_pathway: int = 0
) -> PopulationDraws
Read evenly spaced draws from a FitResult or a list of chain CSV files.
Validation: EXPERIMENTAL.
to_arrays ¶
to_arrays() -> dict[str, Array]
Return every array by name, for saving.
Validation: EXPERIMENTAL.
Visit
dataclass
¶
One visit: whole days since baseline, the scores measured and the standardised LEDD.
Validation: EXPERIMENTAL.
AdaptiveConformal
dataclass
¶
Adaptive conformal inference on the twin's central intervals, one level per endpoint.
After each outcome, alpha_t moves by gamma * (target - miss): a miss lowers alpha (wider intervals) and
a hit raises it. Over time the miss rate approaches the target whatever the data do.
Validation: EXPERIMENTAL.
alpha ¶
alpha(endpoint: str) -> float
Return the current miscoverage level for an endpoint, clipped to [0.001, 0.999].
Validation: EXPERIMENTAL.
interval ¶
interval(
samples: ndarray, endpoint: str
) -> tuple[float, float]
Return the central interval of samples at the endpoint's current level.
Validation: EXPERIMENTAL.
update ¶
update(samples: ndarray, y: float, endpoint: str) -> bool
Score one outcome against the current interval, move the level, and return whether it was covered.
Validation: EXPERIMENTAL.
state ¶
state() -> dict[str, Any]
Return the current levels and the realised miss rates.
Validation: EXPERIMENTAL.
CalibrationMonitor
dataclass
¶
An anytime-valid e-process monitor of PIT uniformity, overall and per endpoint.
update(pit, endpoint) adds one PIT. evidence is the current e-value of the mixture; alarm is true once
it has reached 1/alpha. Each stream starts at e = 1. The mixture weights are uniform over eight bias and
dispersion alternatives, fixed before any data, which keeps the mixture a test martingale.
Validation: EXPERIMENTAL.
update ¶
update(pit: float, endpoint: str | None = None) -> float
Add one PIT value to the overall stream and to its endpoint stream; return the overall e-value.
Validation: EXPERIMENTAL.
evidence ¶
evidence(stream: str = 'all') -> float
Return the e-value of a stream: the average wealth over the alternatives.
Validation: EXPERIMENTAL.
alarm ¶
alarm(stream: str = 'all') -> bool
True once the stream's e-value has reached 1/alpha at any time.
Validation: EXPERIMENTAL.
state ¶
state() -> dict[str, Any]
Return a JSON-serialisable summary of every stream.
Validation: EXPERIMENTAL.
reset ¶
reset(stream: str | None = None) -> None
Restart one stream, or all streams, at e = 1, for example after relearning.
Validation: EXPERIMENTAL.
RelearnDecision
dataclass
¶
Whether to refit the population model, and why.
Validation: EXPERIMENTAL.
RelearnPolicy
dataclass
¶
Refit when the calibration monitor alarms, or when max_new_outcomes outcomes have arrived since the fit.
The monitor's alarm carries anytime-valid error control: a calibrated twin triggers it with probability at most alpha over its whole life. The count rule refreshes the population as data accumulate, with no claim of miscalibration.
Validation: EXPERIMENTAL.
decide ¶
decide(
monitor: CalibrationMonitor, new_outcomes: int
) -> RelearnDecision
Return the decision for the current monitor state and count of new outcomes.
Validation: EXPERIMENTAL.
TwinRegistry
dataclass
¶
Many participant twins over one population, with pooled monitoring and versioned relearning.
Validation: EXPERIMENTAL.
enrol ¶
enrol(
history: TwinDataset, *, seed: int = 0
) -> ParticipantTwin
Create and register a twin from one participant's history.
Validation: EXPERIMENTAL.
enrol_all ¶
enrol_all(dataset: TwinDataset, *, seed: int = 0) -> int
Enrol every participant of a dataset; return how many were enrolled.
Validation: EXPERIMENTAL.
ingest ¶
ingest(
participant_id: str, visit: Visit | Mapping[str, Any]
) -> dict[str, Any]
Score a new visit against the twin's forecast, update the twin, and return the audit entry.
Validation: EXPERIMENTAL.
decide ¶
decide() -> RelearnDecision
Ask the relearning policy whether to refit now.
Validation: EXPERIMENTAL.
relearn ¶
relearn(
fit_function: Callable[[TwinDataset], PopulationDraws],
data: TwinDataset,
*,
reason: str = "",
) -> int
Refit the population on data, rebuild every twin on the new draws, and return the new version.
fit_function maps a dataset to new population draws, for example by running symphony_dt.fit.fit
and PopulationDraws.from_fit. Every twin replays its own history on the new population.
Validation: EXPERIMENTAL.
status ¶
status() -> pd.DataFrame
Return one row per twin with its visits, time and effective sample sizes.
Validation: EXPERIMENTAL.
VisitPlan
dataclass
¶
Candidate visits ranked by expected reduction in forecast variance per unit cost.
table has one row per candidate time and set of assessed endpoints. It holds the variance reduction of each
target endpoint (reduction_<endpoint>), the weighted value, the visit, assessment and total cost, the value
per cost and the rank, best first. endpoint_table has one row per option and target endpoint, with the prior
and expected posterior variance, the reduction, the weight and a Gaussian information gain.
Validation: EXPERIMENTAL.
plan_visits ¶
plan_visits(
twin: ParticipantTwin,
candidates_years: Sequence[float],
*,
target_years: float = 2.0,
endpoints: Sequence[str] | None = None,
weights: Mapping[str, float] | None = None,
visit_cost: VisitCost = 1.0,
assessment_cost: Mapping[str, float] | None = None,
assess: Sequence[str] | None = None,
subsets: bool = False,
n_outcomes: int = 32,
seed: int = 3,
) -> VisitPlan
Rank candidate visits by expected reduction in forecast variance per unit cost.
endpoints are the targets whose expected score at target_years the visit should inform; by default all
three. weights maps a target to its weight, absent targets get zero, and weights are normalised to sum to
one. assess lists the endpoints measured at the visit; by default all three, and an empty list gives zero
value. visit_cost is a number, a function of the candidate time in years, or a mapping from candidate time to
cost. assessment_cost adds a burden per assessed endpoint. With subsets, every non-empty subset of assess
is scored as its own option. Candidates outside (0, target_years) are dropped, as in next_visit.
With one candidate, one target, one assessed endpoint, unit cost and the same seed, the value equals the
variance_reduction of next_visit. With several candidates the cloud follows one shared path, so a
candidate's value agrees with next_visit in distribution rather than draw by draw.
Validation: EXPERIMENTAL.