symphony_dt.data¶
symphony_dt.data ¶
Data layer: the canonical dataset, instruments, envelope, harmonisation, Stan data and simulation.
TwinDataset ¶
A longitudinal cohort in the canonical long format.
participants needs participant_id and cohort; age_baseline_years, sex and other
covariates are optional. observations needs participant_id, time_days, endpoint and
value. visits lists every visit time, including visits without a score, and may carry
exposures such as ledd. markers holds one value per participant and marker name.
If visits is omitted, the visit times are the distinct observation times.
Validation: TESTED.
participant_ids
property
¶
participant_ids: list[str]
Participant identifiers in sorted order, the order every builder uses.
validate ¶
validate() -> TwinDataset
Check every rule in VALIDATION_RULES and return self, or raise DataValidationError.
Validation: TESTED.
visit_table ¶
visit_table() -> pd.DataFrame
Return one row per participant and visit time, sorted, with any visit-level exposures.
Visits given in visits are kept; observation times not in visits are added.
Validation: TESTED.
wide_observations ¶
wide_observations() -> pd.DataFrame
Return the visit table with one column per endpoint, missing where not scored.
Validation: TESTED.
marker_matrix ¶
marker_matrix(names: Iterable[str]) -> pd.DataFrame
Return markers as a participant by name frame, missing where absent.
Validation: TESTED.
subset ¶
subset(participant_ids: Iterable[str]) -> TwinDataset
Return a new dataset holding only the named participants.
Validation: TESTED.
summary ¶
summary(*, min_cell: int = 10) -> dict[str, Any]
Return aggregate counts only, suppressing any count below min_cell participants.
Validation: TESTED.
fingerprint ¶
fingerprint() -> str
Return the sha256 of a canonical serialisation of the dataset. The data never leaves.
Frames are sorted and written as CSV with fixed float formatting, so the digest depends on the content and not on row order or dtype detail.
Validation: TESTED.
DiscreteCohort
dataclass
¶
A cohort simulated from pd_bb: the data block, the true parameters and the latents.
Validation: EXPERIMENTAL.
truth ¶
truth() -> dict[str, float]
Return the true global parameters as named scalars.
Validation: EXPERIMENTAL.
AgeRange
dataclass
¶
Bases: EligibilityRule
Baseline age within [low, high] years, ends included. Missing age fails.
Validation: TESTED.
CohortIn
dataclass
¶
CustomRule
dataclass
¶
Bases: EligibilityRule
A user rule: a function from the dataset to a boolean Series by participant_id.
Validation: TESTED.
EligibilityCriteria
dataclass
¶
An ordered list of rules.
Validation: TESTED.
from_list
classmethod
¶
from_list(
specs: Iterable[Mapping[str, Any] | EligibilityRule],
) -> EligibilityCriteria
Build criteria from rule objects or study-file dicts.
Validation: TESTED.
pd_v2_default
classmethod
¶
pd_v2_default() -> EligibilityCriteria
A sensible default for pd_v2: PD or prodromal, age 30 to 95, a baseline score of every endpoint.
These are design defaults, not the study's eligibility ledger.
Validation: TESTED.
EligibilityResult
dataclass
¶
The outcome of apply_eligibility.
decisions is participant-level (one column per rule) and must stay where the data are governed.
attrition is aggregate.
Validation: TESTED.
excluded_ids ¶
excluded_ids() -> list[str]
Return identifiers of excluded participants, for local use only.
Validation: TESTED.
attrition_table ¶
attrition_table(*, min_cell: int = 10) -> pd.DataFrame
Return the attrition table with counts below min_cell shown as <min_cell.
Validation: TESTED.
to_markdown ¶
to_markdown(*, min_cell: int = 10) -> str
Return the attrition table as Markdown.
Validation: TESTED.
EligibilityRule
dataclass
¶
Base class: a named rule that returns one boolean per participant.
Validation: TESTED.
MaxGap
dataclass
¶
Bases: EligibilityRule
No interval between consecutive visits longer than years.
Validation: TESTED.
MinEndpointObservations
dataclass
¶
MinFollowUp
dataclass
¶
MinVisits
dataclass
¶
Bases: EligibilityRule
At least n distinct visit times. With endpoint, only visits that score it count.
Validation: TESTED.
RequiredAtBaseline
dataclass
¶
Bases: EligibilityRule
Every listed endpoint scored at the baseline visit (day 0).
Validation: TESTED.
EnvelopeReport
dataclass
¶
The result of check_envelope.
Validation: TESTED.
EnvelopeWarning
dataclass
¶
One out-of-envelope finding with its code, a message and the share of data affected.
Validation: TESTED.
Crosswalk
dataclass
¶
A cited conversion of one instrument from a source version to a target version.
convert maps an array of source scores to target scores. citation must name the published
source of the conversion; an empty citation raises ValueError.
Validation: EXPERIMENTAL.
UnitConverter
dataclass
¶
A unit conversion for a visit-level exposure column, for example a dose in other units.
Validation: TESTED.
Instrument ¶
Bases: BaseModel
One clinical instrument.
worsening says whether higher scores mean worse disease (increase) or better (decrease).
boundary says how the model treats values at the scale ends: truncated or censored.
Validation: TESTED.
contains ¶
contains(value: float) -> bool
Return True when value lies inside the scale range, ends included.
Validation: TESTED.
InstrumentRegistry ¶
A name-keyed collection of instruments.
Validation: TESTED.
add ¶
add(instrument: Instrument) -> None
Register an instrument. A second instrument with the same name raises ValueError.
Validation: TESTED.
get ¶
get(name: str) -> Instrument
Return the instrument called name, or raise KeyError naming the known instruments.
Validation: TESTED.
names ¶
names() -> tuple[str, ...]
Return the registered names in insertion order.
Validation: TESTED.
DataProfile
dataclass
¶
CovariateShiftReport
dataclass
¶
The result of covariate_shift: differences, envelope findings, support overlap and classifier AUC.
Validation: TESTED.
DomainClassifierResult
dataclass
¶
The cross-fitted domain classifier: AUC, its interval and the standardised coefficients.
coefficients come from one fit on all participants, on standardised features. They show which features
separate the cohorts most, and carry no causal meaning.
Validation: TESTED.
SimulatedCohort
dataclass
¶
A simulated cohort: the dataset, the generating Stan data, the true parameters and latents.
Validation: TESTED.
truth ¶
truth() -> dict[str, float]
Return the true global parameters as named scalars.
Validation: TESTED.
VisitPattern ¶
Bases: TypedDict
The shape of one participant record: interval lengths and the endpoint mask.
Validation: TESTED.
Standardisation
dataclass
¶
Training-only centring and scaling constants, with a digest of the training participants.
stats maps a name to (mean, sd). Build it with Standardisation.fit on the training
participants only, so no held-out row enters a constant.
Validation: TESTED.
fit
classmethod
¶
fit(
dataset: TwinDataset,
train_ids: Iterable[str] | None = None,
*,
pathway: Sequence[str] = (),
) -> Standardisation
Compute constants on the training participants (all participants when train_ids is None).
Age: mean and sd over training participants. LEDD: mean and sd over every visit of a training participant, zero dose where missing. Each pathway marker: mean and sd over training participants who have it. Standard deviations use ddof = 1.
Validation: TESTED.
from_table
classmethod
¶
from_table(table: DataFrame) -> Standardisation
Build from a frame with columns name, mean and sd.
Validation: TESTED.
get ¶
get(name: str) -> tuple[float, float]
Return (mean, sd) for name, or raise KeyError naming the known constants.
Validation: TESTED.
StanData
dataclass
¶
The pd_v2 data block with its audit and the participant order behind it.
Validation: TESTED.
serialise ¶
serialise() -> bytes
Return the canonical JSON bytes: sorted keys, compact separators, one trailing newline.
Validation: TESTED.
to_json ¶
to_json(path: str | Path) -> Path
Write the canonical JSON to path and return the path.
Validation: TESTED.
from_json
classmethod
¶
from_json(path: str | Path) -> StanData
Read a data block written by to_json or by CmdStan tooling.
Validation: TESTED.
node_times ¶
node_times(i: int) -> NDArray[np.float64]
Return node times in years for participant index i (zero-based).
Validation: TESTED.
participant_sort_key ¶
participant_sort_key(ids: Iterable[str]) -> list[str]
Sort identifiers numerically when all are whole numbers, otherwise lexically.
The study sorted on a numeric identifier. Sorting numeric strings as numbers keeps that order.
Validation: TESTED.
beta_binomial_moments ¶
beta_binomial_moments(
p: ArrayLike, phi: ArrayLike, n: ArrayLike
) -> tuple[NDArray[Any], NDArray[Any]]
Return the mean and variance of a beta-binomial count with mean share p and precision phi.
The shapes are alpha = p phi and beta = (1 - p) phi. The mean is n p and the variance is n p (1 - p) (phi + n) / (phi + 1). As phi grows the variance tends to the binomial one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
p
|
ArrayLike
|
Mean share of the maximum score, in 0 to 1. |
required |
phi
|
ArrayLike
|
Precision, positive. |
required |
n
|
ArrayLike
|
Number of trials, the scale width U - L. |
required |
Returns:
| Type | Description |
|---|---|
tuple[NDArray[Any], NDArray[Any]]
|
The mean and the variance of the count above the floor. |
Validation: TESTED.
discrete_stan_data ¶
discrete_stan_data(
stan_data: StanData,
*,
practice_tau_years: float = PRACTICE_TAU_YEARS,
round_scores: bool = False,
prior: Mapping[str, float] | None = None,
) -> StanData
Convert a pd_v2 data block into a pd_bb data block.
Scores must be whole numbers inside their scale bounds. A non-integer score raises unless
round_scores is set, which rounds to the nearest integer and records how many moved. The
pd_v2 switches for truncation, censoring and state-dependent noise are dropped. They have no
meaning under a discrete likelihood. The LEDD switch is kept.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stan_data
|
StanData
|
A block from |
required |
practice_tau_years
|
float
|
Decay time of the MoCA practice term. |
PRACTICE_TAU_YEARS
|
round_scores
|
bool
|
Round non-integer scores instead of raising. |
False
|
prior
|
Mapping[str, float] | None
|
Overrides for |
None
|
Returns:
| Type | Description |
|---|---|
StanData
|
The pd_bb data block, with an audit of the conversion. |
Validation: EXPERIMENTAL.
draw_discrete_prior ¶
draw_discrete_prior(
rng: Generator,
n_pathway: int = 0,
hyper: Mapping[str, Any] | None = None,
prior: Mapping[str, float] | None = None,
) -> dict[str, Any]
Draw the pd_bb global parameters from its prior.
The dynamic parameters follow the pd_v2 prior through draw_prior. The Gaussian noise
parameters are replaced by a log-normal precision per endpoint and a normal practice gain.
Validation: EXPERIMENTAL.
practice_weights ¶
practice_weights(
data: Mapping[str, Any],
*,
tau_years: float = PRACTICE_TAU_YEARS,
endpoint: str = PRACTICE_ENDPOINT,
) -> NDArray[np.float64]
Return the transient practice weight of every observation in a Stan data block.
The weight is zero for any other endpoint and for a participant's first score on endpoint.
A later score gets exp(-gap / tau), where gap is the time in years since the previous score.
So the gain is largest soon after a test and fades as the interval grows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Mapping[str, Any]
|
A pd_v2 or pd_bb data block, with |
required |
tau_years
|
float
|
Decay time in years, positive. |
PRACTICE_TAU_YEARS
|
endpoint
|
str
|
Endpoint that carries the term. |
PRACTICE_ENDPOINT
|
Returns:
| Type | Description |
|---|---|
NDArray[float64]
|
One weight per observation, in 0 to 1. |
Validation: TESTED.
simulate_discrete_cohort ¶
simulate_discrete_cohort(
n_participants: int,
*,
seed: int = C.MASTER_SEED,
theta: Mapping[str, Any] | None = None,
patterns: Sequence[VisitPattern] | None = None,
ledd_in_mu_U: int = 1,
practice_tau_years: float = PRACTICE_TAU_YEARS,
n_pathway: int = 0,
prior: Mapping[str, float] | None = None,
) -> DiscreteCohort
Simulate a synthetic cohort from pd_bb, drawing the parameters from its prior unless given.
Validation: EXPERIMENTAL.
simulate_discrete_replicate ¶
simulate_discrete_replicate(
patterns: Sequence[VisitPattern],
n: int,
theta: Mapping[str, Any],
rng: Generator,
*,
ledd_in_mu_U: int = 1,
practice_tau_years: float = PRACTICE_TAU_YEARS,
h_max: float = C.H_MAX_YEARS,
grainsize: int = 1,
prior: Mapping[str, float] | None = None,
latents: dict[str, Any] | None = None,
) -> dict[str, Any]
Simulate one replicate from pd_bb and return it as a pd_bb data block.
The latent paths follow the pd_v2 process on the same sub-step grid. Each scored endpoint is
drawn as L plus a beta-binomial count on U - L trials. latents, when given, is filled with the
true s0, b_raw and eps on the Stan indexing.
Validation: EXPERIMENTAL.
apply_eligibility ¶
apply_eligibility(
dataset: TwinDataset,
criteria: EligibilityCriteria
| Sequence[EligibilityRule | Mapping[str, Any]],
) -> EligibilityResult
Apply rules in sequence and return the eligible dataset, decisions and attrition.
Validation: TESTED.
rule_from_dict ¶
rule_from_dict(spec: Mapping[str, Any]) -> EligibilityRule
Build a rule from a dict such as {"rule": "min_visits", "n": 3}, as written in a study file.
Validation: TESTED.
check_envelope ¶
check_envelope(
dataset: TwinDataset,
model: str = "pd_v2",
limits: dict[str, Any] | None = None,
) -> EnvelopeReport
Check that dataset lies inside the design envelope of model.
limits overrides entries of PD_V2_ENVELOPE for a stricter or looser check.
Validation: TESTED.
convert_units ¶
convert_units(
dataset: TwinDataset,
converters: Iterable[UnitConverter],
) -> TwinDataset
Multiply visit-level columns by their conversion factors and record the conversion.
Validation: TESTED.
default_registry ¶
default_registry() -> InstrumentRegistry
Return the three instruments of the pd_v2 model with their published scale ranges.
MDS-UPDRS Part III runs 0 to 132 and worsens upwards. MoCA runs 0 to 30 and worsens downwards. SCOPA-AUT is prorated to the 23-item scale, 0 to 69, and worsens upwards. Boundary handling follows the pd_v2 primary arm: MoCA censored, the other two truncated.
Validation: TESTED.
covariate_shift ¶
covariate_shift(
development: TwinDataset,
external: TwinDataset,
*,
covariates: Sequence[str] | None = None,
baseline_window_days: int = 180,
threshold: float = 0.1,
coverage: float = 0.95,
folds: int = 5,
penalty: float = 1.0,
bootstrap_replicates: int = 1000,
min_cell: int = 10,
model: str = "pd_v2",
seed: int = C.MASTER_SEED,
) -> CovariateShiftReport
Compare an external cohort with the development cohort and report the shift in aggregates only.
Features come from participant_features on each dataset. The report holds standardised differences, the
envelope codes of check_envelope for each cohort, the external share inside the central coverage range of
each continuous development feature, and the domain classifier AUC of domain_classifier_auc. Each cohort
needs at least min_cell participants. The diagnostics describe association between cohort and features;
they do not say whether a forecast will transfer.
Validation: TESTED.
domain_classifier_auc ¶
domain_classifier_auc(
development: DataFrame,
external: DataFrame,
*,
folds: int = 5,
penalty: float = 1.0,
bootstrap_replicates: int = 1000,
seed: int = C.MASTER_SEED,
) -> DomainClassifierResult
Estimate how well a classifier tells external from development participants, as a cross-fitted AUC.
The two feature tables are stacked, missing values imputed at the pooled mean with a missing indicator, and
columns standardised. A ridge logistic regression is fitted on all but one of folds stratified folds and
scores the held-out fold. The AUC of the out-of-fold scores is near 0.5 when the classifier finds no shift
and near 1 when the cohorts separate. The interval is a stratified participant bootstrap of the out-of-fold
scores; it holds the fitted folds fixed, so it is somewhat too narrow.
Validation: TESTED.
participant_features ¶
participant_features(
dataset: TwinDataset,
*,
covariates: Sequence[str] | None = None,
baseline_window_days: int = 180,
) -> pd.DataFrame
Return one row per participant of baseline covariates, baseline scores and follow-up features.
Numeric columns of participants are kept as they are. Text columns, such as cohort, become one indicator
per level, named column=level. covariates restricts the participant columns used. Each endpoint gives a
baseline_<endpoint> column, its first score within baseline_window_days of the first visit. A ledd
column in visits gives baseline_ledd. Every participant also gets n_visits, follow_up_years and
median_interval_years. Missing values stay missing.
Validation: TESTED.
standardised_differences ¶
standardised_differences(
development: DataFrame,
external: DataFrame,
*,
threshold: float = 0.1,
min_cell: int = 10,
) -> pd.DataFrame
Return the standardised mean difference and variance ratio of each shared feature column.
The difference is the external mean less the development mean, over the root mean of the two sample
variances (Austin, 2009). Indicator columns use the same formula, which then compares proportions. flag
marks differences beyond threshold in absolute value; 0.1 is a common convention, not a test. A feature
with fewer than min_cell observed values in either cohort is suppressed.
Validation: TESTED.
coupling_matrix ¶
coupling_matrix(
theta: Mapping[str, Any],
) -> NDArray[np.float64]
Return the sparse 3 x 3 coupling matrix: six free entries, three structural zeros.
Validation: VALIDATED.
draw_prior ¶
draw_prior(
rng: Generator,
n_pathway: int,
hyper: Mapping[str, Any] | None = None,
) -> dict[str, Any]
Draw the global parameters from the pd_v2 prior.
Half-normals are drawn as the absolute value of a normal, which is what the lower-bound constraint plus a normal statement means in the Stan program.
Validation: VALIDATED.
flatten_theta ¶
flatten_theta(theta: Mapping[str, Any]) -> dict[str, float]
Return the global parameters as named scalars, the granularity SBC ranks and gates check.
Names follow Stan's convention: mu_r[1], Gamma[2,3].
Validation: VALIDATED.
initial_values ¶
initial_values(
theta_like: Mapping[str, Any],
rng: Generator,
n: int = 0,
n_steps: int = 0,
jitter: float = 0.1,
) -> dict[str, Any]
Return inits at the prior location with per-chain jitter, not Stan's uniform(-2, 2) box.
The default box puts the boundary densities at minus infinity. Starting at the prior mean, jittered per chain, keeps the chains distinct so R-hat stays meaningful.
Validation: VALIDATED.
simulate_cohort ¶
simulate_cohort(
n_participants: int,
*,
seed: int = C.MASTER_SEED,
config: ModelConfig | None = None,
patterns: Sequence[VisitPattern] | None = None,
theta: Mapping[str, Any] | None = None,
n_pathway: int = 0,
cohort_share_pd: float = 0.4,
) -> SimulatedCohort
Simulate a synthetic cohort from the pd_v2 generative model.
Draws the global parameters from the prior unless theta is given, then simulates every
participant on patterns (synthetic ones by default). The returned dataset carries age as
65 + 10 x the simulated centred age in decades, and LEDD as 300 + 200 x the simulated
standardised level, so a rebuilt data block sits close to the generating one.
Validation: TESTED.
simulate_replicate ¶
simulate_replicate(
patterns: Sequence[VisitPattern],
n: int,
theta: Mapping[str, Any],
rng: Generator,
*,
censored: Sequence[int],
state_dependent_sigma: int,
ledd_in_mu_U: int,
sigma_xbar: Sequence[float] | None,
h_max: float = C.H_MAX_YEARS,
grainsize: int = 1,
latents: dict[str, Any] | None = None,
record: dict[str, Any] | None = None,
) -> dict[str, Any]
Simulate one replicate and return it as a pd_v2 Stan data block.
The four observation-model switches are required and keyword-only, so a caller must name the
arm it simulates. latents, when given, is filled with the true s0, b_raw and eps on the
Stan indexing. record, when given, is filled with the chosen patterns and the per-participant
LEDD level. Neither draws an extra random number, so the output is bit-identical either way.
Validation: VALIDATED. Draw-for-draw equal to the study simulator (golden test).
synthetic_visit_patterns ¶
synthetic_visit_patterns(
n: int,
rng: Generator,
*,
mean_extra_visits: float = 4.0,
max_visits: int = 14,
interval_days: Sequence[int] = (
182,
365,
365,
365,
730,
),
jitter_days: int = 30,
observed_probability: Sequence[float] = (
0.85,
0.6,
0.6,
),
) -> list[VisitPattern]
Generate synthetic visit patterns: visit counts, whole-day intervals and endpoint masks.
The defaults are design choices for testing, not estimates from any cohort. The baseline visit always scores every endpoint.
Validation: TESTED.
visit_patterns ¶
visit_patterns(dataset: TwinDataset) -> list[VisitPattern]
Borrow the visit shape of a real dataset: when each participant was seen and what was scored.
No outcome value is used. Simulating on these patterns keeps the interval distribution, the visit counts and the missingness pattern jointly real.
Validation: TESTED.
build_stan_data ¶
build_stan_data(
dataset: TwinDataset,
*,
config: ModelConfig | None = None,
standardisation: Standardisation | None = None,
pathway: Sequence[str] = (),
grainsize: int = C.PRODUCTION_GRAINSIZE,
) -> StanData
Build the pd_v2 Stan data block from a TwinDataset.
standardisation must come from training participants only; when None it is fitted on every
participant, which is correct for a full-cohort fit and wrong for a held-out evaluation.
pathway names marker columns for the pathway block z, in order.
The output equals the study builder's output on the same input (golden-tested).
Validation: VALIDATED.
dt_years_from_days ¶
dt_years_from_days(
dt_days: NDArray[Any] | Sequence[float],
) -> NDArray[np.float64]
Convert intervals in days to years. Used for the step size only, never for the count.
Validation: VALIDATED.
h_max_in_days ¶
h_max_in_days(
h_max_years: float = C.H_MAX_YEARS,
) -> tuple[int, int]
Return h_max in days as an exact fraction (numerator, denominator).
At the pinned constants this is (1461, 8), which is 182.625 days.
Validation: VALIDATED.
substeps_days ¶
substeps_days(
dt_days: NDArray[Any] | Sequence[float],
h_max_years: float = C.H_MAX_YEARS,
) -> NDArray[np.int64]
Return the number of equal sub-steps on each interval, from integer days (rule D39).
Only an exact tie collapses: an interval of zero days takes zero steps. Every interval of one day or more takes at least one step. The count is ceil(q x days / p) in integer arithmetic.
Validation: VALIDATED.