Skip to content

Study run

A study run reads the study's define files, builds every dataset they declare from its inputs, and hands each built dataset forward. fleet.plan_study returns the study plan without building anything; fleet.run_study yields one built dataset per step and writes no file. fleet run is the command on top of it: it prints the plan, writes each dataset and sets the exit code. A run that cannot plan or build raises StudyRunError, documented with the other exceptions. The rule for inputs is ADR 0006: every input is pinned, and only carry-through columns (declared with no derivation) are joined from the other inputs.

plan_study

fleet.run.plan_study

plan_study(ctx, *, datasets=None)

Read the study's define files and return the steps of a study run.

A dataset runs after the datasets of the plan that it names as type: dataset inputs, so ADVS reads the ADSL of the same run. Datasets with no such link keep their file order, SDTM first.

Parameters:

Name Type Description Default
ctx StudyContext

The study context, from :func:fleet.load_study_context.

required
datasets Sequence[str] | None

Keep only these datasets (case-insensitive). Default: every dataset in the define files.

None

Returns:

Name Type Description
StudyPlan StudyPlan

The steps, in run order.

Raises:

Type Description
StudyRunError

When neither define file exists, a name in datasets is not declared in them, a planned dataset declares no inputs, or two datasets need each other.

Examples:

List what fleet run would build::

plan = fleet.plan_study(fleet.load_study_context("study_config.yaml"))
[(s.standard, s.dataset) for s in plan.steps]
Source code in src/fleet/run.py
def plan_study(ctx: StudyContext, *, datasets: Sequence[str] | None = None) -> StudyPlan:
    """Read the study's define files and return the steps of a study run.

    A dataset runs after the datasets of the plan that it names as
    ``type: dataset`` inputs, so ADVS reads the ADSL of the same run.
    Datasets with no such link keep their file order, SDTM first.

    Args:
        ctx: The study context, from :func:`fleet.load_study_context`.
        datasets: Keep only these datasets (case-insensitive).  Default:
            every dataset in the define files.

    Returns:
        StudyPlan: The steps, in run order.

    Raises:
        StudyRunError: When neither define file exists, a name in
            *datasets* is not declared in them, a planned dataset
            declares no inputs, or two datasets need each other.

    Examples:
        List what ``fleet run`` would build::

            plan = fleet.plan_study(fleet.load_study_context("study_config.yaml"))
            [(s.standard, s.dataset) for s in plan.steps]
    """
    standards: tuple[Standard, ...] = ("sdtm", "adam")
    defines = [
        (ctx.metadata_dir(standard) / "define.yaml", standard)
        for standard in standards
        if (ctx.metadata_dir(standard) / "define.yaml").is_file()
    ]
    if not defines:
        raise StudyRunError(
            f"no define.yaml found under {ctx.metadata_sdtm_dir} or "
            f"{ctx.metadata_adam_dir}. Run `fleet init define` first."
        )

    steps: list[Step] = []
    for path, standard in defines:
        for entry in load_define_spec(path).datasets or []:
            steps.append(
                Step(
                    define=path,
                    standard=standard,
                    dataset=entry.name.upper(),
                    inputs=tuple(
                        DeclaredInput(
                            name=i["name"],
                            path=i.get("path"),
                            type="raw" if i.get("type") == "raw" else "dataset",
                        )
                        for i in entry.inputs
                    ),
                    carry_through=tuple(v.name for v in entry.variables if v.derivation is None),
                    text_columns=_text_columns(entry),
                    qualifiers=_qualifiers(entry) if standard == "sdtm" else (),
                )
            )

    declared = {s.dataset: s.standard for s in steps}
    if datasets is not None:
        wanted = {d.upper() for d in datasets}
        known = sorted({s.dataset for s in steps})
        unknown = sorted(wanted - set(known))
        if unknown:
            raise StudyRunError(
                f"unknown dataset(s): {', '.join(unknown)}. "
                f"Datasets in the define files: {', '.join(known)}"
            )
        steps = [s for s in steps if s.dataset in wanted]

    for step in steps:
        if not step.inputs:
            raise StudyRunError(
                f"dataset {step.dataset}: the define declares no `inputs:`, so a study "
                "run cannot determine the source data. Add an inputs: block."
            )

    return StudyPlan(ctx=ctx, steps=_in_dependency_order(steps), declared=declared)

options: show_root_heading: true heading_level: 3

run_study

fleet.run.run_study

run_study(plan, *, inputs=None, strict=True)

