study

run.study

Run a SimulationStudy end to end: its experiments, its analyses, its figures, and the provenance of every container it writes.

tvbo run and SimulationStudy.run() both call this module, so a run from a shell and a run from a notebook take one path and leave one record. A study that declares studies: runs as a tree: every nested study first, each in its own directory, then the holder’s own content, then the results manifest the manuscript reads.

Nothing here exits the process. A run that refuses its input or cannot finish raises StudyRunError with a message written for the person who asked for the run; tvbo run prints that message and exits 1, and the Python API lets it propagate.

Attributes

Name Description
logger

Classes

Name Description
RunOptions How each experiment of one run executes and saves; the recipe itself is never modified.
StudyRunError A run refused its input or could not finish, for the reason its message gives.

RunOptions

run.study.RunOptions(
    backend=None,
    overrides=(),
    pins=(),
    max_iterations=None,
    duration=None,
    subject=None,
    results_root=None,
    rendered_code=None,
    limit=None,
    shard=None,
    compress=True,
    record_only=True,
)

How each experiment of one run executes and saves; the recipe itself is never modified.

The defaults run the recipe as written and save its recorded outputs compressed. Each field is the tvbo run flag named beside it.

Attributes

Name Type Description
backend str | None Backend for every experiment, over each one’s declared execution.backend (--backend).
overrides Sequence[tuple[str, Any]] (dotted.path, value) assignments applied to each experiment before it runs (--set).
pins Sequence[tuple[str, Any]] (axis parameter, value) pairs, each setting that parameter and dropping its exploration axis, or for <parameter>[<element>] holding that one element while the others keep sweeping (--pin).
max_iterations int | None Cap on every algorithm’s and stage’s n_iterations (--max-iterations, --smoke).
duration float | None integration.duration in ms (--duration).
subject str | None Active subject of a per-subject dataset experiment (--subject).
results_root Path | str | None Where a from_experiment warm start looks for its source run, in place of this run’s results directory (--results-root).
rendered_code str | None A pre-rendered backend script run as-is in place of generated code, for a single experiment (--rendered).
limit int | None Run at most this many cells of a sweep, a spread sample; ignored under shard (--limit).
shard tuple[int, int] | None (i, n), running the sweep cells j with j % n == i (--shard).
compress bool gzip the result containers (--compress/--no-compress).
record_only bool Save the recorded outputs only, not every intermediate observation (cleared by --save-all).

Methods

Name Description
backend_kwargs The keyword arguments SimulationExperiment.run takes from these options.
backend_kwargs
run.study.RunOptions.backend_kwargs()

The keyword arguments SimulationExperiment.run takes from these options.

StudyRunError

run.study.StudyRunError()

A run refused its input or could not finish, for the reason its message gives.

Raised only where that message is the whole story, so it is addressed to the person who asked for the run rather than to a traceback reader.

Functions

