Skip to content

Study, outputs, compute and benchmark

symphony_dt.study

One study file, one command: symphony-dt run study.yaml.

A StudyConfig names the data, the eligibility rules, the model arm, the held-out design, the sampler, any gate override, the forecast, the scoring specification and the outputs. run_study runs the stages in order, writes each stage's outputs and a manifest into its own folder, and skips a stage that is already complete for the same configuration. dry_run stops before fitting, so a configuration and its data can be checked in seconds.

DataSection

Bases: _Section

Where the data come from: a dataset folder, a table with a mapping, or a simulation.

Validation: TESTED.

ModelSection

Bases: _Section

The registered model, its arm and its pathway markers.

Validation: TESTED.

SplitSection

Bases: _Section

The held-out design: a random share of participants masked after the anchor.

Validation: TESTED.

SamplerSection

Bases: _Section

CmdStan NUTS settings.

Validation: TESTED.

OverrideSection

Bases: _Section

An explicit gate override; it needs a reason and an author and is logged.

Validation: TESTED.

ForecastSection

Bases: _Section

Exact-route forecast settings.

Validation: TESTED.

OutputSection

Bases: _Section

Table formats, figure formats and whether to draw figures.

Validation: TESTED.

StudyConfig

Bases: _Section

The whole study in one object, loaded from study.yaml.

Validation: TESTED.

digest

digest(*sections: str) -> str

Return a digest of the named sections, used to decide whether a stage must rerun.

Validation: TESTED.

StudyResult

What run_study produced: stage folders, statuses and the objects of the last run.

Validation: TESTED.

summary

summary() -> dict[str, str]

Return the status of every stage.

Validation: TESTED.

init_study

init_study(directory: str | Path) -> Path

Write a commented study.yaml template into directory and return its path. An existing file is kept.

Validation: TESTED.

load_study

load_study(path: str | Path) -> StudyConfig

Read and validate a study file. Relative data paths resolve against the file's folder.

Validation: TESTED.

run_study

run_study(
    config: StudyConfig | str | Path,
    *,
    stages: Sequence[str] | None = None,
    dry_run: bool = False,
    force: bool = False,
) -> StudyResult

Run the study, stage by stage.

stages restricts the run to named stages (their inputs must exist from an earlier run). dry_run runs data, eligibility, profile, build and split only. A stage whose marker matches the current configuration is skipped unless force is set; its outputs are reloaded from disk.

Validation: TESTED.

symphony_dt.outputs

Tidy output tables a modeller can take into R, Python, Excel or a manuscript pipeline.

Every table is long and tidy: one row per observation unit, one column per variable. write_tables writes a dict of tables as CSV and Parquet files and one Excel workbook with a sheet per table.

posterior_summary

posterior_summary(
    fit: Any,
    *,
    globals_only: bool = True,
    retained_only: bool = True,
) -> pd.DataFrame

Return a tidy posterior summary from CmdStan's stansummary, on the retained chains by default.

Columns: parameter, mean, sd, mcse, q5, q50, q95, ess_bulk, ess_tail, rhat.

Validation: TESTED.

tidy_summary

tidy_summary(
    table: DataFrame, *, globals_only: bool = True
) -> pd.DataFrame

Turn a stansummary table into the tidy layout of posterior_summary.

Validation: TESTED.

forecast_table

forecast_table(
    forecast: Any,
    participant_ids: Sequence[str] | None = None,
    quantiles: Sequence[float] = (
        0.025,
        0.25,
        0.5,
        0.75,
        0.975,
    ),
) -> pd.DataFrame

Return one row per forecast target with endpoint name, horizon, observed value and quantiles.

participant_ids maps the zero-based index i of an exact-route forecast to identifiers.

Validation: TESTED.

scores_table

scores_table(scores: Mapping[str, Any]) -> pd.DataFrame

Flatten a scores dict (FoldScores.scores or PooledScores.scores) to rows of cell, method, metric.

Each row holds the estimate and its bootstrap interval.

Validation: TESTED.

write_tables

write_tables(
    tables: Mapping[str, DataFrame],
    directory: str | Path,
    formats: Sequence[str] = ("csv", "parquet", "xlsx"),
) -> dict[str, list[str]]