Build every step of a study plan, in order, and yield each built dataset.

Writes no file and prints nothing.

Parameters:

Name Type Description Default
plan StudyPlan

The plan from :func:plan_study.

required
inputs Mapping[str, DataFrame] | None

Frames the caller already holds, by dataset name. A seed is used before any file.

None
strict bool

Raise on an unknown spec algorithm (default). False warns and skips, as from_spec does.

True

Yields:

Name Type Description
BuiltDataset BuiltDataset

One per step, as soon as it is built.

Raises:

Type Description
StudyRunError

When a seed is also a step of the plan, an input cannot be found, or a carry-through column needs a USUBJID that one side lacks or that has two different rows in the input.

Examples:

Build ADVS from an ADSL held in memory::

plan = fleet.plan_study(ctx, datasets=["ADVS"])
advs = next(fleet.run_study(plan, inputs={"ADSL": adsl})).frame
Source code in src/fleet/run.py
def run_study(
    plan: StudyPlan,
    *,
    inputs: Mapping[str, pl.DataFrame] | None = None,
    strict: bool = True,
) -> Iterator[BuiltDataset]:
    """Build every step of a study plan, in order, and yield each built dataset.

    Writes no file and prints nothing.

    Args:
        plan: The plan from :func:`plan_study`.
        inputs: Frames the caller already holds, by dataset name.  A seed
            is used before any file.
        strict: Raise on an unknown spec algorithm (default).  ``False``
            warns and skips, as ``from_spec`` does.

    Yields:
        BuiltDataset: One per step, as soon as it is built.

    Raises:
        StudyRunError: When a seed is also a step of the plan, an input
            cannot be found, or a carry-through column needs a USUBJID
            that one side lacks or that has two different rows in the input.

    Examples:
        Build ADVS from an ADSL held in memory::

            plan = fleet.plan_study(ctx, datasets=["ADVS"])
            advs = next(fleet.run_study(plan, inputs={"ADSL": adsl})).frame
    """
    held: dict[str, _Held] = {
        name.upper(): _Held(frame, ResolvedInput(path=None, source="seed"))
        for name, frame in (inputs or {}).items()
    }
    text_columns = frozenset(c for s in plan.steps for c in s.text_columns)
    collisions = sorted(held.keys() & {s.dataset for s in plan.steps})
    if collisions:
        raise StudyRunError(
            f"{', '.join(collisions)} is both a seeded input and a step; "
            "plan with datasets= to leave it out."
        )

    for step in plan.steps:
        resolved = {d.name: _resolve_input(plan, step, d, held, text_columns) for d in step.inputs}
        frames = [held[d.name.upper()].frame for d in step.inputs]
        base, extras = frames[0], list(zip(step.inputs[1:], frames[1:], strict=True))

        for declared, extra in extras:
            cols = [c for c in extra.columns if c in step.carry_through and c not in base.columns]
            if not cols:
                continue
            if "USUBJID" not in base.columns or "USUBJID" not in extra.columns:
                raise StudyRunError(
                    f"dataset {step.dataset}: cannot carry {', '.join(cols)} from input "
                    f"'{declared.name}' because both frames must carry USUBJID."
                )
            base = _carry(step.dataset, declared.name, base, extra.select(["USUBJID", *cols]))

        ns = _namespace(base, step.standard)
        for declared, extra in extras:
            ns = ns.pin(declared.name.upper(), extra)
        try:
            built_frame = (
                ns.from_spec(step.define, dataset=step.dataset, strict=strict)
                .select(spec=step.define, dataset=step.dataset)
                .to_frame()
            )
        except SpecError as err:
            _undeclared_source(step, err)
            raise
        held[step.dataset] = _Held(built_frame, ResolvedInput(path=None, source="built"))
        if step.qualifiers:
            seq = f"{step.dataset}SEQ"
            supp = _frame(built_frame).sdtm.export_supp(
                spec=step.define,
                dataset=step.dataset,
                idvar=seq if seq in built_frame.columns else None,
                domain=step.dataset,
            )
            parent = built_frame.drop(step.qualifiers, strict=False)
            yield BuiltDataset(step=step, frame=parent, inputs=resolved, supp=supp)
            continue
        yield BuiltDataset(step=step, frame=built_frame, inputs=resolved)

options: show_root_heading: true heading_level: 3

Records

fleet.run.StudyPlan dataclass

The ordered steps of a study run, fixed before the first one builds.

Attributes:

Name Type Description
ctx StudyContext

The study context the steps resolve against.