Name Description
apply_axis_pins Pin fanned exploration axes to single values for THIS run — the workflow fan-out’s per-cell restriction (the model-scope sibling of --subject).
apply_max_iterations Cap every algorithm’s and stage’s n_iterations (and any optimization’s max_iterations) to n for THIS run — a smoke override, the recipe untouched.
apply_overrides Apply (dotted.path, value) overrides to a resolved experiment in place, and return what they invalidated.
experiment_ids The identifiers an experiment can be selected by.
figure_code_modules The code_modules the figures declare, deduplicated in declaration order.
figure_outputs (name, image, script) for figure under out_dir — where the render writes, named once.
has_nested Whether obj is a study that aggregates others, which is the only thing that changes how a run proceeds.
nested_root Where the study the tree knows as label writes, for a tree writing into base.
provenance_ctx What a run needs in hand to record itself beside each container it writes; owner is the study (or lone experiment) the records name.
provenance_root The root a recorded used: edge names its containers relative to.
rebuild_invalidated Resolve again each object an override invalidated (:func:apply_overrides), from the directory of the recipe it was loaded from, so the run receives what the overridden declaration builds. A network that keeps a random subset of its source’s nodes draws it from the execution.random_seed of experiment, as its build did.
register_figure_code Put a root’s code/ on sys.path, so a figure rendering against it can import the modules its code_modules names.
render_figures Emit + run each figure’s render script and return the written images.
render_study_figures Render a study’s declarative figures: after its experiments have run.
results_root The directory holding THIS run’s result containers.
run_experiment Run one experiment under options, persist its container, and record the run in the container’s sidecar.
run_named_analyses Run only the named analyses: (comma-separated wanted), plus whatever they read, in dependency order.
run_study Run study: its before-analyses, its experiments, its after-analyses and its figures, each container recording the run that wrote it.
run_tree Run a study-of-studies: every nested study depth first, then this study’s own content, then the results manifest the manuscript reads.
runtime_experiment record materialised through study.get_experiment, which is keyed on its id; a StudyRunError names what usually stops one from loading.
select_experiments The experiment records of study, or the comma-separated ids subset of them.
spec_base The study file’s own directory — the root used: references resolve against — or the cwd for a spec that is not a file.
spec_dir The directory a spec’s relative paths mean, or None when the spec is not a file.
study_path_for The directory base gives role, per the study-layout record.
warn_stale_analyses Name the containers a partial run just invalidated but did not recompute.

apply_axis_pins

run.study.apply_axis_pins(experiment, pins)

Pin fanned exploration axes to single values for THIS run — the workflow fan-out’s per-cell restriction (the model-scope sibling of --subject).

For each (parameter, value): set the axis’s parameter on the experiment so the base (representative) run uses it — every DECLARED observation, host or not, is computed on that run, so this is what makes a fanned cell’s host observation land at the cell’s coordinates — AND drop that axis from every exploration so the sweep does not re-expand it. An exploration left with no axes is removed, collapsing the run to a single point.

A parameter written <path>[<element>] pins one element of a per-node parameter (:func:_pin_element): the element is the index its element: declares or a node label, and the other elements keep sweeping.

apply_max_iterations

run.study.apply_max_iterations(experiment, n)

Cap every algorithm’s and stage’s n_iterations (and any optimization’s max_iterations) to n for THIS run — a smoke override, the recipe untouched.

The post-tuning evaluation of a fit — the memory- and time-critical part of a long-horizon run — is independent of how many tuning iterations preceded it, so a handful of iterations is enough to verify the fit executes and its long-horizon post-tuning observables stream within memory. Mirrors :func:apply_overrides: it mutates only the loaded object, so one recipe stays the single source of truth.

apply_overrides

run.study.apply_overrides(experiment, overrides)

Apply (dotted.path, value) overrides to a resolved experiment in place, and return what they invalidated.

Traverses attributes and keyed collections (LinkML keyed dicts) so one recipe can stay the single source of truth while a run uses test settings. A mapping set on a slot that holds one record class is built as that record (:func:_record_for_slot), as the recipe would have built it. Mutates the loaded object only — the recipe file is untouched.

Anything on the path that has already MATERIALISED from its declaration is invalidated before the value is written, and the path is then walked again, so what the invalidation puts back (the nodes and the count a node selection replaced) cannot overwrite the value and the rebuild starts from it. Without this an override of, say, a graph generator’s connectome is reported and then ignored — the network resolved at load time and keeps the matrix it built — and the run completes, looks right, and is not the run that was asked for. An override of the experiment’s execution.random_seed invalidates its network when the network drew a random subset of its source’s nodes from it (:func:_invalidate_drawn_network), so the rebuild draws again. The invalidated objects are returned once each, in the order the overrides reached them, for :func:rebuild_invalidated to rebuild after every override has landed, since a declaration several overrides change together is consistent only at the end.

experiment_ids

run.study.experiment_ids(exp)

The identifiers an experiment can be selected by.