Write each table in each format; xlsx puts every table in one workbook, one sheet each.

Returns the written paths per table.

Validation: TESTED.

symphony_dt.compute

Run anywhere: portable bundles, Slurm job arrays, container recipes, JSON Schemas and a JSON twin service.

  • write_bundle packs a run's inputs, settings, manifests and an environment lock with a SHA256SUMS file, so the run can be repeated on another machine; verify_bundle checks every digest there.
  • slurm_script writes an sbatch job array with one CmdStan chain per task and a dependent job that judges the gates once every chain has finished.
  • container_recipe returns a Dockerfile or an Apptainer definition with CmdStan installed.
  • json_schema returns JSON Schemas for the study file, the dataset tables and a twin visit, so R, Julia or any language can produce valid inputs.
  • serve_twin runs a JSON-lines loop on standard streams: any program sends a command and reads a reply.

write_bundle

write_bundle(
    files: Iterable[str | Path],
    output: str | Path,
    *,
    root: str | Path | None = None,
    note: str = "",
) -> Path

Pack files into a .tar.gz run bundle with SHA256SUMS, an environment lock and a README.

Paths inside the bundle are relative to root (default: the common parent). Never include participant-level data unless the receiving machine is governed for it.

Validation: TESTED.

verify_bundle

verify_bundle(
    bundle: str | Path,
    *,
    extract_to: str | Path | None = None,
) -> dict[str, bool]

Extract a bundle and check every file against SHA256SUMS; return file to match.

Validation: TESTED.

slurm_script

slurm_script(
    data: str | Path,
    output_dir: str | Path,
    *,
    chains: int = 4,
    warmup: int = 1000,
    draws: int = 1000,
    seed: int = 20260729,
    threads_per_chain: int = 1,
    time: str = "24:00:00",
    mem: str = "16G",
    partition: str | None = None,
    account: str | None = None,
    python: str = "python",
    cmdstan: str | None = None,
    modules: Sequence[str] = (),
) -> str

Return an sbatch job-array script: one chain per array task, then a dependent gates job.

Chains share one output folder and seed and differ by chain id, so the result equals a local run with the same settings. Submit with sbatch fit.sbatch; the script submits the gates job itself.

Validation: TESTED.

container_recipe

container_recipe(
    kind: Literal["docker", "apptainer"] = "docker",
    version: str | None = None,
) -> str

Return a Dockerfile or an Apptainer definition that installs symphony-dt and CmdStan 2.39.0.

Validation: TESTED.

json_schema

json_schema(
    name: Literal["study", "dataset", "visit"],
) -> dict[str, Any]

Return a JSON Schema: the study file, the dataset tables, or one twin visit.

Validation: TESTED.

serve_twin

serve_twin(
    twin_path: str | Path,
    stdin: IO[str] | None = None,
    stdout: IO[str] | None = None,
) -> int

Run a JSON-lines command loop for one saved twin; return the number of commands handled.

Commands, one JSON object per line: {"op": "observe", "visit": {...}}, {"op": "forecast", "horizons": [1, 2]}, {"op": "next_visit", "candidates": [0.5, 1], "target_years": 2}, {"op": "milestone", "endpoint": "moca", "threshold": 26}, {"op": "status"}, {"op": "save"} and {"op": "quit"}. Each reply is one JSON object with ok and either result or error. The twin is saved after every observe.

Validation: EXPERIMENTAL.

symphony_dt.bench

An open benchmark of synthetic scenarios with known truth.

Each scenario simulates a cohort from the pd_v2 generative model, alters it in one named way, holds out every test participant's visits after a two-year anchor and scores forecasts with the frozen code-of-record specification. Baselines are LOCF and the linear mixed model of the scoring code.

The twin is the living twin of symphony_dt.twin. It runs on one of three populations. The oracle population is the generating parameters, which isolates the participant-level machinery and the scoring. The estimated population is a pd_v2 fit on the scenario's fit data, read with PopulationDraws.from_fit, which adds population estimation. A supplied population is any PopulationDraws the caller passes.