steps tuple[Step, ...]

The steps, in run order.

declared Mapping[str, Standard]

Every dataset the define files declare, with its standard, also those the datasets= filter left out.

Source code in src/fleet/run.py
@dataclass(frozen=True)
class StudyPlan:
    """The ordered steps of a study run, fixed before the first one builds.

    Attributes:
        ctx: The study context the steps resolve against.
        steps: The steps, in run order.
        declared: Every dataset the define files declare, with its
            standard, also those the ``datasets=`` filter left out.
    """

    ctx: StudyContext
    steps: tuple[Step, ...]
    declared: Mapping[str, Standard] = field(default_factory=dict)

options: show_root_heading: true heading_level: 3 filters: ["!^_"]

fleet.run.Step dataclass

One dataset of a study plan.

Attributes:

Name Type Description
define Path

The define file that declares the dataset.

standard Standard

"sdtm" or "adam".

dataset str

The dataset name, upper-cased.

inputs tuple[DeclaredInput, ...]

The declared inputs, in order. The first is the base frame; every other one is pinned under its name.

carry_through tuple[str, ...]

The declared variables with no derivation, which the run takes from the inputs unchanged (ADR 0006).

text_columns tuple[str, ...]

The variables of define type text and the raw columns their derivations name as source. A CSV input reads them as text, so SUBJID 0012 and LBORRES 1.10 keep their characters.

qualifiers tuple[str, ...]

The SDTM variables with role: qualifier or algorithm: nsv. The run moves them to a SUPP dataset.

Source code in src/fleet/run.py
@dataclass(frozen=True)
class Step:
    """One dataset of a study plan.

    Attributes:
        define: The define file that declares the dataset.
        standard: ``"sdtm"`` or ``"adam"``.
        dataset: The dataset name, upper-cased.
        inputs: The declared inputs, in order.  The first is the base
            frame; every other one is pinned under its name.
        carry_through: The declared variables with no derivation, which
            the run takes from the inputs unchanged (ADR 0006).
        text_columns: The variables of define type ``text`` and the raw
            columns their derivations name as ``source``.  A CSV input
            reads them as text, so SUBJID ``0012`` and LBORRES ``1.10``
            keep their characters.
        qualifiers: The SDTM variables with ``role: qualifier`` or
            ``algorithm: nsv``.  The run moves them to a SUPP dataset.
    """

    define: Path
    standard: Standard
    dataset: str
    inputs: tuple[DeclaredInput, ...]
    carry_through: tuple[str, ...]
    text_columns: tuple[str, ...] = ()
    qualifiers: tuple[str, ...] = ()

options: show_root_heading: true heading_level: 3 filters: ["!^_"]

fleet.run.BuiltDataset dataclass

What a study run yields for one step.

Attributes:

Name Type Description
step Step

The step that was built.

frame DataFrame

The built dataset, materialised. An SDTM dataset leaves out its qualifier variables, which are in supp.

inputs dict[str, ResolvedInput]

Each input of the step, by name, with where it came from.

supp DataFrame | None

The SUPP<domain> dataset of an SDTM step with qualifier variables (SDTMIG 3.4 section 8.4), else None.

Source code in src/fleet/run.py
@dataclass(frozen=True)
class BuiltDataset:
    """What a study run yields for one step.

    Attributes:
        step: The step that was built.
        frame: The built dataset, materialised.  An SDTM dataset leaves out
            its qualifier variables, which are in *supp*.
        inputs: Each input of the step, by name, with where it came from.
        supp: The ``SUPP<domain>`` dataset of an SDTM step with qualifier
            variables (SDTMIG 3.4 section 8.4), else ``None``.
    """

    step: Step
    frame: pl.DataFrame
    inputs: dict[str, ResolvedInput]
    supp: pl.DataFrame | None = None

options: show_root_heading: true heading_level: 3 filters: ["!^_"]

fleet.run.ResolvedInput dataclass

One input of a step and where the study run took it from.

Attributes:

Name Type Description
path Path | None

The file it was read from, or None for a seed or a dataset built earlier in the run.

source InputSource

Which of the sources supplied it.

Source code in src/fleet/run.py
@dataclass(frozen=True)
class ResolvedInput:
    """One input of a step and where the study run took it from.

    Attributes:
        path: The file it was read from, or ``None`` for a seed or a
            dataset built earlier in the run.
        source: Which of the sources supplied it.
    """

    path: Path | None
    source: InputSource

options: show_root_heading: true heading_level: 3 filters: ["!^_"]