Its key, name, label, and stringified id (dropping the empty ones), plus the bare numeric id those spell — exp-3, exp3 and 3 name one experiment, and an experiment carrying only key: exp-3 must still answer to 3. Normalising HERE and in analysis_io.dependencies is what lets the two sides of the staleness walk intersect; normalising one side only makes every dotted spelling match nothing, and an empty stale set reads exactly like a clean one.

Shared by tvbo run and tvbo workflow so --experiment matches the same way in both.

figure_code_modules

run.study.figure_code_modules(figures)

The code_modules the figures declare, deduplicated in declaration order.

Importing one registers the custom panels and transforms its figures name, which is why a study run imports them before its experiments and tvbo workflow bundles them into a kit’s code/.

figure_outputs

run.study.figure_outputs(figure, out_dir)

(name, image, script) for figure under out_dir — where the render writes, named once.

The renderer and every consumer that has to find a rendered figure afterwards ask this, so a figure’s file name is derived in one place rather than re-spelled wherever it is looked up.

has_nested

run.study.has_nested(obj)

Whether obj is a study that aggregates others, which is the only thing that changes how a run proceeds.

nested_root

run.study.nested_root(base, recipe_dir, label)

Where the study the tree knows as label writes, for a tree writing into base.

None — the study’s own directory — whenever the run has not been redirected, which is the CLI’s behaviour and keeps a nested study’s results in its own layout. A redirected run gives each study a subdirectory named for its label, so a run that must not write into the source tree does not write into a nested study’s either. The label rather than the recipe stem, because a sub-study written inline has no recipe of its own and inherits the holding study’s: naming the directory after that would land every inline sub-study of one recipe in a single directory, each overwriting the last.

provenance_ctx

run.study.provenance_ctx(spec, owner, out_dir=None, *, base=None)

What a run needs in hand to record itself beside each container it writes; owner is the study (or lone experiment) the records name.

Always built. The record goes into the container’s own sidecar, which is a product of the run and never tracked, so remembering what happened costs one key in a file the run was writing anyway — there is nothing for a study to switch off.

provenance_root

run.study.provenance_root(spec, out_dir, *, base=None)

The root a recorded used: edge names its containers relative to.

The STUDY the spec belongs to, even when -o sends the data elsewhere: both ends of an edge have to spell a container identically, and the study is the frame the reader resolves them in. A spec that is in no study — a curated experiment run straight out of the installed database — has no such root, so the results themselves are the frame: out_dir when the results were redirected, else base, the root the run writes into, which defaults to the spec’s own directory. out_dir is -o as the caller gave it, not the directory it resolves to: the question is whether the results were redirected, and a resolved default answers that yes every time.

rebuild_invalidated

run.study.rebuild_invalidated(objects, experiment=None)

Resolve again each object an override invalidated (:func:apply_overrides), from the directory of the recipe it was loaded from, so the run receives what the overridden declaration builds. A network that keeps a random subset of its source’s nodes draws it from the execution.random_seed of experiment, as its build did.

register_figure_code

run.study.register_figure_code(base)

Put a root’s code/ on sys.path, so a figure rendering against it can import the modules its code_modules names.

Called for whichever root a figure actually renders against: its own, or — for a record !included from another study — that study’s, which the including spec knows nothing about. Without it a figure resolves against the right root and still cannot find its panels.

render_figures

run.study.render_figures(figures, base_dir, out_dir, origins=None)

Emit + run each figure’s render script and return the written images.

The single home for the per-figure render loop, shared by the tvbo figure render command and by a study run (which renders a study’s figures after its experiments, so one command closes the replication loop). base_dir is the study root each layer’s used IRI resolves against, whose results directory holds the containers; origins overrides it per figure, for a record !included from another study (see :func:tvbo.cli.figures.figure_origins).

Every figure is attempted before anything is raised, so one broken declaration reports itself alongside the others rather than hiding the thirteen behind it; the run still fails, naming all of them.

The image lands directly in out_dir — the one place the report and every other consumer reads a figure from — while its self-contained, editable plot_<name>.py goes to out_dir/scripts/. Both are regenerable and gitignored together; separating them just keeps a study with many figures from interleaving twice as many files in the directory people actually browse. The subdirectory is deliberately NOT called code: in a study that name means the authored, tracked, importable code the recipe references by bare module name, which this is not.