External methods are scored on equal terms. benchmark_targets returns the history a method may see and the targets it must forecast, and score_predictions scores a long table of forecast draws with the same specification and the same baselines as run_benchmark.

Scenarios: * dense: visits every six months to a year. * sparse: few visits, one to two years apart. * floor: motor scores pushed toward zero, where the truncated density matters. * dropout: informative loss to follow-up; a participant leaves after their motor score passes 40. * drift: from year three, every motor score reads three points high, a measurement drift the model does not know.

All results are synthetic. They are associational and make no causal, treatment or deployment claim.

BenchmarkScenario dataclass

One scenario: the simulated cohort, its generating parameters and the split at the anchor.

participant_ids is the Stan data order, which split indexes. standardisation is fitted on the whole cohort, as the twin and the fit use it. seed is the benchmark seed the scenario was built with.

Validation: EXPERIMENTAL.

scenario_cohort

scenario_cohort(
    name: str, n: int = 120, seed: int = 0
) -> tuple[TwinDataset, dict[str, Any]]

Simulate the cohort of one scenario; return the dataset and the generating parameters.

Validation: EXPERIMENTAL.

benchmark_scenario

benchmark_scenario(
    name: str,
    *,
    n: int = 120,
    n_test: int = 40,
    seed: int = 0,
) -> BenchmarkScenario

Simulate one scenario and hold out every test participant's visits after the anchor.

The seeds follow the scenario's place in SCENARIOS, so a scenario is the same alone or in a full run. The split is split_at_anchor at the anchor of the default scoring specification.

Validation: EXPERIMENTAL.

benchmark_targets

benchmark_targets(
    scenario: BenchmarkScenario,
) -> tuple[TwinDataset, pd.DataFrame]

Return the history a method may see and the table of targets it must forecast.

The history is the fit data of the split: every training participant's full record, and each test participant's observations and visits up to the anchor. The LMM baseline and an estimated population see the same data. The targets table has one row per held-out observation, in scoring order, with participant_id, endpoint, time_days and horizon_years, the time since that participant's last visible observation. It holds no outcome values.

Validation: TESTED.

twin_predictions

twin_predictions(
    scenario: BenchmarkScenario,
    population: Any = None,
    *,
    n_particles: int = 1000,
    n_samples: int = 400,
) -> pd.DataFrame

Return the twin's forecast draws for the scenario's targets as a predictions table.

population is a PopulationDraws, or None for the oracle. The table has the columns of PREDICTION_COLUMNS and scores exactly as the twin does inside run_benchmark.

Validation: EXPERIMENTAL.

score_predictions

score_predictions(
    scenario: BenchmarkScenario,
    predictions: DataFrame,
    *,
    label: str = "external",
) -> pd.DataFrame

Score an external method's forecast draws with the benchmark's specification and baselines.

predictions is a long table with the columns of PREDICTION_COLUMNS: one row per target of benchmark_targets and draw. Every target needs the same number of draws, and every value must lie within its endpoint's scale bounds; any breach raises ValueError. Row order and draw labels do not matter. The table has the layout of run_benchmark without its population columns. The method's rows are named label and label_all, its paired differences crps_diff_<label>_minus_<baseline>.

Validation: TESTED.

run_benchmark

run_benchmark(
    scenarios: Sequence[str] = SCENARIOS,
    *,
    n: int = 120,
    n_test: int = 40,
    seed: int = 0,
    population: Any = None,
    n_particles: int = 1000,
    n_samples: int = 400,
    fit_options: Mapping[str, Any] | None = None,
) -> pd.DataFrame

Run the benchmark and return a tidy table of scores per scenario, endpoint, window, method and metric.

population chooses the twin's population draws. None or "oracle" uses the generating parameters. "estimated" fits pd_v2 on each scenario's fit data and reads the draws with PopulationDraws.from_fit. A PopulationDraws is used as supplied for every scenario. fit_options passes keyword arguments to symphony_dt.fit.fit, such as chains, iter_warmup, iter_sampling and seed, plus n_draws for from_fit. The column population_kind records oracle, estimated or supplied; population names the draws' source.

Validation: EXPERIMENTAL.