render_study_figures

run.study.render_study_figures(study, spec, *, base=None, sample=None)

Render a study’s declarative figures: after its experiments have run.

Reuses the exact tvbo figure render path (:func:render_figures), so the images and render scripts a one-command run produces are byte-identical to a follow-up tvbo figure render — the study run just fuses the two steps. base is the study root each layer’s used IRI resolves against and whose figures directory the images land in, defaulting to the recipe’s own directory; -o moves the containers and not the figures. sample is a --limit run’s own directory (:func:results_root): its figures read the sample’s containers and land in its figures/, leaving the study’s untouched. A study with no figures: is a silent no-op. A render failure is reported but does not fail the run — the experiments already succeeded and their results are on disk.

results_root

run.study.results_root(spec, out_dir, *, base=None, sample=None)

The directory holding THIS run’s result containers.

The results directory of the study root the run writes into (:mod:tvbo.utils.study_layout, role results), holding exp-<id>_*_result.h5 for a run and ana-<name>_result.h5 for an analysis, flat. That root is base, defaulting to the recipe’s own directory. out_dir (-o) overrides the location and nothing else. Writer and reader ask this one function, because two independent answers disagreeing is invisible: a run would render this run’s experiments against a previous run’s analyses and report success.

A run sampled to sample cells per sweep (--limit) has a directory of its own beside that one, <results>-limit-<N>, holding its containers, its analyses and its figures, so a sample never mixes with a whole run. Beside it, not inside it, because the container lookups glob the results directory recursively.

run_experiment

run.study.run_experiment(
    experiment,
    spec,
    out_dir=None,
    *,
    options=None,
    owner=None,
    base=None,
)

Run one experiment under options, persist its container, and record the run in the container’s sidecar.

Parameters

Name Type Description Default
experiment A runnable experiment; the overrides, pins and iteration cap in options are applied to it in place, and what an override invalidates is rebuilt before it runs. required
spec str The recipe the run was asked for, which roots its paths and its provenance. required
out_dir Path | None Results directory, in place of base’s. None
options RunOptions | None How the experiment executes and saves; the defaults run it as written. None
owner Any The study the experiment belongs to, which its provenance record names; the experiment itself when omitted. None
base Path | None The study root the run writes into; defaults to the recipe’s own directory. None

Raises

Name Type Description
StudyRunError An override or pin names nothing on the experiment, an element pin names no per-node parameter, or a shard or limit asks a backend to slice a sweep it does not vectorise.

run_named_analyses

run.study.run_named_analyses(study, spec, wanted, out_dir=None)

Run only the named analyses: (comma-separated wanted), plus whatever they read, in dependency order.

The counterpart to --experiment on the derivation side. It exists because an analysis container is content-addressed on its INPUTS: editing the callable that produces it changes nothing a cache can see, so the only way to refresh one is to ask for it by name. Its own upstream analyses are pulled in — a container that has never been produced cannot be read — while the experiments are left alone, which is the point.

Raises

Name Type Description
StudyRunError wanted names nothing, or names an analysis the study does not declare.

run_study

run.study.run_study(
    study,
    spec,
    out_dir=None,
    *,
    base=None,
    options=None,
    experiment=None,
    figures=True,
    analyses=True,
)

Run study: its before-analyses, its experiments, its after-analyses and its figures, each container recording the run that wrote it.

The one path every study run takes — tvbo run <recipe>, each study of a tree, and SimulationStudy.run() — so the flags a run honours and the provenance it records cannot depend on how it was launched.

A run narrowed by experiment or by options.shard, or one told to skip its analyses, runs its experiments with only the analyses they read: no analysis stage and no figures, since both would read a half-refreshed set of containers. An unsharded narrowed run then names the analysis containers it left stale.

Parameters

Name Type Description Default
study The loaded study. required
spec str The recipe it was loaded from, which roots its relative paths and its provenance. required
out_dir Path | None Results directory, in place of base’s. None
base Path | None The study root this run writes into — containers land in its results directory, figures in its figures directory; defaults to the recipe’s own directory. None
options RunOptions | None How each experiment executes and saves; the defaults run the recipe as written. None
experiment str | None Comma-separated ids of the experiments to run, instead of all of them. None
figures bool Render the declared figures: once a whole-study run’s analyses hold. True
analyses bool Run the study’s analysis stages; false runs only the analyses its experiments read, and no figures. True

Returns

Name Type Description
bool Whether the after-experiment analysis stage held; figures are skipped when it did not.

Raises

Name Type Description
StudyRunError experiment matches nothing, a pre-rendered script is given for several experiments, or an experiment cannot be materialised, overridden or sharded as asked.

run_tree

run.study.run_tree(
    inv,
    spec,
    out_dir=None,
    *,
    backend=None,
    figures=True,
    skip=(),
    dry_run=False,
    manifest_only=False,
    base=None,
)

Run a study-of-studies: every nested study depth first, then this study’s own content, then the results manifest the manuscript reads.

Each study runs through :func:run_study with the recipe’s own settings and backend, in its own directory, so its results land in its own layout rather than the aggregating study’s. skip drops named studies at any depth (and everything they hold); dry_run lists what would run and emits nothing; manifest_only runs nothing and emits the manifest from the containers already on disk. The manifest lands at <study-dir>/manuscript_results.yml — a committed derived artifact (the seam Quarto reads as ?meta:results.*), so the build never needs the generated run containers.

base redirects everything this run WRITES, leaving what it READS alone: nested recipes still resolve against their own directories, while each one’s results land in a subdirectory of base named for its label. Defaults to the recipe’s directory, which is the CLI’s behaviour. out_dir moves this study’s own results only.

Raises

Name Type Description
StudyRunError A study’s analysis stage failed, or a result key does not resolve; the manifest is not written in either case.

runtime_experiment

run.study.runtime_experiment(study, record)

record materialised through study.get_experiment, which is keyed on its id; a StudyRunError names what usually stops one from loading.

select_experiments

run.study.select_experiments(study, ids=None)

The experiment records of study, or the comma-separated ids subset of them.

An id is matched against every spelling :func:experiment_ids accepts, so --experiment selects the same way in every verb; a selector that matches nothing raises StudyRunError. The records are datamodel objects — :func:runtime_experiment turns each into one that can run and render, which callers do one at a time so a long study never holds every materialised experiment at once.

spec_base

run.study.spec_base(spec)

The study file’s own directory — the root used: references resolve against — or the cwd for a spec that is not a file.

spec_dir

run.study.spec_dir(spec)

The directory a spec’s relative paths mean, or None when the spec is not a file.

A spec may also be a CURIE (study:Deco2014), a bare database name or a file:// URL; Path(spec).parent on any of those silently yields the cwd, which would resolve relative paths against whatever directory the run happened to start in.

study_path_for

run.study.study_path_for(role, base)

The directory base gives role, per the study-layout record.

warn_stale_analyses

run.study.warn_stale_analyses(
    analyses,
    spec,
    out_dir,
    *,
    experiments=(),
    recomputed=(),
)

Name the containers a partial run just invalidated but did not recompute.

Both partial modes need this and they need it identically. --experiment re-runs a simulation, --analysis re-derives a container, and in each case everything downstream keeps the PREVIOUS numbers while the thing it reads is fresh. Nothing raises, so a figure or report built next mixes the two.

recomputed names what this run actually produced, which both seeds the walk and drops out of its result. A transient analysis (persist: false) among them is recomputed by every run that reads it and seeds nothing: its other consumers go stale only through a persisted change upstream of it, which the walk reaches on its own. It is the CLOSURE, not what was asked for on the command line: a named analysis pulls a never-produced upstream in with it, and seeding on the request would miss every dependent of that upstream.