Skip to content

Therapeutic-Area Extensions

Fleet ships eight TA extensions accessible via df.adam.<ta>, inspired by the admiral TA packages. They are not ports: a verb can give other values than its admiral counterpart. Each verb docstring names its source under References.

Every TA namespace inherits the shared ADaM verbs, so autocomplete shows about 45 names. To list only the verbs a TA namespace adds, filter verbs() on its origin:

import fleet
import polars as pl

df = pl.DataFrame({"x": [1]})
df.adam.vaccine.verbs().filter(pl.col("origin") == "adam.vaccine")

A TA verb is a clinical verb: it encodes a rule a programmer would otherwise copy from a standard or a SAP, and its docstring cites that rule under References. A new clinical verb must pass the admission bar of ADR-0009: if it were deleted, a programmer who rewrites it inline must be able to get a wrong answer, not only type more.

Oncology — df.adam.onco

fleet.adam.OncoNamespace

Bases: SharedADaMVerbsMixin

Immutable pipeline builder for ADaM oncology derivations.

Inherits shared verbs from SharedADaMVerbsMixin. Each verb returns a new OncoNamespace instance; to_frame() materialises the result.

Source code in src/fleet/adam/onco_namespace.py
class OncoNamespace(SharedADaMVerbsMixin):
    """
    Immutable pipeline builder for ADaM oncology derivations.

    Inherits shared verbs from ``SharedADaMVerbsMixin``.
    Each verb returns a new ``OncoNamespace`` instance;
    ``to_frame()`` materialises the result.
    """

    # ------------------------------------------------------------------ #
    # 1. aval_resp — RECIST text → numeric                                #
    # ------------------------------------------------------------------ #

    def aval_resp(self, target: str, *, source: str) -> Self:
        """Map RECIST response text to numeric codes.

        Mapping: CR=1, PR=2, SD=3, NON-CR/NON-PD=4, PD=5, NE=6,
        MISSING=7.  Other/null values produce null.

        Args:
            target: Name of the output numeric column.
            source: Column containing RECIST response text.

        Returns:
            Self: The namespace with *target* appended.

        Examples:
            Map overall response to a numeric code::

                adrs = (
                    rs_raw.adam.onco
                    .aval_resp("AVAL", source="OVRLRESP")
                    .to_frame()
                )

        References:
            RECIST 1.1: Eisenhauer EA et al. New response evaluation criteria in solid
            tumours. Eur J Cancer. 2009;45(2):228-247. The numeric ranks follow
            admiralonco ``aval_resp`` (pharmaverse).
        """
        return self._chain(_resp_num_expr(source).cast(pl.Float64).alias(target))

    # ------------------------------------------------------------------ #
    # 2. tumor_response_flag — flag responders                            #
    # ------------------------------------------------------------------ #

    def tumor_response_flag(
        self,
        target: str,
        *,
        source: str,
        responses: list[str] | None = None,
        flag_value: str = "Y",
    ) -> Self:
        """Flag records where *source* matches a target response.

        Args:
            target: Name of the output flag column.
            source: Column containing response text.
            responses: Values to flag (default ``["CR", "PR"]``).
            flag_value: Value to assign for matching records (default ``"Y"``).

        Returns:
            Self: The namespace with *target* appended.

        Examples:
            Flag objective responders (CR or PR)::

                adrs = (
                    rs_raw.adam.onco
                    .tumor_response_flag("RSPFL", source="OVRLRESP")
                    .to_frame()
                )
        """
        rsp = responses if responses is not None else ["CR", "PR"]
        return self._chain(
            pl.when(pl.col(source).is_in(rsp))
            .then(pl.lit(flag_value))
            .otherwise(pl.lit(None))
            .alias(target)
        )

    # ------------------------------------------------------------------ #
    # 3. best_overall_response — most favourable response per group       #
    # ------------------------------------------------------------------ #

    def best_overall_response(
        self,
        target: str,
        *,
        source: str,
        date_col: str,
        reference_date: str,
        min_sd_days: int,
        by: list[str] | None = None,
    ) -> Self:
        """Derive best overall response (BOR) per group.

        The most favourable response is the one with the lowest RECIST rank
        (CR < PR < SD < NON-CR/NON-PD < PD < NE < MISSING). An SD or
        NON-CR/NON-PD assessed before *reference_date* + *min_sd_days*, or
        with a null date, counts as NE. The verb reads every record: it does
        not remove records after the first PD or after new anti-cancer
        therapy. Run ``filter_pd`` on a copy first and join BOR back.

        Args:
            target: Name of the output column.
            source: Column containing RECIST response text.
            date_col: Assessment date column (Date or ISO text).
            reference_date: Start of the SD minimum, for example RANDDT or
                TRTSDT.
            min_sd_days: Protocol minimum duration of SD, in days. ``0``
                switches the rule off; the two date columns are then not read.
            by: Partition columns (default ``["USUBJID"]``).

        Returns:
            Self: The namespace with *target* appended.

        Raises:
            DerivationError: If *min_sd_days* is negative.

        Examples:
            Derive BOR per subject up to the first PD, with a 42-day SD minimum::

                bor = (
                    adrs.adam.onco
                    .filter_pd(response_col="OVRLRESP", date_col="ADT",
                               by=["USUBJID"])
                    .best_overall_response("BOR", source="OVRLRESP",
                                           date_col="ADT",
                                           reference_date="RANDDT",
                                           min_sd_days=42, by=["USUBJID"])
                    .to_frame()
                    .select("USUBJID", "BOR")
                    .unique()
                )
                adrs = adrs.join(bor, on="USUBJID", how="left")

        References:
            RECIST 1.1 (Eisenhauer EA et al. Eur J Cancer. 2009;45(2):228-247),
            section 4.4: best overall response is the best response up to
            progression; section 4.4.3: SD must meet a protocol-specified
            minimum time from the reference date, else BOR is NE or PD. The
            ordering CR < PR < SD < NON-CR/NON-PD < PD < NE follows admiralonco
            ``derive_param_bor`` (``ADT >= reference + minimum``). This verb does
            not apply the confirmation requirement; see
            ``confirmed_response_flag``. ADR-0031.
        """
        if min_sd_days < 0:
            raise DerivationError(
                f"best_overall_response(): min_sd_days={min_sd_days}. Give 0 or more days."
            )
        grps = by or ["USUBJID"]
        resp = pl.col(source)
        if min_sd_days:
            early = (
                pl.col(date_col).cast(pl.Date)
                < pl.col(reference_date).cast(pl.Date) + pl.duration(days=min_sd_days)
            ).fill_null(True)
            resp = (
                pl.when(resp.is_in(["SD", "NON-CR/NON-PD"]) & early)
                .then(pl.lit("NE"))
                .otherwise(resp)
            )
        best_num = resp.replace_strict(_RESP_TO_NUM, default=None).min().over(grps)
        return self._chain(_num_resp_expr(best_num).alias(target))

    # ------------------------------------------------------------------ #
    # 4. confirmed_response_flag — confirm response sustained N days      #
    # ------------------------------------------------------------------ #

    def confirmed_response_flag(
        self,
        target: str,
        *,
        source: str,
        date_col: str,
        confirmation_days: int = 28,
        responses: list[str] | None = None,
        by: list[str] | None = None,
        flag_value: str = "Y",
        max_nr_ne: int | None = 1,
        max_nr_sd: int | None = 0,
    ) -> Self:
        """Flag each CR or PR record that a later assessment confirms.

        A CR is confirmed by a CR at least *confirmation_days* later. A PR is
        confirmed by a CR or PR at least *confirmation_days* later. All
        assessments after the record, up to and including the first
        confirming one, must be CR or NE for a CR, and CR, PR, NE or SD for a
        PR, with at most *max_nr_ne* NE and at most *max_nr_sd* SD. For a PR,
        no PR may follow a CR in that window. Assessments after the first PD
        of a group are not read, so a ``filter_pd`` before the verb changes
        nothing. Only the confirmed record is flagged.

        The verb warns, with the group values, when a CR is followed by a PR
        or SD, when two assessments of a group have the same date, and when
        *source* is null.

        Args:
            target: Name of the output flag column.
            source: Column containing response text.
            date_col: Assessment date column (Date or ISO text).
            confirmation_days: Minimum gap in days (default ``28``).
            responses: Responses to confirm: ``["CR", "PR"]`` (default) or a
                subset of it.
            by: Partition columns (default ``["USUBJID"]``).
            flag_value: Value to assign (default ``"Y"``).
            max_nr_ne: Maximum number of NE assessments in the window
                (default ``1``). ``None`` gives no limit.
            max_nr_sd: Maximum number of SD assessments in the window of a
                PR (default ``0``). ``None`` gives no limit. SD never
                confirms a CR.

        Returns:
            Self: A fresh namespace wrapping the updated frame.

        Raises:
            DerivationError: If *responses* holds a value other than CR or PR.

        Examples:
            Flag confirmed CR/PR responses::

                adrs = (
                    rs_raw.adam.onco
                    .confirmed_response_flag(
                        "CRSPFL", source="OVRLRESP", date_col="ADT",
                        confirmation_days=28, by=["USUBJID"])
                    .to_frame()
                )

        References:
            RECIST 1.1 (Eisenhauer EA et al. Eur J Cancer. 2009;45(2):228-247),
            section 4.4.3 Table 3, section 4.4.4 and the Appendix FAQ: a CR or PR
            is confirmed by a repeat assessment no less than 4 weeks later. The
            rules for NE and SD between the two follow the admiralonco
            ``crsp_y_cr`` and ``crsp_y_pr`` events (pharmaverse); SD between
            two PR is the ``accept_sd`` option of the deprecated
            ``derive_param_confirmed_resp``. RECIST does not fix them: check the
            SAP. ADR-0030.
        """
        rsp = responses if responses is not None else ["CR", "PR"]
        unknown = sorted(set(rsp) - {"CR", "PR"})
        if unknown or not rsp:
            raise DerivationError(
                f"confirmed_response_flag(): responses={rsp!r}. Only CR and PR can be "
                "confirmed; give ['CR', 'PR'] or a subset."
            )
        grps = by or ["USUBJID"]
        df = self.to_frame().with_row_index("__row")
        work = df.select(
            "__row",
            *grps,
            pl.col(date_col).cast(pl.Date).alias("__dt"),
            pl.col(source).alias("__v"),
        )
        first_pd = (
            work.filter(pl.col("__v") == "PD")
            .group_by(grps)
            .agg(pl.col("__dt").min().alias("__pd"))
        )
        scope = (
            work.join(first_pd, on=grps, how="left", nulls_equal=True)
            .filter(pl.col("__pd").is_null() | (pl.col("__dt") <= pl.col("__pd")))
            .filter(pl.col("__dt").is_not_null())
            .drop("__pd")
        )
        _warn_response_data(scope, grps)

        anchors = scope.filter(pl.col("__v").is_in(rsp))
        later = scope.select(*grps, pl.col("__dt").alias("__dt_j"), pl.col("__v").alias("__v_j"))
        pairs = anchors.join(later, on=grps, how="inner", nulls_equal=True).filter(
            pl.col("__dt_j") > pl.col("__dt")
        )
        is_cr = pl.col("__v") == "CR"
        far = pl.col("__dt_j") >= pl.col("__dt") + pl.duration(days=confirmation_days)
        confirms = far & pl.when(is_cr).then(pl.col("__v_j") == "CR").otherwise(
            pl.col("__v_j").is_in(["CR", "PR"])
        )
        upper = pairs.filter(confirms).group_by("__row").agg(pl.col("__dt_j").min().alias("__up"))
        window = pairs.join(upper, on="__row").filter(pl.col("__dt_j") <= pl.col("__up"))

        v_j = pl.col("__v_j")
        n_ne = (v_j == "NE").sum()
        n_sd = (v_j == "SD").sum()
        allowed_pr = ["CR", "PR", "NE"] + (["SD"] if max_nr_sd != 0 else [])
        cr_ok = v_j.is_in(["CR", "NE"]).fill_null(False).all()
        pr_ok = v_j.is_in(allowed_pr).fill_null(False).all()
        no_pr_after_cr = (
            pl.col("__dt_j").filter(v_j == "CR").min() > pl.col("__dt_j").filter(v_j == "PR").max()
        ).fill_null(True)
        rule = pl.when(pl.col("__v").first() == "CR").then(cr_ok).otherwise(pr_ok & no_pr_after_cr)
        if max_nr_ne is not None:
            rule = rule & (n_ne <= max_nr_ne)
        if max_nr_sd is not None:
            rule = rule & (n_sd <= max_nr_sd)
        confirmed = (
            window.group_by("__row")
            .agg(rule.alias("__ok"))
            .filter(pl.col("__ok"))
            .select("__row", pl.lit(flag_value).alias(target))
        )
        out = df.drop(target, strict=False).join(confirmed, on="__row", how="left")
        return self._materialise_then(out.sort("__row").drop("__row"))

    # ------------------------------------------------------------------ #
    # 5. filter_pd — keep records up to first PD per group               #
    # ------------------------------------------------------------------ #

    def filter_pd(
        self,
        *,
        response_col: str,
        date_col: str,
        by: list[str] | None = None,
    ) -> Self:
        """Keep records up to and including the first PD per group.

        Groups without any PD observation are fully retained.
        Materialises the pipeline before filtering.

        Args:
            response_col: Column containing response text.
            date_col: Assessment date column.
            by: Partition columns (default ``["USUBJID"]``).

        Returns:
            Self: A fresh namespace wrapping the filtered frame.

        Examples:
            Filter to records up to first progressive disease::

                adrs = (
                    rs_raw.adam.onco
                    .filter_pd(response_col="OVRLRESP", date_col="ADT",
                               by=["USUBJID"])
                    .to_frame()
                )

        References:
            admiralonco ``filter_pd`` (pharmaverse): records up to and including the
            first progressive disease, as RECIST 1.1 uses for response endpoints.
        """
        grps = by or ["USUBJID"]
        df = self.to_frame()

        # First PD date per group
        pd_dates = (
            df.filter(pl.col(response_col) == "PD")
            .with_columns(pl.col(date_col).cast(pl.Date))
            .group_by(grps)
            .agg(pl.col(date_col).min().alias("_first_pd"))
        )

        joined = df.join(pd_dates, on=grps, how="left", nulls_equal=True)
        filtered = joined.filter(
            pl.col("_first_pd").is_null() | (pl.col(date_col).cast(pl.Date) <= pl.col("_first_pd"))
        ).drop("_first_pd")

        from fleet.core.lineage import record_row_step

        return record_row_step(self._materialise_then(filtered), "filter_pd", {})

aval_resp

aval_resp(target, *, source)

Map RECIST response text to numeric codes.

Mapping: CR=1, PR=2, SD=3, NON-CR/NON-PD=4, PD=5, NE=6, MISSING=7. Other/null values produce null.

Parameters:

Name Type Description Default
target str

Name of the output numeric column.

required
source str

Column containing RECIST response text.

required

Returns:

Name Type Description
Self Self

The namespace with target appended.

Examples:

Map overall response to a numeric code::

adrs = (
    rs_raw.adam.onco
    .aval_resp("AVAL", source="OVRLRESP")
    .to_frame()
)
References

RECIST 1.1: Eisenhauer EA et al. New response evaluation criteria in solid tumours. Eur J Cancer. 2009;45(2):228-247. The numeric ranks follow admiralonco aval_resp (pharmaverse).

Source code in src/fleet/adam/onco_namespace.py
def aval_resp(self, target: str, *, source: str) -> Self:
    """Map RECIST response text to numeric codes.

    Mapping: CR=1, PR=2, SD=3, NON-CR/NON-PD=4, PD=5, NE=6,
    MISSING=7.  Other/null values produce null.

    Args:
        target: Name of the output numeric column.
        source: Column containing RECIST response text.

    Returns:
        Self: The namespace with *target* appended.

    Examples:
        Map overall response to a numeric code::

            adrs = (
                rs_raw.adam.onco
                .aval_resp("AVAL", source="OVRLRESP")
                .to_frame()
            )

    References:
        RECIST 1.1: Eisenhauer EA et al. New response evaluation criteria in solid
        tumours. Eur J Cancer. 2009;45(2):228-247. The numeric ranks follow
        admiralonco ``aval_resp`` (pharmaverse).
    """
    return self._chain(_resp_num_expr(source).cast(pl.Float64).alias(target))

tumor_response_flag

tumor_response_flag(
    target, *, source, responses=None, flag_value="Y"
)

Flag records where source matches a target response.

Parameters:

Name Type Description Default
target str

Name of the output flag column.

required
source str

Column containing response text.

required
responses list[str] | None

Values to flag (default ["CR", "PR"]).

None
flag_value str

Value to assign for matching records (default "Y").

'Y'

Returns:

Name Type Description
Self Self

The namespace with target appended.

Examples:

Flag objective responders (CR or PR)::

adrs = (
    rs_raw.adam.onco
    .tumor_response_flag("RSPFL", source="OVRLRESP")
    .to_frame()
)
Source code in src/fleet/adam/onco_namespace.py
def tumor_response_flag(
    self,
    target: str,
    *,
    source: str,
    responses: list[str] | None = None,
    flag_value: str = "Y",
) -> Self:
    """Flag records where *source* matches a target response.

    Args:
        target: Name of the output flag column.
        source: Column containing response text.
        responses: Values to flag (default ``["CR", "PR"]``).
        flag_value: Value to assign for matching records (default ``"Y"``).

    Returns:
        Self: The namespace with *target* appended.

    Examples:
        Flag objective responders (CR or PR)::

            adrs = (
                rs_raw.adam.onco
                .tumor_response_flag("RSPFL", source="OVRLRESP")
                .to_frame()
            )
    """
    rsp = responses if responses is not None else ["CR", "PR"]
    return self._chain(
        pl.when(pl.col(source).is_in(rsp))
        .then(pl.lit(flag_value))
        .otherwise(pl.lit(None))
        .alias(target)
    )

best_overall_response

best_overall_response(
    target,
    *,
    source,
    date_col,
    reference_date,
    min_sd_days,
    by=None
)

Derive best overall response (BOR) per group.

The most favourable response is the one with the lowest RECIST rank (CR < PR < SD < NON-CR/NON-PD < PD < NE < MISSING). An SD or NON-CR/NON-PD assessed before reference_date + min_sd_days, or with a null date, counts as NE. The verb reads every record: it does not remove records after the first PD or after new anti-cancer therapy. Run filter_pd on a copy first and join BOR back.

Parameters:

Name Type Description Default
target str

Name of the output column.

required
source str

Column containing RECIST response text.

required
date_col str

Assessment date column (Date or ISO text).

required
reference_date str

Start of the SD minimum, for example RANDDT or TRTSDT.

required
min_sd_days int

Protocol minimum duration of SD, in days. 0 switches the rule off; the two date columns are then not read.

required
by list[str] | None

Partition columns (default ["USUBJID"]).

None

Returns:

Name Type Description
Self Self

The namespace with target appended.

Raises:

Type Description
DerivationError

If min_sd_days is negative.

Examples:

Derive BOR per subject up to the first PD, with a 42-day SD minimum::

bor = (
    adrs.adam.onco
    .filter_pd(response_col="OVRLRESP", date_col="ADT",
               by=["USUBJID"])
    .best_overall_response("BOR", source="OVRLRESP",
                           date_col="ADT",
                           reference_date="RANDDT",
                           min_sd_days=42, by=["USUBJID"])
    .to_frame()
    .select("USUBJID", "BOR")
    .unique()
)
adrs = adrs.join(bor, on="USUBJID", how="left")
References

RECIST 1.1 (Eisenhauer EA et al. Eur J Cancer. 2009;45(2):228-247), section 4.4: best overall response is the best response up to progression; section 4.4.3: SD must meet a protocol-specified minimum time from the reference date, else BOR is NE or PD. The ordering CR < PR < SD < NON-CR/NON-PD < PD < NE follows admiralonco derive_param_bor (ADT >= reference + minimum). This verb does not apply the confirmation requirement; see confirmed_response_flag. ADR-0031.

Source code in src/fleet/adam/onco_namespace.py
def best_overall_response(
    self,
    target: str,
    *,
    source: str,
    date_col: str,
    reference_date: str,
    min_sd_days: int,
    by: list[str] | None = None,
) -> Self:
    """Derive best overall response (BOR) per group.

    The most favourable response is the one with the lowest RECIST rank
    (CR < PR < SD < NON-CR/NON-PD < PD < NE < MISSING). An SD or
    NON-CR/NON-PD assessed before *reference_date* + *min_sd_days*, or
    with a null date, counts as NE. The verb reads every record: it does
    not remove records after the first PD or after new anti-cancer
    therapy. Run ``filter_pd`` on a copy first and join BOR back.

    Args:
        target: Name of the output column.
        source: Column containing RECIST response text.
        date_col: Assessment date column (Date or ISO text).
        reference_date: Start of the SD minimum, for example RANDDT or
            TRTSDT.
        min_sd_days: Protocol minimum duration of SD, in days. ``0``
            switches the rule off; the two date columns are then not read.
        by: Partition columns (default ``["USUBJID"]``).

    Returns:
        Self: The namespace with *target* appended.

    Raises:
        DerivationError: If *min_sd_days* is negative.

    Examples:
        Derive BOR per subject up to the first PD, with a 42-day SD minimum::

            bor = (
                adrs.adam.onco
                .filter_pd(response_col="OVRLRESP", date_col="ADT",
                           by=["USUBJID"])
                .best_overall_response("BOR", source="OVRLRESP",
                                       date_col="ADT",
                                       reference_date="RANDDT",
                                       min_sd_days=42, by=["USUBJID"])
                .to_frame()
                .select("USUBJID", "BOR")
                .unique()
            )
            adrs = adrs.join(bor, on="USUBJID", how="left")

    References:
        RECIST 1.1 (Eisenhauer EA et al. Eur J Cancer. 2009;45(2):228-247),
        section 4.4: best overall response is the best response up to
        progression; section 4.4.3: SD must meet a protocol-specified
        minimum time from the reference date, else BOR is NE or PD. The
        ordering CR < PR < SD < NON-CR/NON-PD < PD < NE follows admiralonco
        ``derive_param_bor`` (``ADT >= reference + minimum``). This verb does
        not apply the confirmation requirement; see
        ``confirmed_response_flag``. ADR-0031.
    """
    if min_sd_days < 0:
        raise DerivationError(
            f"best_overall_response(): min_sd_days={min_sd_days}. Give 0 or more days."
        )
    grps = by or ["USUBJID"]
    resp = pl.col(source)
    if min_sd_days:
        early = (
            pl.col(date_col).cast(pl.Date)
            < pl.col(reference_date).cast(pl.Date) + pl.duration(days=min_sd_days)
        ).fill_null(True)
        resp = (
            pl.when(resp.is_in(["SD", "NON-CR/NON-PD"]) & early)
            .then(pl.lit("NE"))
            .otherwise(resp)
        )
    best_num = resp.replace_strict(_RESP_TO_NUM, default=None).min().over(grps)
    return self._chain(_num_resp_expr(best_num).alias(target))

confirmed_response_flag

confirmed_response_flag(
    target,
    *,
    source,
    date_col,
    confirmation_days=28,
    responses=None,
    by=None,
    flag_value="Y",
    max_nr_ne=1,
    max_nr_sd=0
)

Flag each CR or PR record that a later assessment confirms.

A CR is confirmed by a CR at least confirmation_days later. A PR is confirmed by a CR or PR at least confirmation_days later. All assessments after the record, up to and including the first confirming one, must be CR or NE for a CR, and CR, PR, NE or SD for a PR, with at most max_nr_ne NE and at most max_nr_sd SD. For a PR, no PR may follow a CR in that window. Assessments after the first PD of a group are not read, so a filter_pd before the verb changes nothing. Only the confirmed record is flagged.

The verb warns, with the group values, when a CR is followed by a PR or SD, when two assessments of a group have the same date, and when source is null.

Parameters:

Name Type Description Default
target str

Name of the output flag column.

required
source str

Column containing response text.

required
date_col str

Assessment date column (Date or ISO text).

required
confirmation_days int

Minimum gap in days (default 28).

28
responses list[str] | None

Responses to confirm: ["CR", "PR"] (default) or a subset of it.

None
by list[str] | None

Partition columns (default ["USUBJID"]).

None
flag_value str

Value to assign (default "Y").

'Y'
max_nr_ne int | None

Maximum number of NE assessments in the window (default 1). None gives no limit.

1
max_nr_sd int | None

Maximum number of SD assessments in the window of a PR (default 0). None gives no limit. SD never confirms a CR.

0

Returns:

Name Type Description
Self Self

A fresh namespace wrapping the updated frame.

Raises:

Type Description
DerivationError

If responses holds a value other than CR or PR.

Examples:

Flag confirmed CR/PR responses::

adrs = (
    rs_raw.adam.onco
    .confirmed_response_flag(
        "CRSPFL", source="OVRLRESP", date_col="ADT",
        confirmation_days=28, by=["USUBJID"])
    .to_frame()
)
References

RECIST 1.1 (Eisenhauer EA et al. Eur J Cancer. 2009;45(2):228-247), section 4.4.3 Table 3, section 4.4.4 and the Appendix FAQ: a CR or PR is confirmed by a repeat assessment no less than 4 weeks later. The rules for NE and SD between the two follow the admiralonco crsp_y_cr and crsp_y_pr events (pharmaverse); SD between two PR is the accept_sd option of the deprecated derive_param_confirmed_resp. RECIST does not fix them: check the SAP. ADR-0030.

Source code in src/fleet/adam/onco_namespace.py
def confirmed_response_flag(
    self,
    target: str,
    *,
    source: str,
    date_col: str,
    confirmation_days: int = 28,
    responses: list[str] | None = None,
    by: list[str] | None = None,
    flag_value: str = "Y",
    max_nr_ne: int | None = 1,
    max_nr_sd: int | None = 0,
) -> Self:
    """Flag each CR or PR record that a later assessment confirms.

    A CR is confirmed by a CR at least *confirmation_days* later. A PR is
    confirmed by a CR or PR at least *confirmation_days* later. All
    assessments after the record, up to and including the first
    confirming one, must be CR or NE for a CR, and CR, PR, NE or SD for a
    PR, with at most *max_nr_ne* NE and at most *max_nr_sd* SD. For a PR,
    no PR may follow a CR in that window. Assessments after the first PD
    of a group are not read, so a ``filter_pd`` before the verb changes
    nothing. Only the confirmed record is flagged.

    The verb warns, with the group values, when a CR is followed by a PR
    or SD, when two assessments of a group have the same date, and when
    *source* is null.

    Args:
        target: Name of the output flag column.
        source: Column containing response text.
        date_col: Assessment date column (Date or ISO text).
        confirmation_days: Minimum gap in days (default ``28``).
        responses: Responses to confirm: ``["CR", "PR"]`` (default) or a
            subset of it.
        by: Partition columns (default ``["USUBJID"]``).
        flag_value: Value to assign (default ``"Y"``).
        max_nr_ne: Maximum number of NE assessments in the window
            (default ``1``). ``None`` gives no limit.
        max_nr_sd: Maximum number of SD assessments in the window of a
            PR (default ``0``). ``None`` gives no limit. SD never
            confirms a CR.

    Returns:
        Self: A fresh namespace wrapping the updated frame.

    Raises:
        DerivationError: If *responses* holds a value other than CR or PR.

    Examples:
        Flag confirmed CR/PR responses::

            adrs = (
                rs_raw.adam.onco
                .confirmed_response_flag(
                    "CRSPFL", source="OVRLRESP", date_col="ADT",
                    confirmation_days=28, by=["USUBJID"])
                .to_frame()
            )

    References:
        RECIST 1.1 (Eisenhauer EA et al. Eur J Cancer. 2009;45(2):228-247),
        section 4.4.3 Table 3, section 4.4.4 and the Appendix FAQ: a CR or PR
        is confirmed by a repeat assessment no less than 4 weeks later. The
        rules for NE and SD between the two follow the admiralonco
        ``crsp_y_cr`` and ``crsp_y_pr`` events (pharmaverse); SD between
        two PR is the ``accept_sd`` option of the deprecated
        ``derive_param_confirmed_resp``. RECIST does not fix them: check the
        SAP. ADR-0030.
    """
    rsp = responses if responses is not None else ["CR", "PR"]
    unknown = sorted(set(rsp) - {"CR", "PR"})
    if unknown or not rsp:
        raise DerivationError(
            f"confirmed_response_flag(): responses={rsp!r}. Only CR and PR can be "
            "confirmed; give ['CR', 'PR'] or a subset."
        )
    grps = by or ["USUBJID"]
    df = self.to_frame().with_row_index("__row")
    work = df.select(
        "__row",
        *grps,
        pl.col(date_col).cast(pl.Date).alias("__dt"),
        pl.col(source).alias("__v"),
    )
    first_pd = (
        work.filter(pl.col("__v") == "PD")
        .group_by(grps)
        .agg(pl.col("__dt").min().alias("__pd"))
    )
    scope = (
        work.join(first_pd, on=grps, how="left", nulls_equal=True)
        .filter(pl.col("__pd").is_null() | (pl.col("__dt") <= pl.col("__pd")))
        .filter(pl.col("__dt").is_not_null())
        .drop("__pd")
    )
    _warn_response_data(scope, grps)

    anchors = scope.filter(pl.col("__v").is_in(rsp))
    later = scope.select(*grps, pl.col("__dt").alias("__dt_j"), pl.col("__v").alias("__v_j"))
    pairs = anchors.join(later, on=grps, how="inner", nulls_equal=True).filter(
        pl.col("__dt_j") > pl.col("__dt")
    )
    is_cr = pl.col("__v") == "CR"
    far = pl.col("__dt_j") >= pl.col("__dt") + pl.duration(days=confirmation_days)
    confirms = far & pl.when(is_cr).then(pl.col("__v_j") == "CR").otherwise(
        pl.col("__v_j").is_in(["CR", "PR"])
    )
    upper = pairs.filter(confirms).group_by("__row").agg(pl.col("__dt_j").min().alias("__up"))
    window = pairs.join(upper, on="__row").filter(pl.col("__dt_j") <= pl.col("__up"))

    v_j = pl.col("__v_j")
    n_ne = (v_j == "NE").sum()
    n_sd = (v_j == "SD").sum()
    allowed_pr = ["CR", "PR", "NE"] + (["SD"] if max_nr_sd != 0 else [])
    cr_ok = v_j.is_in(["CR", "NE"]).fill_null(False).all()
    pr_ok = v_j.is_in(allowed_pr).fill_null(False).all()
    no_pr_after_cr = (
        pl.col("__dt_j").filter(v_j == "CR").min() > pl.col("__dt_j").filter(v_j == "PR").max()
    ).fill_null(True)
    rule = pl.when(pl.col("__v").first() == "CR").then(cr_ok).otherwise(pr_ok & no_pr_after_cr)
    if max_nr_ne is not None:
        rule = rule & (n_ne <= max_nr_ne)
    if max_nr_sd is not None:
        rule = rule & (n_sd <= max_nr_sd)
    confirmed = (
        window.group_by("__row")
        .agg(rule.alias("__ok"))
        .filter(pl.col("__ok"))
        .select("__row", pl.lit(flag_value).alias(target))
    )
    out = df.drop(target, strict=False).join(confirmed, on="__row", how="left")
    return self._materialise_then(out.sort("__row").drop("__row"))

filter_pd

filter_pd(*, response_col, date_col, by=None)

Keep records up to and including the first PD per group.

Groups without any PD observation are fully retained. Materialises the pipeline before filtering.

Parameters:

Name Type Description Default
response_col str

Column containing response text.

required
date_col str

Assessment date column.

required
by list[str] | None

Partition columns (default ["USUBJID"]).

None

Returns:

Name Type Description
Self Self

A fresh namespace wrapping the filtered frame.

Examples:

Filter to records up to first progressive disease::

adrs = (
    rs_raw.adam.onco
    .filter_pd(response_col="OVRLRESP", date_col="ADT",
               by=["USUBJID"])
    .to_frame()
)
References

admiralonco filter_pd (pharmaverse): records up to and including the first progressive disease, as RECIST 1.1 uses for response endpoints.

Source code in src/fleet/adam/onco_namespace.py
def filter_pd(
    self,
    *,
    response_col: str,
    date_col: str,
    by: list[str] | None = None,
) -> Self:
    """Keep records up to and including the first PD per group.

    Groups without any PD observation are fully retained.
    Materialises the pipeline before filtering.

    Args:
        response_col: Column containing response text.
        date_col: Assessment date column.
        by: Partition columns (default ``["USUBJID"]``).

    Returns:
        Self: A fresh namespace wrapping the filtered frame.

    Examples:
        Filter to records up to first progressive disease::

            adrs = (
                rs_raw.adam.onco
                .filter_pd(response_col="OVRLRESP", date_col="ADT",
                           by=["USUBJID"])
                .to_frame()
            )

    References:
        admiralonco ``filter_pd`` (pharmaverse): records up to and including the
        first progressive disease, as RECIST 1.1 uses for response endpoints.
    """
    grps = by or ["USUBJID"]
    df = self.to_frame()

    # First PD date per group
    pd_dates = (
        df.filter(pl.col(response_col) == "PD")
        .with_columns(pl.col(date_col).cast(pl.Date))
        .group_by(grps)
        .agg(pl.col(date_col).min().alias("_first_pd"))
    )

    joined = df.join(pd_dates, on=grps, how="left", nulls_equal=True)
    filtered = joined.filter(
        pl.col("_first_pd").is_null() | (pl.col(date_col).cast(pl.Date) <= pl.col("_first_pd"))
    ).drop("_first_pd")

    from fleet.core.lineage import record_row_step

    return record_row_step(self._materialise_then(filtered), "filter_pd", {})

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

Ophthalmology — df.adam.ophtha

fleet.adam.OphthaNamespace

Bases: SharedADaMVerbsMixin

Immutable pipeline builder for ADaM ophthalmology derivations.

Inherits shared verbs from SharedADaMVerbsMixin.

Source code in src/fleet/adam/ophtha_namespace.py
class OphthaNamespace(SharedADaMVerbsMixin):
    """
    Immutable pipeline builder for ADaM ophthalmology derivations.

    Inherits shared verbs from ``SharedADaMVerbsMixin``.
    """

    # ------------------------------------------------------------------ #
    # 1. etdrs_to_logmar — ETDRS score → LogMAR                          #
    # ------------------------------------------------------------------ #

    def etdrs_to_logmar(
        self,
        target: str,
        *,
        source: str,
        round_digits: int | None = 4,
    ) -> Self:
        """Convert an ETDRS letter score to LogMAR units.

        Formula (Beck et al.): ``logMAR = -0.02 × ETDRS + 1.7``.

        Args:
            target: Name of the output column.
            source: Column containing the ETDRS letter score.
            round_digits: Decimal places to round to (default ``4``).

        Returns:
            Self: The namespace with *target* appended.

        Examples:
            Convert ETDRS to LogMAR::

                adbcva = (
                    bcva_raw.adam.ophtha
                    .etdrs_to_logmar("LOGMAR", source="ETDRS")
                    .to_frame()
                )

        References:
            Beck RW et al. A computerized method of visual acuity testing. Am J
            Ophthalmol. 2003;135(2):194-205. admiralophtha
            ``convert_etdrs_to_logmar`` (pharmaverse) applies the same formula.
        """
        expr = -0.02 * pl.col(source) + 1.7
        if round_digits is not None:
            expr = expr.round(round_digits)
        return self._chain(expr.alias(target))

    # ------------------------------------------------------------------ #
    # 2. logmar_to_etdrs — LogMAR → ETDRS                                #
    # ------------------------------------------------------------------ #

    def logmar_to_etdrs(
        self,
        target: str,
        *,
        source: str,
        round_digits: int | None = 1,
    ) -> Self:
        """Convert a LogMAR value back to ETDRS letter score.

        Inverse of the Beck formula: ``ETDRS = (1.7 - logMAR) / 0.02``.

        Args:
            target: Name of the output column.
            source: Column containing the LogMAR value.
            round_digits: Decimal places to round to (default ``1``).

        Returns:
            Self: The namespace with *target* appended.

        Examples:
            Convert LogMAR back to ETDRS::

                adbcva = (
                    bcva_raw.adam.ophtha
                    .logmar_to_etdrs("ETDRS", source="LOGMAR")
                    .to_frame()
                )

        References:
            Beck RW et al. A computerized method of visual acuity testing. Am J
            Ophthalmol. 2003;135(2):194-205. admiralophtha
            ``convert_logmar_to_etdrs`` (pharmaverse) applies the same formula.
        """
        expr = (1.7 - pl.col(source)) / 0.02
        if round_digits is not None:
            expr = expr.round(round_digits)
        return self._chain(expr.alias(target))

    # ------------------------------------------------------------------ #
    # 3. study_eye — derive STUDYEYE from SC FOCID                       #
    # ------------------------------------------------------------------ #

    def study_eye(
        self,
        target: str,
        *,
        source: str,
    ) -> Self:
        """Map SC FOCID laterality codes to study eye labels.

        OS → LEFT, OD → RIGHT, OU → BILATERAL, other → null.

        Args:
            target: Name of the output column.
            source: Column containing the FOCID code.

        Returns:
            Self: The namespace with *target* appended.

        Examples:
            Derive study eye from SC domain::

                adbcva = (
                    bcva_raw.adam.ophtha
                    .study_eye("STUDYEYE", source="SCSTRESC")
                    .to_frame()
                )

        References:
            Ophthalmic convention: OD = oculus dexter (right), OS = oculus sinister
            (left), OU = oculus uterque (both). CDISC SDTM controlled terminology for
            laterality uses LEFT, RIGHT and BILATERAL. admiralophtha
            ``derive_var_studyeye`` (pharmaverse) applies the same mapping.
        """
        return self._chain(
            pl.when(pl.col(source).str.to_uppercase() == "OS")
            .then(pl.lit("LEFT"))
            .when(pl.col(source).str.to_uppercase() == "OD")
            .then(pl.lit("RIGHT"))
            .when(pl.col(source).str.to_uppercase() == "OU")
            .then(pl.lit("BILATERAL"))
            .otherwise(pl.lit(None))
            .alias(target)
        )

    # ------------------------------------------------------------------ #
    # 4. affected_eye — derive AFEYE from laterality and study eye        #
    # ------------------------------------------------------------------ #

    def affected_eye(
        self,
        target: str,
        *,
        loc_col: str,
        lat_col: str,
        study_eye_col: str = "STUDYEYE",
        loc_values: list[str] | None = None,
    ) -> Self:
        """Derive Affected Eye (AFEYE) from laterality and study eye.

        Maps laterality/study-eye combinations to ``"Study Eye"``,
        ``"Fellow Eye"``, or ``"Both Eyes"``.

        Args:
            target: Name of the output column.
            loc_col: Column containing the anatomical location.
            lat_col: Column containing the laterality.
            study_eye_col: Study eye column (default ``"STUDYEYE"``).
            loc_values: Valid location values (default ``["EYE"]``).

        Returns:
            Self: The namespace with *target* appended.

        Examples:
            Derive AFEYE for AE records::

                adae = (
                    ae_raw.adam.ophtha
                    .affected_eye("AFEYE", loc_col="AELOC",
                                  lat_col="AELAT")
                    .to_frame()
                )

        References:
            admiralophtha ``derive_var_afeye`` (pharmaverse): the Study Eye, Fellow
            Eye and Both Eyes rule from laterality, location and study eye.
        """
        locs = [v.upper() for v in (loc_values or ["EYE"])]
        valid_lat = ["LEFT", "RIGHT", "BILATERAL"]

        seye_up = pl.col(study_eye_col).str.to_uppercase()
        lat_up = pl.col(lat_col).str.to_uppercase()
        loc_up = pl.col(loc_col).str.to_uppercase()

        return self._chain(
            pl.when(
                seye_up.is_in(["LEFT", "RIGHT", "BILATERAL"])
                & lat_up.eq(pl.lit("BILATERAL"))
                & loc_up.is_in(locs)
            )
            .then(pl.lit("Both Eyes"))
            .when(seye_up.eq(pl.lit("BILATERAL")) & lat_up.is_in(valid_lat) & loc_up.is_in(locs))
            .then(pl.lit("Study Eye"))
            .when(
                lat_up.eq(seye_up)
                & seye_up.is_in(["LEFT", "RIGHT", "BILATERAL"])
                & lat_up.is_in(valid_lat)
                & loc_up.is_in(locs)
            )
            .then(pl.lit("Study Eye"))
            .when(
                lat_up.ne(seye_up)
                & seye_up.is_in(["LEFT", "RIGHT", "BILATERAL"])
                & lat_up.is_in(valid_lat)
                & loc_up.is_in(locs)
            )
            .then(pl.lit("Fellow Eye"))
            .otherwise(pl.lit(None))
            .alias(target)
        )

    # ------------------------------------------------------------------ #
    # 5. bcva_criterion — flag records meeting a BCVA threshold           #
    # ------------------------------------------------------------------ #

    def bcva_criterion(
        self,
        target: str,
        *,
        value_col: str,
        threshold: float,
        direction: str = "ge",
        flag_value: str = "Y",
    ) -> Self:
        """Flag records meeting a BCVA criterion threshold.

        Args:
            target: Name of the output flag column.
            value_col: Column containing the BCVA score.
            threshold: Numeric threshold value.
            direction: Comparison — ``"ge"`` (≥), ``"gt"`` (>), ``"le"`` (≤),
                ``"lt"`` (<).
            flag_value: Value to assign (default ``"Y"``).

        Returns:
            Self: The namespace with *target* appended.

        Examples:
            Flag records with ETDRS >= 70::

                adbcva = (
                    bcva_raw.adam.ophtha
                    .bcva_criterion("BCVACR1FL", value_col="ETDRS",
                                    threshold=70, direction="ge")
                    .to_frame()
                )
        """
        direction = direction.lower()
        col = pl.col(value_col)
        if direction == "ge":
            cond = col >= threshold
        elif direction == "gt":
            cond = col > threshold
        elif direction == "le":
            cond = col <= threshold
        elif direction == "lt":
            cond = col < threshold
        else:
            raise DerivationError(f"direction must be one of ge/gt/le/lt, got '{direction}'.")

        return self._chain(
            pl.when(cond).then(pl.lit(flag_value)).otherwise(pl.lit(None)).alias(target)
        )

etdrs_to_logmar

etdrs_to_logmar(target, *, source, round_digits=4)

Convert an ETDRS letter score to LogMAR units.

Formula (Beck et al.): logMAR = -0.02 × ETDRS + 1.7.

Parameters:

Name Type Description Default
target str

Name of the output column.

required
source str

Column containing the ETDRS letter score.

required
round_digits int | None

Decimal places to round to (default 4).

4

Returns:

Name Type Description
Self Self

The namespace with target appended.

Examples:

Convert ETDRS to LogMAR::

adbcva = (
    bcva_raw.adam.ophtha
    .etdrs_to_logmar("LOGMAR", source="ETDRS")
    .to_frame()
)
References

Beck RW et al. A computerized method of visual acuity testing. Am J Ophthalmol. 2003;135(2):194-205. admiralophtha convert_etdrs_to_logmar (pharmaverse) applies the same formula.

Source code in src/fleet/adam/ophtha_namespace.py
def etdrs_to_logmar(
    self,
    target: str,
    *,
    source: str,
    round_digits: int | None = 4,
) -> Self:
    """Convert an ETDRS letter score to LogMAR units.

    Formula (Beck et al.): ``logMAR = -0.02 × ETDRS + 1.7``.

    Args:
        target: Name of the output column.
        source: Column containing the ETDRS letter score.
        round_digits: Decimal places to round to (default ``4``).

    Returns:
        Self: The namespace with *target* appended.

    Examples:
        Convert ETDRS to LogMAR::

            adbcva = (
                bcva_raw.adam.ophtha
                .etdrs_to_logmar("LOGMAR", source="ETDRS")
                .to_frame()
            )

    References:
        Beck RW et al. A computerized method of visual acuity testing. Am J
        Ophthalmol. 2003;135(2):194-205. admiralophtha
        ``convert_etdrs_to_logmar`` (pharmaverse) applies the same formula.
    """
    expr = -0.02 * pl.col(source) + 1.7
    if round_digits is not None:
        expr = expr.round(round_digits)
    return self._chain(expr.alias(target))

logmar_to_etdrs

logmar_to_etdrs(target, *, source, round_digits=1)

Convert a LogMAR value back to ETDRS letter score.

Inverse of the Beck formula: ETDRS = (1.7 - logMAR) / 0.02.

Parameters:

Name Type Description Default
target str

Name of the output column.

required
source str

Column containing the LogMAR value.

required
round_digits int | None

Decimal places to round to (default 1).

1

Returns:

Name Type Description
Self Self

The namespace with target appended.

Examples:

Convert LogMAR back to ETDRS::

adbcva = (
    bcva_raw.adam.ophtha
    .logmar_to_etdrs("ETDRS", source="LOGMAR")
    .to_frame()
)
References

Beck RW et al. A computerized method of visual acuity testing. Am J Ophthalmol. 2003;135(2):194-205. admiralophtha convert_logmar_to_etdrs (pharmaverse) applies the same formula.

Source code in src/fleet/adam/ophtha_namespace.py
def logmar_to_etdrs(
    self,
    target: str,
    *,
    source: str,
    round_digits: int | None = 1,
) -> Self:
    """Convert a LogMAR value back to ETDRS letter score.

    Inverse of the Beck formula: ``ETDRS = (1.7 - logMAR) / 0.02``.

    Args:
        target: Name of the output column.
        source: Column containing the LogMAR value.
        round_digits: Decimal places to round to (default ``1``).

    Returns:
        Self: The namespace with *target* appended.

    Examples:
        Convert LogMAR back to ETDRS::

            adbcva = (
                bcva_raw.adam.ophtha
                .logmar_to_etdrs("ETDRS", source="LOGMAR")
                .to_frame()
            )

    References:
        Beck RW et al. A computerized method of visual acuity testing. Am J
        Ophthalmol. 2003;135(2):194-205. admiralophtha
        ``convert_logmar_to_etdrs`` (pharmaverse) applies the same formula.
    """
    expr = (1.7 - pl.col(source)) / 0.02
    if round_digits is not None:
        expr = expr.round(round_digits)
    return self._chain(expr.alias(target))

study_eye

study_eye(target, *, source)

Map SC FOCID laterality codes to study eye labels.

OS → LEFT, OD → RIGHT, OU → BILATERAL, other → null.

Parameters:

Name Type Description Default
target str

Name of the output column.

required
source str

Column containing the FOCID code.

required

Returns:

Name Type Description
Self Self

The namespace with target appended.

Examples:

Derive study eye from SC domain::

adbcva = (
    bcva_raw.adam.ophtha
    .study_eye("STUDYEYE", source="SCSTRESC")
    .to_frame()
)
References

Ophthalmic convention: OD = oculus dexter (right), OS = oculus sinister (left), OU = oculus uterque (both). CDISC SDTM controlled terminology for laterality uses LEFT, RIGHT and BILATERAL. admiralophtha derive_var_studyeye (pharmaverse) applies the same mapping.

Source code in src/fleet/adam/ophtha_namespace.py
def study_eye(
    self,
    target: str,
    *,
    source: str,
) -> Self:
    """Map SC FOCID laterality codes to study eye labels.

    OS → LEFT, OD → RIGHT, OU → BILATERAL, other → null.

    Args:
        target: Name of the output column.
        source: Column containing the FOCID code.

    Returns:
        Self: The namespace with *target* appended.

    Examples:
        Derive study eye from SC domain::

            adbcva = (
                bcva_raw.adam.ophtha
                .study_eye("STUDYEYE", source="SCSTRESC")
                .to_frame()
            )

    References:
        Ophthalmic convention: OD = oculus dexter (right), OS = oculus sinister
        (left), OU = oculus uterque (both). CDISC SDTM controlled terminology for
        laterality uses LEFT, RIGHT and BILATERAL. admiralophtha
        ``derive_var_studyeye`` (pharmaverse) applies the same mapping.
    """
    return self._chain(
        pl.when(pl.col(source).str.to_uppercase() == "OS")
        .then(pl.lit("LEFT"))
        .when(pl.col(source).str.to_uppercase() == "OD")
        .then(pl.lit("RIGHT"))
        .when(pl.col(source).str.to_uppercase() == "OU")
        .then(pl.lit("BILATERAL"))
        .otherwise(pl.lit(None))
        .alias(target)
    )

affected_eye

affected_eye(
    target,
    *,
    loc_col,
    lat_col,
    study_eye_col="STUDYEYE",
    loc_values=None
)

Derive Affected Eye (AFEYE) from laterality and study eye.

Maps laterality/study-eye combinations to "Study Eye", "Fellow Eye", or "Both Eyes".

Parameters:

Name Type Description Default
target str

Name of the output column.

required
loc_col str

Column containing the anatomical location.

required
lat_col str

Column containing the laterality.

required
study_eye_col str

Study eye column (default "STUDYEYE").

'STUDYEYE'
loc_values list[str] | None

Valid location values (default ["EYE"]).

None

Returns:

Name Type Description
Self Self

The namespace with target appended.

Examples:

Derive AFEYE for AE records::

adae = (
    ae_raw.adam.ophtha
    .affected_eye("AFEYE", loc_col="AELOC",
                  lat_col="AELAT")
    .to_frame()
)
References

admiralophtha derive_var_afeye (pharmaverse): the Study Eye, Fellow Eye and Both Eyes rule from laterality, location and study eye.

Source code in src/fleet/adam/ophtha_namespace.py
def affected_eye(
    self,
    target: str,
    *,
    loc_col: str,
    lat_col: str,
    study_eye_col: str = "STUDYEYE",
    loc_values: list[str] | None = None,
) -> Self:
    """Derive Affected Eye (AFEYE) from laterality and study eye.

    Maps laterality/study-eye combinations to ``"Study Eye"``,
    ``"Fellow Eye"``, or ``"Both Eyes"``.

    Args:
        target: Name of the output column.
        loc_col: Column containing the anatomical location.
        lat_col: Column containing the laterality.
        study_eye_col: Study eye column (default ``"STUDYEYE"``).
        loc_values: Valid location values (default ``["EYE"]``).

    Returns:
        Self: The namespace with *target* appended.

    Examples:
        Derive AFEYE for AE records::

            adae = (
                ae_raw.adam.ophtha
                .affected_eye("AFEYE", loc_col="AELOC",
                              lat_col="AELAT")
                .to_frame()
            )

    References:
        admiralophtha ``derive_var_afeye`` (pharmaverse): the Study Eye, Fellow
        Eye and Both Eyes rule from laterality, location and study eye.
    """
    locs = [v.upper() for v in (loc_values or ["EYE"])]
    valid_lat = ["LEFT", "RIGHT", "BILATERAL"]

    seye_up = pl.col(study_eye_col).str.to_uppercase()
    lat_up = pl.col(lat_col).str.to_uppercase()
    loc_up = pl.col(loc_col).str.to_uppercase()

    return self._chain(
        pl.when(
            seye_up.is_in(["LEFT", "RIGHT", "BILATERAL"])
            & lat_up.eq(pl.lit("BILATERAL"))
            & loc_up.is_in(locs)
        )
        .then(pl.lit("Both Eyes"))
        .when(seye_up.eq(pl.lit("BILATERAL")) & lat_up.is_in(valid_lat) & loc_up.is_in(locs))
        .then(pl.lit("Study Eye"))
        .when(
            lat_up.eq(seye_up)
            & seye_up.is_in(["LEFT", "RIGHT", "BILATERAL"])
            & lat_up.is_in(valid_lat)
            & loc_up.is_in(locs)
        )
        .then(pl.lit("Study Eye"))
        .when(
            lat_up.ne(seye_up)
            & seye_up.is_in(["LEFT", "RIGHT", "BILATERAL"])
            & lat_up.is_in(valid_lat)
            & loc_up.is_in(locs)
        )
        .then(pl.lit("Fellow Eye"))
        .otherwise(pl.lit(None))
        .alias(target)
    )

bcva_criterion

bcva_criterion(
    target,
    *,
    value_col,
    threshold,
    direction="ge",
    flag_value="Y"
)

Flag records meeting a BCVA criterion threshold.

Parameters:

Name Type Description Default
target str

Name of the output flag column.

required
value_col str

Column containing the BCVA score.

required
threshold float

Numeric threshold value.

required
direction str

Comparison — "ge" (≥), "gt" (>), "le" (≤), "lt" (<).

'ge'
flag_value str

Value to assign (default "Y").

'Y'

Returns:

Name Type Description
Self Self

The namespace with target appended.

Examples:

Flag records with ETDRS >= 70::

adbcva = (
    bcva_raw.adam.ophtha
    .bcva_criterion("BCVACR1FL", value_col="ETDRS",
                    threshold=70, direction="ge")
    .to_frame()
)
Source code in src/fleet/adam/ophtha_namespace.py
def bcva_criterion(
    self,
    target: str,
    *,
    value_col: str,
    threshold: float,
    direction: str = "ge",
    flag_value: str = "Y",
) -> Self:
    """Flag records meeting a BCVA criterion threshold.

    Args:
        target: Name of the output flag column.
        value_col: Column containing the BCVA score.
        threshold: Numeric threshold value.
        direction: Comparison — ``"ge"`` (≥), ``"gt"`` (>), ``"le"`` (≤),
            ``"lt"`` (<).
        flag_value: Value to assign (default ``"Y"``).

    Returns:
        Self: The namespace with *target* appended.

    Examples:
        Flag records with ETDRS >= 70::

            adbcva = (
                bcva_raw.adam.ophtha
                .bcva_criterion("BCVACR1FL", value_col="ETDRS",
                                threshold=70, direction="ge")
                .to_frame()
            )
    """
    direction = direction.lower()
    col = pl.col(value_col)
    if direction == "ge":
        cond = col >= threshold
    elif direction == "gt":
        cond = col > threshold
    elif direction == "le":
        cond = col <= threshold
    elif direction == "lt":
        cond = col < threshold
    else:
        raise DerivationError(f"direction must be one of ge/gt/le/lt, got '{direction}'.")

    return self._chain(
        pl.when(cond).then(pl.lit(flag_value)).otherwise(pl.lit(None)).alias(target)
    )

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

Pediatrics — df.adam.peds

fleet.adam.PedsNamespace

Bases: SharedADaMVerbsMixin

Immutable pipeline builder for paediatric ADaM derivations.

Inherits shared verbs from SharedADaMVerbsMixin.

Source code in src/fleet/adam/peds_namespace.py
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
class PedsNamespace(SharedADaMVerbsMixin):
    """
    Immutable pipeline builder for paediatric ADaM derivations.

    Inherits shared verbs from ``SharedADaMVerbsMixin``.
    """

    def _age_in_days(self, verb: str, birth_date: str, analysis_date: str) -> pl.Expr:
        """Days from *birth_date* to *analysis_date*; ``--DTC`` text by its date, a number raises."""
        schema = self._lazy.collect_schema()
        analysis, birth = (
            to_day(pl.col(c), schema.get(c), verb=verb).cast(pl.Date)
            for c in (analysis_date, birth_date)
        )
        return (analysis - birth).dt.total_days()

    # ------------------------------------------------------------------ #
    # 1. age_days — age in whole days                                     #
    # ------------------------------------------------------------------ #

    def age_days(
        self,
        target: str,
        *,
        birth_date: str,
        analysis_date: str,
    ) -> Self:
        """Compute age in whole days.

        Args:
            target: Name of the output column.
            birth_date: Column containing the date of birth.
            analysis_date: Column containing the reference date.

        Returns:
            Self: The namespace with *target* appended.

        Examples:
            Derive age in days from birth and reference dates::

                adsl = (
                    dm_raw.adam.peds
                    .age_days("AGEDAYS", birth_date="BRTHDT",
                              analysis_date="RFSTDTC")
                    .to_frame()
                )
        """
        expr = self._age_in_days("age_days", birth_date, analysis_date).cast(pl.Int64).alias(target)
        return self._chain(expr)

    # ------------------------------------------------------------------ #
    # 2. age_months — age in whole calendar months                        #
    # ------------------------------------------------------------------ #

    def age_months(
        self,
        target: str,
        *,
        birth_date: str,
        analysis_date: str,
    ) -> Self:
        """Compute age in whole months (floor of days / 30.4375).

        Args:
            target: Name of the output column.
            birth_date: Column containing the date of birth.
            analysis_date: Column containing the reference date.

        Returns:
            Self: The namespace with *target* appended.

        Examples:
            Derive age in months::

                adsl = (
                    dm_raw.adam.peds
                    .age_months("AGEMOS", birth_date="BRTHDT",
                                analysis_date="RFSTDTC")
                    .to_frame()
                )

        References:
            admiral ``derive_vars_duration`` (pharmaverse): one month = 30.4375 days
            (365.25 / 12). A month of 30 days gives a different answer.
        """
        days = self._age_in_days("age_months", birth_date, analysis_date)
        expr = (days / 30.4375).floor().cast(pl.Int64).alias(target)
        return self._chain(expr)

    # ------------------------------------------------------------------ #
    # 3. age_years — age in completed years                               #
    # ------------------------------------------------------------------ #

    def age_years(
        self,
        target: str,
        *,
        birth_date: str,
        analysis_date: str,
        unit: Literal["years", "decimal"] = "years",
        round_digits: int | None = None,
    ) -> Self:
        """Compute age from two date columns, in completed years by default.

        Same rule as ``adsl.age_from_dates``: ``unit="years"`` gives whole
        completed years (Int64), so a child is 4 on the day before the 5th
        birthday.  A 29 February birthday is reached on 1 March in a non-leap
        year; a reference date before birth gives a negative age.
        ``unit="decimal"`` gives days / 365.25 at full precision.

        Args:
            target: Name of the output column.
            birth_date: Column containing the date of birth.
            analysis_date: Column containing the reference date.
            unit: ``"years"`` (default) or ``"decimal"``.
            round_digits: Decimal places for ``unit="decimal"``, rounded as
                SAS ``ROUND``.  Default ``None``: no rounding.

        Returns:
            Self: The namespace with *target* appended.

        Raises:
            VerbUsageError: When *round_digits* is given with
                ``unit="years"``, or *unit* is unknown.

        Examples:
            Derive age in completed years::

                adsl = (
                    dm_raw.adam.peds
                    .age_years("AAGE", birth_date="BRTHDT",
                               analysis_date="RFSTDT")
                    .to_frame()
                )

        References:
            admiral ``derive_vars_aage`` (pharmaverse) and SAS
            ``FLOOR(YRDIF(BRTHDT, RFSTDT, 'AGE'))``: completed years. ICH E11 age
            bands use completed years. Decimal: one year = 365.25 days. ADR-0025.
        """
        from fleet.adam.utils import age_between

        schema = self._lazy.collect_schema()
        reference, birth = (
            to_day(pl.col(c), schema.get(c), verb="age_years").cast(pl.Date)
            for c in (analysis_date, birth_date)
        )
        expr = age_between(birth, reference, unit=unit, round_digits=round_digits, verb="age_years")
        return self._chain(expr.alias(target))

    # ------------------------------------------------------------------ #
    # 4. corrected_age — gestational-corrected age for preterm infants    #
    # ------------------------------------------------------------------ #

    def corrected_age(
        self,
        target: str,
        *,
        age_days_col: str,
        gestational_weeks_col: str,
        term_weeks: int = 40,
    ) -> Self:
        """Compute gestational-corrected age in decimal years.

        Corrected age = chronological age − (term_weeks − gestational_weeks) / 52.18.
        No correction when gestational weeks >= *term_weeks*.  A null or NaN
        gestational age gives a null result; if the SAP assumes term birth,
        fill the column with *term_weeks* before the call.

        Args:
            target: Name of the output column.
            age_days_col: Column containing age in days.
            gestational_weeks_col: Column containing gestational age in weeks.
            term_weeks: Full-term threshold (default ``40``).

        Returns:
            Self: The namespace with *target* appended.

        Examples:
            Derive corrected age for preterm infants::

                adsl = (
                    dm_raw.adam.peds
                    .corrected_age("CORAGE", age_days_col="AGEDAYS",
                                   gestational_weeks_col="GESTAG")
                    .to_frame()
                )

        References:
            American Academy of Pediatrics, Committee on Fetus and Newborn. Age
            terminology during the perinatal period. Pediatrics. 2004;114(5):1362-1364:
            corrected age = chronological age minus the weeks born before 40 weeks.
            52.18 weeks per year = 365.25 / 7.
        """
        ga = pl.col(gestational_weeks_col).cast(pl.Float64).fill_nan(None)
        prematurity_years = pl.when(ga >= term_weeks).then(0.0).otherwise((term_weeks - ga) / 52.18)
        chron_age_years = pl.col(age_days_col) / 365.25
        return self._chain((chron_age_years - prematurity_years).round(4).alias(target))

    # ------------------------------------------------------------------ #
    # 5. prematurity_flag — flag infants born prematurely                 #
    # ------------------------------------------------------------------ #

    def prematurity_flag(
        self,
        target: str,
        *,
        gestational_weeks_col: str,
        threshold: int = 37,
        flag_value: str = "Y",
    ) -> Self:
        """Flag infants born before *threshold* gestational weeks.

        Default threshold of 37 weeks matches the clinical definition of
        prematurity.

        Args:
            target: Name of the output flag column.
            gestational_weeks_col: Column containing gestational age in weeks.
            threshold: Weeks below which prematurity is flagged (default ``37``).
            flag_value: Value to assign (default ``"Y"``).

        Returns:
            Self: The namespace with *target* appended.

        Examples:
            Derive prematurity flag::

                adsl = (
                    dm_raw.adam.peds
                    .prematurity_flag("PREMFL",
                                     gestational_weeks_col="GESTAG")
                    .to_frame()
                )

        References:
            WHO: preterm birth is birth before 37 completed weeks of gestation
            (ICD-10 P07; WHO preterm birth fact sheet).
        """
        return self._chain(
            pl.when(pl.col(gestational_weeks_col) < threshold)
            .then(pl.lit(flag_value))
            .otherwise(pl.lit(None))
            .alias(target)
        )

    # ------------------------------------------------------------------ #
    # 6. bmi_percentile_category — BMI-for-age class (CDC 2000, WHO 2007) #
    # ------------------------------------------------------------------ #

    def bmi_percentile_category(
        self,
        target: str,
        *,
        bmi_col: str,
        age_months_col: str,
        sex_col: str,
        reference: Literal["CDC2000", "WHO2007"],
        sex_male_value: str = "M",
        sex_female_value: str = "F",
    ) -> Self:
        """Classify a child's BMI by age and sex with the CDC 2000 or WHO 2007 reference.

        ``reference="CDC2000"`` (ages 24 to < 240 months) takes the table row
        of the completed month (row 60.5 for 60.0 to 60.99 months) and gives
        Underweight (< P5), Healthy weight (P5 to < P85), Overweight (P85 to
        < P95) or Obesity (>= P95).

        ``reference="WHO2007"`` (ages 61 to 228 months) interpolates L, M and
        S linearly between the two whole months around the age, as WHO
        AnthroPlus, computes the z-score ``((BMI / M) ** L - 1) / (L * S)``
        rounded to 2 decimals, and gives Severe thinness (z < -3), Thinness
        (z < -2), Normal (-2 to +1), Overweight (> +1 to +2) or Obesity
        (z > +2).

        A null, NaN or infinite BMI, a null age, an age out of the range of
        the reference, or a sex that is neither *sex_male_value* nor
        *sex_female_value* gives null.  Check the SAP for the reference and
        for the age rule (completed months or exact age).

        Args:
            target: Name of the output column.
            bmi_col: Column containing BMI in kg/m2.
            age_months_col: Column containing age in months at the
                measurement (whole or decimal months).
            sex_col: Column containing the sex code.
            reference: ``"CDC2000"`` or ``"WHO2007"``.  No default: the SAP
                names the reference.
            sex_male_value: Value indicating male (default ``"M"``).
            sex_female_value: Value indicating female (default ``"F"``).

        Returns:
            Self: The namespace with *target* appended.

        Raises:
            VerbUsageError: When *reference* is not ``"CDC2000"`` or
                ``"WHO2007"``.

        Examples:
            Classify BMI-for-age with the CDC 2000 charts::

                adsl = (
                    adsl_raw.adam.peds
                    .bmi_percentile_category("BMICG", bmi_col="BMI",
                                             age_months_col="AGEMOS",
                                             sex_col="SEX",
                                             reference="CDC2000")
                    .to_frame()
                )

        References:
            CDC NCHS, 2000 CDC growth charts, BMI-for-age LMS and percentile file
            ``bmiagerev.csv``; CDC "Child and Teen BMI Categories": < 5th, 5th to
            < 85th, 85th to < 95th, >= 95th percentile.
            WHO 2007 growth reference 5-19 years, BMI-for-age expanded LMS tables
            (de Onis M et al. Bull World Health Organ. 2007;85:660-667): thinness
            < -2 SD, severe thinness < -3 SD, overweight > +1 SD, obesity > +2 SD.
            WHO ``anthroplus`` R package: linear interpolation of L, M and S, z
            rounded to 2 decimals. Source files and SHA-256:
            ``fleet/adam/data/growth/README.md``. ADR-0026.
        """
        loaders = {"CDC2000": self._cdc2000_class, "WHO2007": self._who2007_class}
        if reference not in loaders:
            raise VerbUsageError(
                f"bmi_percentile_category: reference={reference!r} is not supported. "
                "Use 'CDC2000' or 'WHO2007'."
            )
        df = self.to_frame()
        sex_code = (
            pl.when(pl.col(sex_col) == sex_male_value)
            .then(pl.lit(1, dtype=pl.Int64))
            .when(pl.col(sex_col) == sex_female_value)
            .then(pl.lit(2, dtype=pl.Int64))
        )
        keyed = df.with_columns(
            sex_code.alias("__sex__"),
            pl.col(age_months_col).cast(pl.Float64).alias("__age__"),
            pl.col(bmi_col).cast(pl.Float64).alias("__bmi__"),
        )
        classed = loaders[reference](keyed)
        bmi_ok = pl.col("__bmi__").is_finite()
        result = classed.with_columns(
            pl.when(bmi_ok).then(pl.col("__class__")).alias(target)
        ).select(*[c for c in df.columns if c != target], target)
        return self._materialise_then(result)

    @staticmethod
    def _cdc2000_class(keyed: pl.DataFrame) -> pl.DataFrame:
        age = pl.col("__age__")
        row = pl.when((age >= 24) & (age < 240)).then(age.floor() + 0.5)
        joined = keyed.with_columns(row.alias("__agemos__")).join(
            _cdc2000_bmi(), on=["__sex__", "__agemos__"], how="left", maintain_order="left"
        )
        bmi = pl.col("__bmi__")
        return joined.with_columns(
            pl.when(pl.col("__P5__").is_null())
            .then(pl.lit(None, dtype=pl.String))
            .when(bmi < pl.col("__P5__"))
            .then(pl.lit("Underweight"))
            .when(bmi < pl.col("__P85__"))
            .then(pl.lit("Healthy weight"))
            .when(bmi < pl.col("__P95__"))
            .then(pl.lit("Overweight"))
            .otherwise(pl.lit("Obesity"))
            .alias("__class__")
        )

    @staticmethod
    def _who2007_class(keyed: pl.DataFrame) -> pl.DataFrame:
        table = _who2007_bmi()
        age = pl.col("__age__")
        low_month = pl.when((age >= 61) & (age <= 228)).then(age.floor().cast(pl.Int64))
        low = table.rename(
            {"Sex": "__sex__", "Month": "__lo__", "L": "__L0", "M": "__M0", "S": "__S0"}
        )
        high = table.rename(
            {"Sex": "__sex__", "Month": "__hi__", "L": "__L1", "M": "__M1", "S": "__S1"}
        )
        joined = (
            keyed.with_columns(low_month.alias("__lo__"))
            .with_columns((pl.col("__lo__") + 1).alias("__hi__"))
            .join(low, on=["__sex__", "__lo__"], how="left", maintain_order="left")
            .join(high, on=["__sex__", "__hi__"], how="left", maintain_order="left")
        )
        frac = age - pl.col("__lo__")

        def _interp(p: str) -> pl.Expr:
            lo, hi = pl.col(f"__{p}0"), pl.col(f"__{p}1")
            return pl.when(frac == 0).then(lo).otherwise(lo + frac * (hi - lo))

        lam, mu, sigma = _interp("L"), _interp("M"), _interp("S")
        z = (((pl.col("__bmi__") / mu).pow(lam) - 1) / (lam * sigma)).round(2)
        return joined.with_columns(
            pl.when(z.is_null())
            .then(pl.lit(None, dtype=pl.String))
            .when(z < -3)
            .then(pl.lit("Severe thinness"))
            .when(z < -2)
            .then(pl.lit("Thinness"))
            .when(z <= 1)
            .then(pl.lit("Normal"))
            .when(z <= 2)
            .then(pl.lit("Overweight"))
            .otherwise(pl.lit("Obesity"))
            .alias("__class__")
        )

age_days

age_days(target, *, birth_date, analysis_date)

Compute age in whole days.

Parameters:

Name Type Description Default
target str

Name of the output column.

required
birth_date str

Column containing the date of birth.

required
analysis_date str

Column containing the reference date.

required

Returns:

Name Type Description
Self Self

The namespace with target appended.

Examples:

Derive age in days from birth and reference dates::

adsl = (
    dm_raw.adam.peds
    .age_days("AGEDAYS", birth_date="BRTHDT",
              analysis_date="RFSTDTC")
    .to_frame()
)
Source code in src/fleet/adam/peds_namespace.py
def age_days(
    self,
    target: str,
    *,
    birth_date: str,
    analysis_date: str,
) -> Self:
    """Compute age in whole days.

    Args:
        target: Name of the output column.
        birth_date: Column containing the date of birth.
        analysis_date: Column containing the reference date.

    Returns:
        Self: The namespace with *target* appended.

    Examples:
        Derive age in days from birth and reference dates::

            adsl = (
                dm_raw.adam.peds
                .age_days("AGEDAYS", birth_date="BRTHDT",
                          analysis_date="RFSTDTC")
                .to_frame()
            )
    """
    expr = self._age_in_days("age_days", birth_date, analysis_date).cast(pl.Int64).alias(target)
    return self._chain(expr)

age_months

age_months(target, *, birth_date, analysis_date)

Compute age in whole months (floor of days / 30.4375).

Parameters:

Name Type Description Default
target str

Name of the output column.

required
birth_date str

Column containing the date of birth.

required
analysis_date str

Column containing the reference date.

required

Returns:

Name Type Description
Self Self

The namespace with target appended.

Examples:

Derive age in months::

adsl = (
    dm_raw.adam.peds
    .age_months("AGEMOS", birth_date="BRTHDT",
                analysis_date="RFSTDTC")
    .to_frame()
)
References

admiral derive_vars_duration (pharmaverse): one month = 30.4375 days (365.25 / 12). A month of 30 days gives a different answer.

Source code in src/fleet/adam/peds_namespace.py
def age_months(
    self,
    target: str,
    *,
    birth_date: str,
    analysis_date: str,
) -> Self:
    """Compute age in whole months (floor of days / 30.4375).

    Args:
        target: Name of the output column.
        birth_date: Column containing the date of birth.
        analysis_date: Column containing the reference date.

    Returns:
        Self: The namespace with *target* appended.

    Examples:
        Derive age in months::

            adsl = (
                dm_raw.adam.peds
                .age_months("AGEMOS", birth_date="BRTHDT",
                            analysis_date="RFSTDTC")
                .to_frame()
            )

    References:
        admiral ``derive_vars_duration`` (pharmaverse): one month = 30.4375 days
        (365.25 / 12). A month of 30 days gives a different answer.
    """
    days = self._age_in_days("age_months", birth_date, analysis_date)
    expr = (days / 30.4375).floor().cast(pl.Int64).alias(target)
    return self._chain(expr)

age_years

age_years(
    target,
    *,
    birth_date,
    analysis_date,
    unit="years",
    round_digits=None
)

Compute age from two date columns, in completed years by default.

Same rule as adsl.age_from_dates: unit="years" gives whole completed years (Int64), so a child is 4 on the day before the 5th birthday. A 29 February birthday is reached on 1 March in a non-leap year; a reference date before birth gives a negative age. unit="decimal" gives days / 365.25 at full precision.

Parameters:

Name Type Description Default
target str

Name of the output column.

required
birth_date str

Column containing the date of birth.

required
analysis_date str

Column containing the reference date.

required
unit Literal['years', 'decimal']

"years" (default) or "decimal".

'years'
round_digits int | None

Decimal places for unit="decimal", rounded as SAS ROUND. Default None: no rounding.

None

Returns:

Name Type Description
Self Self

The namespace with target appended.

Raises:

Type Description
VerbUsageError

When round_digits is given with unit="years", or unit is unknown.

Examples:

Derive age in completed years::

adsl = (
    dm_raw.adam.peds
    .age_years("AAGE", birth_date="BRTHDT",
               analysis_date="RFSTDT")
    .to_frame()
)
References

admiral derive_vars_aage (pharmaverse) and SAS FLOOR(YRDIF(BRTHDT, RFSTDT, 'AGE')): completed years. ICH E11 age bands use completed years. Decimal: one year = 365.25 days. ADR-0025.

Source code in src/fleet/adam/peds_namespace.py
def age_years(
    self,
    target: str,
    *,
    birth_date: str,
    analysis_date: str,
    unit: Literal["years", "decimal"] = "years",
    round_digits: int | None = None,
) -> Self:
    """Compute age from two date columns, in completed years by default.

    Same rule as ``adsl.age_from_dates``: ``unit="years"`` gives whole
    completed years (Int64), so a child is 4 on the day before the 5th
    birthday.  A 29 February birthday is reached on 1 March in a non-leap
    year; a reference date before birth gives a negative age.
    ``unit="decimal"`` gives days / 365.25 at full precision.

    Args:
        target: Name of the output column.
        birth_date: Column containing the date of birth.
        analysis_date: Column containing the reference date.
        unit: ``"years"`` (default) or ``"decimal"``.
        round_digits: Decimal places for ``unit="decimal"``, rounded as
            SAS ``ROUND``.  Default ``None``: no rounding.

    Returns:
        Self: The namespace with *target* appended.

    Raises:
        VerbUsageError: When *round_digits* is given with
            ``unit="years"``, or *unit* is unknown.

    Examples:
        Derive age in completed years::

            adsl = (
                dm_raw.adam.peds
                .age_years("AAGE", birth_date="BRTHDT",
                           analysis_date="RFSTDT")
                .to_frame()
            )

    References:
        admiral ``derive_vars_aage`` (pharmaverse) and SAS
        ``FLOOR(YRDIF(BRTHDT, RFSTDT, 'AGE'))``: completed years. ICH E11 age
        bands use completed years. Decimal: one year = 365.25 days. ADR-0025.
    """
    from fleet.adam.utils import age_between

    schema = self._lazy.collect_schema()
    reference, birth = (
        to_day(pl.col(c), schema.get(c), verb="age_years").cast(pl.Date)
        for c in (analysis_date, birth_date)
    )
    expr = age_between(birth, reference, unit=unit, round_digits=round_digits, verb="age_years")
    return self._chain(expr.alias(target))

corrected_age

corrected_age(
    target,
    *,
    age_days_col,
    gestational_weeks_col,
    term_weeks=40
)

Compute gestational-corrected age in decimal years.

Corrected age = chronological age − (term_weeks − gestational_weeks) / 52.18. No correction when gestational weeks >= term_weeks. A null or NaN gestational age gives a null result; if the SAP assumes term birth, fill the column with term_weeks before the call.

Parameters:

Name Type Description Default
target str

Name of the output column.

required
age_days_col str

Column containing age in days.

required
gestational_weeks_col str

Column containing gestational age in weeks.

required
term_weeks int

Full-term threshold (default 40).

40

Returns:

Name Type Description
Self Self

The namespace with target appended.

Examples:

Derive corrected age for preterm infants::

adsl = (
    dm_raw.adam.peds
    .corrected_age("CORAGE", age_days_col="AGEDAYS",
                   gestational_weeks_col="GESTAG")
    .to_frame()
)
References

American Academy of Pediatrics, Committee on Fetus and Newborn. Age terminology during the perinatal period. Pediatrics. 2004;114(5):1362-1364: corrected age = chronological age minus the weeks born before 40 weeks. 52.18 weeks per year = 365.25 / 7.

Source code in src/fleet/adam/peds_namespace.py
def corrected_age(
    self,
    target: str,
    *,
    age_days_col: str,
    gestational_weeks_col: str,
    term_weeks: int = 40,
) -> Self:
    """Compute gestational-corrected age in decimal years.

    Corrected age = chronological age − (term_weeks − gestational_weeks) / 52.18.
    No correction when gestational weeks >= *term_weeks*.  A null or NaN
    gestational age gives a null result; if the SAP assumes term birth,
    fill the column with *term_weeks* before the call.

    Args:
        target: Name of the output column.
        age_days_col: Column containing age in days.
        gestational_weeks_col: Column containing gestational age in weeks.
        term_weeks: Full-term threshold (default ``40``).

    Returns:
        Self: The namespace with *target* appended.

    Examples:
        Derive corrected age for preterm infants::

            adsl = (
                dm_raw.adam.peds
                .corrected_age("CORAGE", age_days_col="AGEDAYS",
                               gestational_weeks_col="GESTAG")
                .to_frame()
            )

    References:
        American Academy of Pediatrics, Committee on Fetus and Newborn. Age
        terminology during the perinatal period. Pediatrics. 2004;114(5):1362-1364:
        corrected age = chronological age minus the weeks born before 40 weeks.
        52.18 weeks per year = 365.25 / 7.
    """
    ga = pl.col(gestational_weeks_col).cast(pl.Float64).fill_nan(None)
    prematurity_years = pl.when(ga >= term_weeks).then(0.0).otherwise((term_weeks - ga) / 52.18)
    chron_age_years = pl.col(age_days_col) / 365.25
    return self._chain((chron_age_years - prematurity_years).round(4).alias(target))

prematurity_flag

prematurity_flag(
    target,
    *,
    gestational_weeks_col,
    threshold=37,
    flag_value="Y"
)

Flag infants born before threshold gestational weeks.

Default threshold of 37 weeks matches the clinical definition of prematurity.

Parameters:

Name Type Description Default
target str

Name of the output flag column.

required
gestational_weeks_col str

Column containing gestational age in weeks.

required
threshold int

Weeks below which prematurity is flagged (default 37).

37
flag_value str

Value to assign (default "Y").

'Y'

Returns:

Name Type Description
Self Self

The namespace with target appended.

Examples:

Derive prematurity flag::

adsl = (
    dm_raw.adam.peds
    .prematurity_flag("PREMFL",
                     gestational_weeks_col="GESTAG")
    .to_frame()
)
References

WHO: preterm birth is birth before 37 completed weeks of gestation (ICD-10 P07; WHO preterm birth fact sheet).

Source code in src/fleet/adam/peds_namespace.py
def prematurity_flag(
    self,
    target: str,
    *,
    gestational_weeks_col: str,
    threshold: int = 37,
    flag_value: str = "Y",
) -> Self:
    """Flag infants born before *threshold* gestational weeks.

    Default threshold of 37 weeks matches the clinical definition of
    prematurity.

    Args:
        target: Name of the output flag column.
        gestational_weeks_col: Column containing gestational age in weeks.
        threshold: Weeks below which prematurity is flagged (default ``37``).
        flag_value: Value to assign (default ``"Y"``).

    Returns:
        Self: The namespace with *target* appended.

    Examples:
        Derive prematurity flag::

            adsl = (
                dm_raw.adam.peds
                .prematurity_flag("PREMFL",
                                 gestational_weeks_col="GESTAG")
                .to_frame()
            )

    References:
        WHO: preterm birth is birth before 37 completed weeks of gestation
        (ICD-10 P07; WHO preterm birth fact sheet).
    """
    return self._chain(
        pl.when(pl.col(gestational_weeks_col) < threshold)
        .then(pl.lit(flag_value))
        .otherwise(pl.lit(None))
        .alias(target)
    )

bmi_percentile_category

bmi_percentile_category(
    target,
    *,
    bmi_col,
    age_months_col,
    sex_col,
    reference,
    sex_male_value="M",
    sex_female_value="F"
)

Classify a child's BMI by age and sex with the CDC 2000 or WHO 2007 reference.

reference="CDC2000" (ages 24 to < 240 months) takes the table row of the completed month (row 60.5 for 60.0 to 60.99 months) and gives Underweight (< P5), Healthy weight (P5 to < P85), Overweight (P85 to < P95) or Obesity (>= P95).

reference="WHO2007" (ages 61 to 228 months) interpolates L, M and S linearly between the two whole months around the age, as WHO AnthroPlus, computes the z-score ((BMI / M) ** L - 1) / (L * S) rounded to 2 decimals, and gives Severe thinness (z < -3), Thinness (z < -2), Normal (-2 to +1), Overweight (> +1 to +2) or Obesity (z > +2).

A null, NaN or infinite BMI, a null age, an age out of the range of the reference, or a sex that is neither sex_male_value nor sex_female_value gives null. Check the SAP for the reference and for the age rule (completed months or exact age).

Parameters:

Name Type Description Default
target str

Name of the output column.

required
bmi_col str

Column containing BMI in kg/m2.

required
age_months_col str

Column containing age in months at the measurement (whole or decimal months).

required
sex_col str

Column containing the sex code.

required
reference Literal['CDC2000', 'WHO2007']

"CDC2000" or "WHO2007". No default: the SAP names the reference.

required
sex_male_value str

Value indicating male (default "M").

'M'
sex_female_value str

Value indicating female (default "F").

'F'

Returns:

Name Type Description
Self Self

The namespace with target appended.

Raises:

Type Description
VerbUsageError

When reference is not "CDC2000" or "WHO2007".

Examples:

Classify BMI-for-age with the CDC 2000 charts::

adsl = (
    adsl_raw.adam.peds
    .bmi_percentile_category("BMICG", bmi_col="BMI",
                             age_months_col="AGEMOS",
                             sex_col="SEX",
                             reference="CDC2000")
    .to_frame()
)
References

CDC NCHS, 2000 CDC growth charts, BMI-for-age LMS and percentile file bmiagerev.csv; CDC "Child and Teen BMI Categories": < 5th, 5th to < 85th, 85th to < 95th, >= 95th percentile. WHO 2007 growth reference 5-19 years, BMI-for-age expanded LMS tables (de Onis M et al. Bull World Health Organ. 2007;85:660-667): thinness < -2 SD, severe thinness < -3 SD, overweight > +1 SD, obesity > +2 SD. WHO anthroplus R package: linear interpolation of L, M and S, z rounded to 2 decimals. Source files and SHA-256: fleet/adam/data/growth/README.md. ADR-0026.

Source code in src/fleet/adam/peds_namespace.py
def bmi_percentile_category(
    self,
    target: str,
    *,
    bmi_col: str,
    age_months_col: str,
    sex_col: str,
    reference: Literal["CDC2000", "WHO2007"],
    sex_male_value: str = "M",
    sex_female_value: str = "F",
) -> Self:
    """Classify a child's BMI by age and sex with the CDC 2000 or WHO 2007 reference.

    ``reference="CDC2000"`` (ages 24 to < 240 months) takes the table row
    of the completed month (row 60.5 for 60.0 to 60.99 months) and gives
    Underweight (< P5), Healthy weight (P5 to < P85), Overweight (P85 to
    < P95) or Obesity (>= P95).

    ``reference="WHO2007"`` (ages 61 to 228 months) interpolates L, M and
    S linearly between the two whole months around the age, as WHO
    AnthroPlus, computes the z-score ``((BMI / M) ** L - 1) / (L * S)``
    rounded to 2 decimals, and gives Severe thinness (z < -3), Thinness
    (z < -2), Normal (-2 to +1), Overweight (> +1 to +2) or Obesity
    (z > +2).

    A null, NaN or infinite BMI, a null age, an age out of the range of
    the reference, or a sex that is neither *sex_male_value* nor
    *sex_female_value* gives null.  Check the SAP for the reference and
    for the age rule (completed months or exact age).

    Args:
        target: Name of the output column.
        bmi_col: Column containing BMI in kg/m2.
        age_months_col: Column containing age in months at the
            measurement (whole or decimal months).
        sex_col: Column containing the sex code.
        reference: ``"CDC2000"`` or ``"WHO2007"``.  No default: the SAP
            names the reference.
        sex_male_value: Value indicating male (default ``"M"``).
        sex_female_value: Value indicating female (default ``"F"``).

    Returns:
        Self: The namespace with *target* appended.

    Raises:
        VerbUsageError: When *reference* is not ``"CDC2000"`` or
            ``"WHO2007"``.

    Examples:
        Classify BMI-for-age with the CDC 2000 charts::

            adsl = (
                adsl_raw.adam.peds
                .bmi_percentile_category("BMICG", bmi_col="BMI",
                                         age_months_col="AGEMOS",
                                         sex_col="SEX",
                                         reference="CDC2000")
                .to_frame()
            )

    References:
        CDC NCHS, 2000 CDC growth charts, BMI-for-age LMS and percentile file
        ``bmiagerev.csv``; CDC "Child and Teen BMI Categories": < 5th, 5th to
        < 85th, 85th to < 95th, >= 95th percentile.
        WHO 2007 growth reference 5-19 years, BMI-for-age expanded LMS tables
        (de Onis M et al. Bull World Health Organ. 2007;85:660-667): thinness
        < -2 SD, severe thinness < -3 SD, overweight > +1 SD, obesity > +2 SD.
        WHO ``anthroplus`` R package: linear interpolation of L, M and S, z
        rounded to 2 decimals. Source files and SHA-256:
        ``fleet/adam/data/growth/README.md``. ADR-0026.
    """
    loaders = {"CDC2000": self._cdc2000_class, "WHO2007": self._who2007_class}
    if reference not in loaders:
        raise VerbUsageError(
            f"bmi_percentile_category: reference={reference!r} is not supported. "
            "Use 'CDC2000' or 'WHO2007'."
        )
    df = self.to_frame()
    sex_code = (
        pl.when(pl.col(sex_col) == sex_male_value)
        .then(pl.lit(1, dtype=pl.Int64))
        .when(pl.col(sex_col) == sex_female_value)
        .then(pl.lit(2, dtype=pl.Int64))
    )
    keyed = df.with_columns(
        sex_code.alias("__sex__"),
        pl.col(age_months_col).cast(pl.Float64).alias("__age__"),
        pl.col(bmi_col).cast(pl.Float64).alias("__bmi__"),
    )
    classed = loaders[reference](keyed)
    bmi_ok = pl.col("__bmi__").is_finite()
    result = classed.with_columns(
        pl.when(bmi_ok).then(pl.col("__class__")).alias(target)
    ).select(*[c for c in df.columns if c != target], target)
    return self._materialise_then(result)

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

Vaccine — df.adam.vaccine

fleet.adam.VaccineNamespace

Bases: SharedADaMVerbsMixin

Immutable pipeline builder for ADaM vaccine derivations.

Inherits shared verbs from SharedADaMVerbsMixin.

Source code in src/fleet/adam/vaccine_namespace.py
class VaccineNamespace(SharedADaMVerbsMixin):
    """
    Immutable pipeline builder for ADaM vaccine derivations.

    Inherits shared verbs from ``SharedADaMVerbsMixin``.
    """

    # ------------------------------------------------------------------ #
    # 1. fever_flag — flag elevated temperature (ADFACE)                  #
    # ------------------------------------------------------------------ #

    def fever_flag(
        self,
        target: str,
        *,
        temp_col: str,
        threshold: float = 38.0,
        inclusive: bool = True,
        flag_value: str = "Y",
    ) -> Self:
        """
        Set *target* to *flag_value* when *temp_col* is at or above *threshold*.

        The default 38.0 °C is the start of grade 1 fever on the FDA 2007
        toxicity grading scale, so a record of exactly 38.0 °C gets the flag.
        ``inclusive=False`` flags strictly above *threshold*, for a SAP limit
        such as FDA grade 4 (> 40.0 °C).  With ``inclusive=False`` and the
        default threshold, a record of 38.0 °C gets no flag.

        Example::

            .fever_flag("FEVFL", temp_col="TEMP")
            .fever_flag("G4FEVFL", temp_col="TEMP", threshold=40.0, inclusive=False)

        References:
            FDA, Guidance for Industry: Toxicity Grading Scale for Healthy Adult and
            Adolescent Volunteers Enrolled in Preventive Vaccine Clinical Trials
            (2007): grade 1 fever starts at 38.0 °C; grade 4 is > 40 °C. Brighton
            Collaboration fever case definition (Marcy SM et al. Vaccine.
            2004;22:551-556): >= 38.0 °C. admiralvaccine ``derive_fever_records``:
            VSSTRESN >= 38. ADR-0027.
        """
        temp = pl.col(temp_col)
        return self._chain(
            pl.when(temp >= threshold if inclusive else temp > threshold)
            .then(pl.lit(flag_value))
            .otherwise(pl.lit(None))
            .alias(target)
        )

    # ------------------------------------------------------------------ #
    # 2. seroconversion_flag — ≥ N-fold rise from baseline               #
    # ------------------------------------------------------------------ #

    def seroconversion_flag(
        self,
        target: str,
        *,
        aval_col: str,
        base_col: str,
        lloq_col: str | None,
        fold_rise: float = 4.0,
        seronegative_fold: float | None = None,
        flag_value: str = "Y",
    ) -> Self:
        """
        Flag seroconversion: a *fold_rise* rise from baseline, with an LLOQ rule.

        *lloq_col* has no default, so the call states the rule of the SAP:

        - ``lloq_col="ISLLOQ"`` (two-arm rule, FDA CBER 2007): when BASE is
          below the LLOQ, the flag needs ``AVAL >= seronegative_fold × LLOQ``
          (HI: pre < 1:10 needs post >= 1:40); when BASE is at or above the
          LLOQ, it needs ``AVAL >= fold_rise × BASE``.  Null when AVAL, BASE
          or the LLOQ is null.  *lloq_col* must hold the LLOQ of the baseline
          record.
        - ``lloq_col=None`` (plain ratio): ``AVAL / BASE >= fold_rise``, for a
          SAP that states the ratio only.  Null when BASE is null or zero.

        Rows that do not meet the rule get null.

        Example::

            .seroconversion_flag("SRCONVFL", aval_col="AVAL", base_col="BASE",
                                  lloq_col="ISLLOQ")
            .seroconversion_flag("SRCONV2FL", aval_col="AVAL", base_col="BASE",
                                  lloq_col=None, fold_rise=2.0)

        References:
            FDA CBER, Guidance for Industry: Clinical Data Needed to Support the
            Licensure of Seasonal Inactivated Influenza Vaccines (2007): seroconversion
            is a pre-vaccination HI titre < 1:10 and a post-vaccination titre
            >= 1:40, or a pre-vaccination titre >= 1:10 and a >= 4-fold rise. EMA
            CHMP, CPMP/BWP/214/96, states the same criterion. Some SAPs use the
            plain ratio. ADR-0027.
        """
        aval = pl.col(aval_col)
        base = pl.col(base_col)
        if lloq_col is None:
            met = base.is_not_null() & (base != 0) & (aval / base >= fold_rise)
        else:
            lloq = pl.col(lloq_col)
            neg_fold = fold_rise if seronegative_fold is None else seronegative_fold
            met = (
                pl.when(aval.is_null() | base.is_null() | lloq.is_null())
                .then(pl.lit(False))
                .when(base < lloq)
                .then(aval >= neg_fold * lloq)
                .otherwise(aval >= fold_rise * base)
            )
        return self._chain(
            pl.when(met).then(pl.lit(flag_value)).otherwise(pl.lit(None)).alias(target)
        )

    # ------------------------------------------------------------------ #
    # 3. seroresponse_flag — titer at or above a threshold               #
    # ------------------------------------------------------------------ #

    def seroresponse_flag(
        self,
        target: str,
        *,
        aval_col: str,
        threshold: float,
        flag_value: str = "Y",
    ) -> Self:
        """
        Set *target* to *flag_value* when *aval_col* ≥ *threshold*.

        Example::

            .seroresponse_flag("SRSFL", aval_col="AVAL", threshold=40.0)
        """
        return self._chain(
            pl.when(pl.col(aval_col) >= threshold)
            .then(pl.lit(flag_value))
            .otherwise(pl.lit(None))
            .alias(target)
        )

    # ------------------------------------------------------------------ #
    # 4. aval_adis — ADIS AVAL with LLOQ/ULOQ handling                   #
    # ------------------------------------------------------------------ #

    def aval_adis(
        self,
        target: str,
        *,
        stresn_col: str = "ISSTRESN",
        lloq_col: str = "ISLLOQ",
        uloq_col: str | None = "ISULOQ",
        orres_col: str | None = "ISORRES",
        lloq_rule: Literal["half", "lloq"] = "half",
        round_digits: int | None = None,
    ) -> Self:
        """
        Derive ``AVAL`` for the ADIS domain following limit-of-quantification rules.

        Rules (based on ``admiralvaccine::derive_var_aval_adis``):

        1. If *stresn_col* is missing:
           - If *orres_col* starts with ``">"`` and *uloq_col* is present →
             use *uloq_col* value.
           - If *orres_col* starts with ``"<"`` → use *lloq_col* × factor
             (``"half"`` = ÷2, ``"lloq"`` = *lloq_col* itself).
           - Otherwise → null.
        2. If *stresn_col* < *lloq_col* → use *lloq_col* × factor.
        3. If *uloq_col* present and *stresn_col* > *uloq_col* → use *uloq_col*.
        4. Otherwise → use *stresn_col*.

        *lloq_rule*: ``"half"`` (LLOQ ÷ 2) or ``"lloq"`` (retain LLOQ value).
        Any other text raises ``DerivationError``.

        Example::

            .aval_adis("AVAL", stresn_col="ISSTRESN",
                       lloq_col="ISLLOQ", uloq_col="ISULOQ",
                       orres_col="ISORRES")

        References:
            admiralvaccine ``derive_var_aval_adis`` (pharmaverse): the rule set this
            verb is based on. No CDISC standard fixes the LLOQ/2 imputation; it is an
            analysis convention. Check the SAP for the rule in force.
        """
        if lloq_rule not in ("half", "lloq"):
            raise DerivationError(
                f"aval_adis: lloq_rule={lloq_rule!r} is not supported. Use 'half' or 'lloq'."
            )
        stresn = pl.col(stresn_col)
        lloq = pl.col(lloq_col)
        lloq_val = lloq / 2.0 if lloq_rule == "half" else lloq

        if uloq_col:
            uloq = pl.col(uloq_col)
            # When STRESN is present: apply LLOQ/ULOQ capping
            stresn_rule = (
                pl.when(stresn < lloq)
                .then(lloq_val)
                .when(stresn > uloq)
                .then(uloq)
                .otherwise(stresn)
            )
            # When STRESN is missing: use ORRES string to infer direction
            if orres_col:
                orres_str = pl.col(orres_col).cast(pl.Utf8)
                missing_rule = (
                    pl.when(orres_str.str.starts_with(">"))
                    .then(uloq)
                    .when(orres_str.str.starts_with("<"))
                    .then(lloq_val)
                    .otherwise(pl.lit(None))
                )
            else:
                missing_rule = pl.lit(None)

            expr = pl.when(stresn.is_not_null()).then(stresn_rule).otherwise(missing_rule)
        else:
            # No ULOQ column
            stresn_rule = pl.when(stresn < lloq).then(lloq_val).otherwise(stresn)
            if orres_col:
                orres_str = pl.col(orres_col).cast(pl.Utf8)
                missing_rule = (
                    pl.when(orres_str.str.starts_with("<")).then(lloq_val).otherwise(pl.lit(None))
                )
            else:
                missing_rule = pl.lit(None)

            expr = pl.when(stresn.is_not_null()).then(stresn_rule).otherwise(missing_rule)

        if round_digits is not None:
            expr = expr.round(round_digits)

        return self._chain(expr.alias(target))

    # ------------------------------------------------------------------ #
    # 5. event_flag — reactogenicity event occurrence flags               #
    # ------------------------------------------------------------------ #

    def event_flag(
        self,
        target: str,
        *,
        aval_col: str,
        cutoff: float,
        by: list[str],
        severity_col: str | None = "AVALC",
        severity_values: list[str] | None = None,
        flag_value: str = "Y",
        no_event_value: str = "N",
    ) -> Self:
        """
        Flag whether a reactogenicity event occurred at least once per *by* group.

        A record has an event if *aval_col* > *cutoff*, or *severity_col* is
        in *severity_values* (default ``["Y", "MILD", "MODERATE", "SEVERE"]``;
        ``[]`` means no value counts).  Every record of a group with an event
        gets *flag_value*.  In a group with no event, a record gets
        *no_event_value* when it shows no event (*aval_col* <= *cutoff*, or
        *severity_col* is ``"N"``), and null when it has no assessable data
        (both missing).  So a diary with only missing records gets null, not
        *no_event_value*.

        *by* has no default: one event must not spread to the other FAOBJ or
        ATPTREF of the subject.  ``severity_col=None`` uses *aval_col* only.

        Materialises the current pipeline.

        Based on ``admiralvaccine::derive_vars_event_flag`` (new_var1 behaviour).

        Example::

            .event_flag("EVENTFL", aval_col="AVAL", cutoff=2.5,
                        by=["USUBJID", "FAOBJ", "ATPTREF"])

        References:
            admiralvaccine ``derive_vars_event_flag`` (pharmaverse), ``new_var1``:
            AVALC in Y, MILD, MODERATE, SEVERE; no default ``by_vars``; a record
            with missing AVAL and AVALC gets NA. FDA toxicity grading scale (2007)
            for the severity grades. ADR-0027.
        """
        sev_vals = (
            ["Y", "MILD", "MODERATE", "SEVERE"] if severity_values is None else severity_values
        )
        aval = pl.col(aval_col)
        row_event = aval > cutoff
        row_no_event = aval <= cutoff
        if severity_col is not None:
            sev = pl.col(severity_col)
            row_event = row_event | sev.is_in(sev_vals).fill_null(False)
            row_no_event = row_no_event | (sev == "N").fill_null(False)

        # Kleene any, as R any(): True, else null when a record is unknown, else False.
        any_event = row_event.any(ignore_nulls=False).over(by)
        return self._chain(
            pl.when(any_event)
            .then(pl.lit(flag_value))
            .when(row_no_event)
            .then(pl.lit(no_event_value))
            .otherwise(pl.lit(None, dtype=pl.String))
            .alias(target),
            verb="event_flag",
        )

fever_flag

fever_flag(
    target,
    *,
    temp_col,
    threshold=38.0,
    inclusive=True,
    flag_value="Y"
)

Set target to flag_value when temp_col is at or above threshold.

The default 38.0 °C is the start of grade 1 fever on the FDA 2007 toxicity grading scale, so a record of exactly 38.0 °C gets the flag. inclusive=False flags strictly above threshold, for a SAP limit such as FDA grade 4 (> 40.0 °C). With inclusive=False and the default threshold, a record of 38.0 °C gets no flag.

Example::

.fever_flag("FEVFL", temp_col="TEMP")
.fever_flag("G4FEVFL", temp_col="TEMP", threshold=40.0, inclusive=False)
References

FDA, Guidance for Industry: Toxicity Grading Scale for Healthy Adult and Adolescent Volunteers Enrolled in Preventive Vaccine Clinical Trials (2007): grade 1 fever starts at 38.0 °C; grade 4 is > 40 °C. Brighton Collaboration fever case definition (Marcy SM et al. Vaccine. 2004;22:551-556): >= 38.0 °C. admiralvaccine derive_fever_records: VSSTRESN >= 38. ADR-0027.

Source code in src/fleet/adam/vaccine_namespace.py
def fever_flag(
    self,
    target: str,
    *,
    temp_col: str,
    threshold: float = 38.0,
    inclusive: bool = True,
    flag_value: str = "Y",
) -> Self:
    """
    Set *target* to *flag_value* when *temp_col* is at or above *threshold*.

    The default 38.0 °C is the start of grade 1 fever on the FDA 2007
    toxicity grading scale, so a record of exactly 38.0 °C gets the flag.
    ``inclusive=False`` flags strictly above *threshold*, for a SAP limit
    such as FDA grade 4 (> 40.0 °C).  With ``inclusive=False`` and the
    default threshold, a record of 38.0 °C gets no flag.

    Example::

        .fever_flag("FEVFL", temp_col="TEMP")
        .fever_flag("G4FEVFL", temp_col="TEMP", threshold=40.0, inclusive=False)

    References:
        FDA, Guidance for Industry: Toxicity Grading Scale for Healthy Adult and
        Adolescent Volunteers Enrolled in Preventive Vaccine Clinical Trials
        (2007): grade 1 fever starts at 38.0 °C; grade 4 is > 40 °C. Brighton
        Collaboration fever case definition (Marcy SM et al. Vaccine.
        2004;22:551-556): >= 38.0 °C. admiralvaccine ``derive_fever_records``:
        VSSTRESN >= 38. ADR-0027.
    """
    temp = pl.col(temp_col)
    return self._chain(
        pl.when(temp >= threshold if inclusive else temp > threshold)
        .then(pl.lit(flag_value))
        .otherwise(pl.lit(None))
        .alias(target)
    )

seroconversion_flag

seroconversion_flag(
    target,
    *,
    aval_col,
    base_col,
    lloq_col,
    fold_rise=4.0,
    seronegative_fold=None,
    flag_value="Y"
)

Flag seroconversion: a fold_rise rise from baseline, with an LLOQ rule.

lloq_col has no default, so the call states the rule of the SAP:

  • lloq_col="ISLLOQ" (two-arm rule, FDA CBER 2007): when BASE is below the LLOQ, the flag needs AVAL >= seronegative_fold × LLOQ (HI: pre < 1:10 needs post >= 1:40); when BASE is at or above the LLOQ, it needs AVAL >= fold_rise × BASE. Null when AVAL, BASE or the LLOQ is null. lloq_col must hold the LLOQ of the baseline record.
  • lloq_col=None (plain ratio): AVAL / BASE >= fold_rise, for a SAP that states the ratio only. Null when BASE is null or zero.

Rows that do not meet the rule get null.

Example::

.seroconversion_flag("SRCONVFL", aval_col="AVAL", base_col="BASE",
                      lloq_col="ISLLOQ")
.seroconversion_flag("SRCONV2FL", aval_col="AVAL", base_col="BASE",
                      lloq_col=None, fold_rise=2.0)
References

FDA CBER, Guidance for Industry: Clinical Data Needed to Support the Licensure of Seasonal Inactivated Influenza Vaccines (2007): seroconversion is a pre-vaccination HI titre < 1:10 and a post-vaccination titre

= 1:40, or a pre-vaccination titre >= 1:10 and a >= 4-fold rise. EMA CHMP, CPMP/BWP/214/96, states the same criterion. Some SAPs use the plain ratio. ADR-0027.

Source code in src/fleet/adam/vaccine_namespace.py
def seroconversion_flag(
    self,
    target: str,
    *,
    aval_col: str,
    base_col: str,
    lloq_col: str | None,
    fold_rise: float = 4.0,
    seronegative_fold: float | None = None,
    flag_value: str = "Y",
) -> Self:
    """
    Flag seroconversion: a *fold_rise* rise from baseline, with an LLOQ rule.

    *lloq_col* has no default, so the call states the rule of the SAP:

    - ``lloq_col="ISLLOQ"`` (two-arm rule, FDA CBER 2007): when BASE is
      below the LLOQ, the flag needs ``AVAL >= seronegative_fold × LLOQ``
      (HI: pre < 1:10 needs post >= 1:40); when BASE is at or above the
      LLOQ, it needs ``AVAL >= fold_rise × BASE``.  Null when AVAL, BASE
      or the LLOQ is null.  *lloq_col* must hold the LLOQ of the baseline
      record.
    - ``lloq_col=None`` (plain ratio): ``AVAL / BASE >= fold_rise``, for a
      SAP that states the ratio only.  Null when BASE is null or zero.

    Rows that do not meet the rule get null.

    Example::

        .seroconversion_flag("SRCONVFL", aval_col="AVAL", base_col="BASE",
                              lloq_col="ISLLOQ")
        .seroconversion_flag("SRCONV2FL", aval_col="AVAL", base_col="BASE",
                              lloq_col=None, fold_rise=2.0)

    References:
        FDA CBER, Guidance for Industry: Clinical Data Needed to Support the
        Licensure of Seasonal Inactivated Influenza Vaccines (2007): seroconversion
        is a pre-vaccination HI titre < 1:10 and a post-vaccination titre
        >= 1:40, or a pre-vaccination titre >= 1:10 and a >= 4-fold rise. EMA
        CHMP, CPMP/BWP/214/96, states the same criterion. Some SAPs use the
        plain ratio. ADR-0027.
    """
    aval = pl.col(aval_col)
    base = pl.col(base_col)
    if lloq_col is None:
        met = base.is_not_null() & (base != 0) & (aval / base >= fold_rise)
    else:
        lloq = pl.col(lloq_col)
        neg_fold = fold_rise if seronegative_fold is None else seronegative_fold
        met = (
            pl.when(aval.is_null() | base.is_null() | lloq.is_null())
            .then(pl.lit(False))
            .when(base < lloq)
            .then(aval >= neg_fold * lloq)
            .otherwise(aval >= fold_rise * base)
        )
    return self._chain(
        pl.when(met).then(pl.lit(flag_value)).otherwise(pl.lit(None)).alias(target)
    )

seroresponse_flag

seroresponse_flag(
    target, *, aval_col, threshold, flag_value="Y"
)

Set target to flag_value when aval_col ≥ threshold.

Example::

.seroresponse_flag("SRSFL", aval_col="AVAL", threshold=40.0)
Source code in src/fleet/adam/vaccine_namespace.py
def seroresponse_flag(
    self,
    target: str,
    *,
    aval_col: str,
    threshold: float,
    flag_value: str = "Y",
) -> Self:
    """
    Set *target* to *flag_value* when *aval_col* ≥ *threshold*.

    Example::

        .seroresponse_flag("SRSFL", aval_col="AVAL", threshold=40.0)
    """
    return self._chain(
        pl.when(pl.col(aval_col) >= threshold)
        .then(pl.lit(flag_value))
        .otherwise(pl.lit(None))
        .alias(target)
    )

aval_adis

aval_adis(
    target,
    *,
    stresn_col="ISSTRESN",
    lloq_col="ISLLOQ",
    uloq_col="ISULOQ",
    orres_col="ISORRES",
    lloq_rule="half",
    round_digits=None
)

Derive AVAL for the ADIS domain following limit-of-quantification rules.

Rules (based on admiralvaccine::derive_var_aval_adis):

  1. If stresn_col is missing:
  2. If orres_col starts with ">" and uloq_col is present → use uloq_col value.
  3. If orres_col starts with "<" → use lloq_col × factor ("half" = ÷2, "lloq" = lloq_col itself).
  4. Otherwise → null.
  5. If stresn_col < lloq_col → use lloq_col × factor.
  6. If uloq_col present and stresn_col > uloq_col → use uloq_col.
  7. Otherwise → use stresn_col.

lloq_rule: "half" (LLOQ ÷ 2) or "lloq" (retain LLOQ value). Any other text raises DerivationError.

Example::

.aval_adis("AVAL", stresn_col="ISSTRESN",
           lloq_col="ISLLOQ", uloq_col="ISULOQ",
           orres_col="ISORRES")
References

admiralvaccine derive_var_aval_adis (pharmaverse): the rule set this verb is based on. No CDISC standard fixes the LLOQ/2 imputation; it is an analysis convention. Check the SAP for the rule in force.

Source code in src/fleet/adam/vaccine_namespace.py
def aval_adis(
    self,
    target: str,
    *,
    stresn_col: str = "ISSTRESN",
    lloq_col: str = "ISLLOQ",
    uloq_col: str | None = "ISULOQ",
    orres_col: str | None = "ISORRES",
    lloq_rule: Literal["half", "lloq"] = "half",
    round_digits: int | None = None,
) -> Self:
    """
    Derive ``AVAL`` for the ADIS domain following limit-of-quantification rules.

    Rules (based on ``admiralvaccine::derive_var_aval_adis``):

    1. If *stresn_col* is missing:
       - If *orres_col* starts with ``">"`` and *uloq_col* is present →
         use *uloq_col* value.
       - If *orres_col* starts with ``"<"`` → use *lloq_col* × factor
         (``"half"`` = ÷2, ``"lloq"`` = *lloq_col* itself).
       - Otherwise → null.
    2. If *stresn_col* < *lloq_col* → use *lloq_col* × factor.
    3. If *uloq_col* present and *stresn_col* > *uloq_col* → use *uloq_col*.
    4. Otherwise → use *stresn_col*.

    *lloq_rule*: ``"half"`` (LLOQ ÷ 2) or ``"lloq"`` (retain LLOQ value).
    Any other text raises ``DerivationError``.

    Example::

        .aval_adis("AVAL", stresn_col="ISSTRESN",
                   lloq_col="ISLLOQ", uloq_col="ISULOQ",
                   orres_col="ISORRES")

    References:
        admiralvaccine ``derive_var_aval_adis`` (pharmaverse): the rule set this
        verb is based on. No CDISC standard fixes the LLOQ/2 imputation; it is an
        analysis convention. Check the SAP for the rule in force.
    """
    if lloq_rule not in ("half", "lloq"):
        raise DerivationError(
            f"aval_adis: lloq_rule={lloq_rule!r} is not supported. Use 'half' or 'lloq'."
        )
    stresn = pl.col(stresn_col)
    lloq = pl.col(lloq_col)
    lloq_val = lloq / 2.0 if lloq_rule == "half" else lloq

    if uloq_col:
        uloq = pl.col(uloq_col)
        # When STRESN is present: apply LLOQ/ULOQ capping
        stresn_rule = (
            pl.when(stresn < lloq)
            .then(lloq_val)
            .when(stresn > uloq)
            .then(uloq)
            .otherwise(stresn)
        )
        # When STRESN is missing: use ORRES string to infer direction
        if orres_col:
            orres_str = pl.col(orres_col).cast(pl.Utf8)
            missing_rule = (
                pl.when(orres_str.str.starts_with(">"))
                .then(uloq)
                .when(orres_str.str.starts_with("<"))
                .then(lloq_val)
                .otherwise(pl.lit(None))
            )
        else:
            missing_rule = pl.lit(None)

        expr = pl.when(stresn.is_not_null()).then(stresn_rule).otherwise(missing_rule)
    else:
        # No ULOQ column
        stresn_rule = pl.when(stresn < lloq).then(lloq_val).otherwise(stresn)
        if orres_col:
            orres_str = pl.col(orres_col).cast(pl.Utf8)
            missing_rule = (
                pl.when(orres_str.str.starts_with("<")).then(lloq_val).otherwise(pl.lit(None))
            )
        else:
            missing_rule = pl.lit(None)

        expr = pl.when(stresn.is_not_null()).then(stresn_rule).otherwise(missing_rule)

    if round_digits is not None:
        expr = expr.round(round_digits)

    return self._chain(expr.alias(target))

event_flag

event_flag(
    target,
    *,
    aval_col,
    cutoff,
    by,
    severity_col="AVALC",
    severity_values=None,
    flag_value="Y",
    no_event_value="N"
)

Flag whether a reactogenicity event occurred at least once per by group.

A record has an event if aval_col > cutoff, or severity_col is in severity_values (default ["Y", "MILD", "MODERATE", "SEVERE"]; [] means no value counts). Every record of a group with an event gets flag_value. In a group with no event, a record gets no_event_value when it shows no event (aval_col <= cutoff, or severity_col is "N"), and null when it has no assessable data (both missing). So a diary with only missing records gets null, not no_event_value.

by has no default: one event must not spread to the other FAOBJ or ATPTREF of the subject. severity_col=None uses aval_col only.

Materialises the current pipeline.

Based on admiralvaccine::derive_vars_event_flag (new_var1 behaviour).

Example::

.event_flag("EVENTFL", aval_col="AVAL", cutoff=2.5,
            by=["USUBJID", "FAOBJ", "ATPTREF"])
References

admiralvaccine derive_vars_event_flag (pharmaverse), new_var1: AVALC in Y, MILD, MODERATE, SEVERE; no default by_vars; a record with missing AVAL and AVALC gets NA. FDA toxicity grading scale (2007) for the severity grades. ADR-0027.

Source code in src/fleet/adam/vaccine_namespace.py
def event_flag(
    self,
    target: str,
    *,
    aval_col: str,
    cutoff: float,
    by: list[str],
    severity_col: str | None = "AVALC",
    severity_values: list[str] | None = None,
    flag_value: str = "Y",
    no_event_value: str = "N",
) -> Self:
    """
    Flag whether a reactogenicity event occurred at least once per *by* group.

    A record has an event if *aval_col* > *cutoff*, or *severity_col* is
    in *severity_values* (default ``["Y", "MILD", "MODERATE", "SEVERE"]``;
    ``[]`` means no value counts).  Every record of a group with an event
    gets *flag_value*.  In a group with no event, a record gets
    *no_event_value* when it shows no event (*aval_col* <= *cutoff*, or
    *severity_col* is ``"N"``), and null when it has no assessable data
    (both missing).  So a diary with only missing records gets null, not
    *no_event_value*.

    *by* has no default: one event must not spread to the other FAOBJ or
    ATPTREF of the subject.  ``severity_col=None`` uses *aval_col* only.

    Materialises the current pipeline.

    Based on ``admiralvaccine::derive_vars_event_flag`` (new_var1 behaviour).

    Example::

        .event_flag("EVENTFL", aval_col="AVAL", cutoff=2.5,
                    by=["USUBJID", "FAOBJ", "ATPTREF"])

    References:
        admiralvaccine ``derive_vars_event_flag`` (pharmaverse), ``new_var1``:
        AVALC in Y, MILD, MODERATE, SEVERE; no default ``by_vars``; a record
        with missing AVAL and AVALC gets NA. FDA toxicity grading scale (2007)
        for the severity grades. ADR-0027.
    """
    sev_vals = (
        ["Y", "MILD", "MODERATE", "SEVERE"] if severity_values is None else severity_values
    )
    aval = pl.col(aval_col)
    row_event = aval > cutoff
    row_no_event = aval <= cutoff
    if severity_col is not None:
        sev = pl.col(severity_col)
        row_event = row_event | sev.is_in(sev_vals).fill_null(False)
        row_no_event = row_no_event | (sev == "N").fill_null(False)

    # Kleene any, as R any(): True, else null when a record is unknown, else False.
    any_event = row_event.any(ignore_nulls=False).over(by)
    return self._chain(
        pl.when(any_event)
        .then(pl.lit(flag_value))
        .when(row_no_event)
        .then(pl.lit(no_event_value))
        .otherwise(pl.lit(None, dtype=pl.String))
        .alias(target),
        verb="event_flag",
    )

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

Metabolic — df.adam.metabolic

fleet.adam.MetabolicNamespace

Bases: SharedADaMVerbsMixin

Immutable pipeline builder for ADaM metabolic / cardiometabolic derivations.

Inherits shared verbs from SharedADaMVerbsMixin.

Source code in src/fleet/adam/metabolic_namespace.py
class MetabolicNamespace(SharedADaMVerbsMixin):
    """
    Immutable pipeline builder for ADaM metabolic / cardiometabolic derivations.

    Inherits shared verbs from ``SharedADaMVerbsMixin``.
    """

    # ------------------------------------------------------------------ #
    # 1. waist_hip_ratio — WSTCIR / HIPCIR                               #
    # ------------------------------------------------------------------ #

    def waist_hip_ratio(
        self,
        target: str,
        *,
        waist_col: str,
        hip_col: str,
        round_digits: int | None = 3,
    ) -> Self:
        """Derive waist-to-hip ratio: ``waist_col / hip_col``.

        Both columns must be in the same unit.  A hip circumference of 0
        gives null.

        Args:
            target: Name of the output column.
            waist_col: Column containing waist circumference.
            hip_col: Column containing hip circumference.
            round_digits: Decimal places to round to (default ``3``).

        Returns:
            Self: The namespace with *target* appended.

        Examples:
            Derive waist-to-hip ratio::

                advs = (
                    vs_raw.adam.metabolic
                    .waist_hip_ratio("WAISTHIP", waist_col="WSTCIR",
                                     hip_col="HIPCIR")
                    .to_frame()
                )
        """
        expr = pl.when(pl.col(hip_col) != 0).then(pl.col(waist_col) / pl.col(hip_col))
        if round_digits is not None:
            expr = expr.round(round_digits)
        return self._chain(expr.alias(target))

    # ------------------------------------------------------------------ #
    # 2. waist_height_ratio — WSTCIR / height                            #
    # ------------------------------------------------------------------ #

    def waist_height_ratio(
        self,
        target: str,
        *,
        waist_col: str,
        height_col: str,
        round_digits: int | None = 3,
    ) -> Self:
        """Derive waist-to-height ratio: ``waist_col / height_col``.

        Both columns must be in the same unit.  A height of 0 gives null.

        Args:
            target: Name of the output column.
            waist_col: Column containing waist circumference.
            height_col: Column containing height.
            round_digits: Decimal places to round to (default ``3``).

        Returns:
            Self: The namespace with *target* appended.

        Examples:
            Derive waist-to-height ratio::

                advs = (
                    vs_raw.adam.metabolic
                    .waist_height_ratio("WAISTHGT", waist_col="WSTCIR",
                                        height_col="HEIGHT")
                    .to_frame()
                )
        """
        expr = pl.when(pl.col(height_col) != 0).then(pl.col(waist_col) / pl.col(height_col))
        if round_digits is not None:
            expr = expr.round(round_digits)
        return self._chain(expr.alias(target))

    # ------------------------------------------------------------------ #
    # 3. body_fat_pct — Deurenberg equation                              #
    # ------------------------------------------------------------------ #

    def body_fat_pct(
        self,
        target: str,
        *,
        bmi_col: str,
        age_col: str,
        sex_col: str,
        sex_male_value: str = "M",
        sex_female_value: str = "F",
        round_digits: int | None = 1,
    ) -> Self:
        """Estimate body fat percentage using the Deurenberg formula.

        ``BF% = 1.2 × BMI + 0.23 × age − 10.8 × sex_num − 5.4``
        where sex_num = 1 (male) or 0 (female).  Any other sex value (null,
        ``U``, ``UNDIFFERENTIATED``) gives null, because the equation has no
        value for it.

        Args:
            target: Name of the output column.
            bmi_col: Column containing BMI.
            age_col: Column containing age in years.
            sex_col: Column containing sex code.
            sex_male_value: Value indicating male (default ``"M"``).
            sex_female_value: Value indicating female (default ``"F"``).
            round_digits: Decimal places to round to (default ``1``).

        Returns:
            Self: The namespace with *target* appended.

        Examples:
            Estimate body fat percentage::

                advs = (
                    vs_raw.adam.metabolic
                    .body_fat_pct("BFPCT", bmi_col="BMI", age_col="AGE",
                                  sex_col="SEX")
                    .to_frame()
                )

        References:
            Deurenberg P, Weststrate JA, Seidell JC. Body mass index as a measure of
            body fatness: age- and sex-specific prediction formulas. Br J Nutr.
            1991;65(2):105-114. Constants 1.2, 0.23, 10.8 and 5.4 are the adult
            equation; admiralmetabolic ships the same rule. CDISC CT C66731 (SEX) also
            holds U and UNDIFFERENTIATED, for which the equation has no value.
        """
        sex = pl.col(sex_col)
        sex_num = (
            pl.when(sex == sex_male_value)
            .then(pl.lit(1.0))
            .when(sex == sex_female_value)
            .then(pl.lit(0.0))
        )
        expr = 1.2 * pl.col(bmi_col) + 0.23 * pl.col(age_col) - 10.8 * sex_num - 5.4
        if round_digits is not None:
            expr = expr.round(round_digits)
        return self._chain(expr.alias(target))

    # ------------------------------------------------------------------ #
    # 4. visceral_fat_flag — flag excessive waist circumference           #
    # ------------------------------------------------------------------ #

    def visceral_fat_flag(
        self,
        target: str,
        *,
        waist_col: str,
        sex_col: str,
        sex_male_value: str = "M",
        sex_female_value: str = "F",
        male_threshold: float = 102.0,
        female_threshold: float = 88.0,
        flag_value: str = "Y",
    ) -> Self:
        """Flag subjects with abdominal obesity by waist circumference.

        Default ATP III / NCEP thresholds: male ≥ 102 cm, female ≥ 88 cm.
        Any other sex value (null, ``U``, ``UNDIFFERENTIATED``) gets no flag.

        Args:
            target: Name of the output flag column.
            waist_col: Column containing waist circumference in cm.
            sex_col: Column containing sex code.
            sex_male_value: Value indicating male (default ``"M"``).
            sex_female_value: Value indicating female (default ``"F"``).
            male_threshold: Threshold for males (default ``102.0``).
            female_threshold: Threshold for females (default ``88.0``).
            flag_value: Value to assign (default ``"Y"``).

        Returns:
            Self: The namespace with *target* appended.

        Examples:
            Flag abdominal obesity::

                advs = (
                    vs_raw.adam.metabolic
                    .visceral_fat_flag("ABDFL", waist_col="WSTCIR",
                                       sex_col="SEX")
                    .to_frame()
                )

        References:
            Grundy SM et al. Diagnosis and management of the metabolic syndrome: an
            AHA/NHLBI scientific statement. Circulation. 2005;112:2735-2752: waist
            circumference >= 102 cm (men) and >= 88 cm (women). NCEP ATP III (2001)
            states the same cut-offs as strictly greater; IDF (2005) uses 94 and 80 cm
            for Europids. Check the SAP for the population.
        """
        is_male = pl.col(sex_col) == sex_male_value
        is_female = pl.col(sex_col) == sex_female_value
        waist = pl.col(waist_col)
        return self._chain(
            pl.when(
                (is_male & (waist >= male_threshold)) | (is_female & (waist >= female_threshold))
            )
            .then(pl.lit(flag_value))
            .otherwise(pl.lit(None))
            .alias(target)
        )

    # ------------------------------------------------------------------ #
    # 5. bmi_category_adult — WHO adult BMI class label                   #
    # ------------------------------------------------------------------ #

    def bmi_category_adult(
        self,
        target: str,
        *,
        bmi_col: str,
        labels: dict[str, float] | None = None,
    ) -> Self:
        """Categorise an adult BMI with the WHO cut-offs.

        Default classes: Underweight (< 18.5), Normal weight (18.5 to < 25.0),
        Overweight (25.0 to < 30.0), Obese (>= 30.0).  A null, NaN or infinite
        BMI gets null.  For a child, use ``peds.bmi_percentile_category``.

        Args:
            target: Name of the output column.
            bmi_col: Column containing the BMI value.
            labels: Optional ``{"label": upper_bound}`` dict, in increasing
                order, to override the default classes.  A BMI that is not
                below the last bound gets null.

        Returns:
            Self: The namespace with *target* appended.

        References:
            WHO. Obesity: preventing and managing the global epidemic. WHO Technical
            Report Series 894 (2000): adult classes at 18.5, 25.0 and 30.0 kg/m2.
            admiral ``derive_vars_cat``: a missing value gets no class.
            ADR-0026: the adult rule lives in ``metabolic``.

        Examples:
            Categorise an adult BMI::

                adsl = (
                    dm_raw.adam.metabolic
                    .bmi_category_adult("BMICG", bmi_col="BMI")
                    .to_frame()
                )
        """
        thresholds = (
            list(labels.items())
            if labels is not None
            else [
                ("Underweight", 18.5),
                ("Normal weight", 25.0),
                ("Overweight", 30.0),
                ("Obese", float("inf")),
            ]
        )
        bmi = pl.col(bmi_col).cast(pl.Float64).fill_nan(None)
        chain = pl.when(bmi.is_null()).then(pl.lit(None, dtype=pl.String))
        for label, upper in thresholds:
            chain = chain.when(bmi < upper).then(pl.lit(label))
        return self._chain(chain.otherwise(pl.lit(None, dtype=pl.String)).alias(target))

waist_hip_ratio

waist_hip_ratio(
    target, *, waist_col, hip_col, round_digits=3
)

Derive waist-to-hip ratio: waist_col / hip_col.

Both columns must be in the same unit. A hip circumference of 0 gives null.

Parameters:

Name Type Description Default
target str

Name of the output column.

required
waist_col str

Column containing waist circumference.

required
hip_col str

Column containing hip circumference.

required
round_digits int | None

Decimal places to round to (default 3).

3

Returns:

Name Type Description
Self Self

The namespace with target appended.

Examples:

Derive waist-to-hip ratio::

advs = (
    vs_raw.adam.metabolic
    .waist_hip_ratio("WAISTHIP", waist_col="WSTCIR",
                     hip_col="HIPCIR")
    .to_frame()
)
Source code in src/fleet/adam/metabolic_namespace.py
def waist_hip_ratio(
    self,
    target: str,
    *,
    waist_col: str,
    hip_col: str,
    round_digits: int | None = 3,
) -> Self:
    """Derive waist-to-hip ratio: ``waist_col / hip_col``.

    Both columns must be in the same unit.  A hip circumference of 0
    gives null.

    Args:
        target: Name of the output column.
        waist_col: Column containing waist circumference.
        hip_col: Column containing hip circumference.
        round_digits: Decimal places to round to (default ``3``).

    Returns:
        Self: The namespace with *target* appended.

    Examples:
        Derive waist-to-hip ratio::

            advs = (
                vs_raw.adam.metabolic
                .waist_hip_ratio("WAISTHIP", waist_col="WSTCIR",
                                 hip_col="HIPCIR")
                .to_frame()
            )
    """
    expr = pl.when(pl.col(hip_col) != 0).then(pl.col(waist_col) / pl.col(hip_col))
    if round_digits is not None:
        expr = expr.round(round_digits)
    return self._chain(expr.alias(target))

waist_height_ratio

waist_height_ratio(
    target, *, waist_col, height_col, round_digits=3
)

Derive waist-to-height ratio: waist_col / height_col.

Both columns must be in the same unit. A height of 0 gives null.

Parameters:

Name Type Description Default
target str

Name of the output column.

required
waist_col str

Column containing waist circumference.

required
height_col str

Column containing height.

required
round_digits int | None

Decimal places to round to (default 3).

3

Returns:

Name Type Description
Self Self

The namespace with target appended.

Examples:

Derive waist-to-height ratio::

advs = (
    vs_raw.adam.metabolic
    .waist_height_ratio("WAISTHGT", waist_col="WSTCIR",
                        height_col="HEIGHT")
    .to_frame()
)
Source code in src/fleet/adam/metabolic_namespace.py
def waist_height_ratio(
    self,
    target: str,
    *,
    waist_col: str,
    height_col: str,
    round_digits: int | None = 3,
) -> Self:
    """Derive waist-to-height ratio: ``waist_col / height_col``.

    Both columns must be in the same unit.  A height of 0 gives null.

    Args:
        target: Name of the output column.
        waist_col: Column containing waist circumference.
        height_col: Column containing height.
        round_digits: Decimal places to round to (default ``3``).

    Returns:
        Self: The namespace with *target* appended.

    Examples:
        Derive waist-to-height ratio::

            advs = (
                vs_raw.adam.metabolic
                .waist_height_ratio("WAISTHGT", waist_col="WSTCIR",
                                    height_col="HEIGHT")
                .to_frame()
            )
    """
    expr = pl.when(pl.col(height_col) != 0).then(pl.col(waist_col) / pl.col(height_col))
    if round_digits is not None:
        expr = expr.round(round_digits)
    return self._chain(expr.alias(target))

body_fat_pct

body_fat_pct(
    target,
    *,
    bmi_col,
    age_col,
    sex_col,
    sex_male_value="M",
    sex_female_value="F",
    round_digits=1
)

Estimate body fat percentage using the Deurenberg formula.

BF% = 1.2 × BMI + 0.23 × age − 10.8 × sex_num − 5.4 where sex_num = 1 (male) or 0 (female). Any other sex value (null, U, UNDIFFERENTIATED) gives null, because the equation has no value for it.

Parameters:

Name Type Description Default
target str

Name of the output column.

required
bmi_col str

Column containing BMI.

required
age_col str

Column containing age in years.

required
sex_col str

Column containing sex code.

required
sex_male_value str

Value indicating male (default "M").

'M'
sex_female_value str

Value indicating female (default "F").

'F'
round_digits int | None

Decimal places to round to (default 1).

1

Returns:

Name Type Description
Self Self

The namespace with target appended.

Examples:

Estimate body fat percentage::

advs = (
    vs_raw.adam.metabolic
    .body_fat_pct("BFPCT", bmi_col="BMI", age_col="AGE",
                  sex_col="SEX")
    .to_frame()
)
References

Deurenberg P, Weststrate JA, Seidell JC. Body mass index as a measure of body fatness: age- and sex-specific prediction formulas. Br J Nutr. 1991;65(2):105-114. Constants 1.2, 0.23, 10.8 and 5.4 are the adult equation; admiralmetabolic ships the same rule. CDISC CT C66731 (SEX) also holds U and UNDIFFERENTIATED, for which the equation has no value.

Source code in src/fleet/adam/metabolic_namespace.py
def body_fat_pct(
    self,
    target: str,
    *,
    bmi_col: str,
    age_col: str,
    sex_col: str,
    sex_male_value: str = "M",
    sex_female_value: str = "F",
    round_digits: int | None = 1,
) -> Self:
    """Estimate body fat percentage using the Deurenberg formula.

    ``BF% = 1.2 × BMI + 0.23 × age − 10.8 × sex_num − 5.4``
    where sex_num = 1 (male) or 0 (female).  Any other sex value (null,
    ``U``, ``UNDIFFERENTIATED``) gives null, because the equation has no
    value for it.

    Args:
        target: Name of the output column.
        bmi_col: Column containing BMI.
        age_col: Column containing age in years.
        sex_col: Column containing sex code.
        sex_male_value: Value indicating male (default ``"M"``).
        sex_female_value: Value indicating female (default ``"F"``).
        round_digits: Decimal places to round to (default ``1``).

    Returns:
        Self: The namespace with *target* appended.

    Examples:
        Estimate body fat percentage::

            advs = (
                vs_raw.adam.metabolic
                .body_fat_pct("BFPCT", bmi_col="BMI", age_col="AGE",
                              sex_col="SEX")
                .to_frame()
            )

    References:
        Deurenberg P, Weststrate JA, Seidell JC. Body mass index as a measure of
        body fatness: age- and sex-specific prediction formulas. Br J Nutr.
        1991;65(2):105-114. Constants 1.2, 0.23, 10.8 and 5.4 are the adult
        equation; admiralmetabolic ships the same rule. CDISC CT C66731 (SEX) also
        holds U and UNDIFFERENTIATED, for which the equation has no value.
    """
    sex = pl.col(sex_col)
    sex_num = (
        pl.when(sex == sex_male_value)
        .then(pl.lit(1.0))
        .when(sex == sex_female_value)
        .then(pl.lit(0.0))
    )
    expr = 1.2 * pl.col(bmi_col) + 0.23 * pl.col(age_col) - 10.8 * sex_num - 5.4
    if round_digits is not None:
        expr = expr.round(round_digits)
    return self._chain(expr.alias(target))

visceral_fat_flag

visceral_fat_flag(
    target,
    *,
    waist_col,
    sex_col,
    sex_male_value="M",
    sex_female_value="F",
    male_threshold=102.0,
    female_threshold=88.0,
    flag_value="Y"
)

Flag subjects with abdominal obesity by waist circumference.

Default ATP III / NCEP thresholds: male ≥ 102 cm, female ≥ 88 cm. Any other sex value (null, U, UNDIFFERENTIATED) gets no flag.

Parameters:

Name Type Description Default
target str

Name of the output flag column.

required
waist_col str

Column containing waist circumference in cm.

required
sex_col str

Column containing sex code.

required
sex_male_value str

Value indicating male (default "M").

'M'
sex_female_value str

Value indicating female (default "F").

'F'
male_threshold float

Threshold for males (default 102.0).

102.0
female_threshold float

Threshold for females (default 88.0).

88.0
flag_value str

Value to assign (default "Y").

'Y'

Returns:

Name Type Description
Self Self

The namespace with target appended.

Examples:

Flag abdominal obesity::

advs = (
    vs_raw.adam.metabolic
    .visceral_fat_flag("ABDFL", waist_col="WSTCIR",
                       sex_col="SEX")
    .to_frame()
)
References

Grundy SM et al. Diagnosis and management of the metabolic syndrome: an AHA/NHLBI scientific statement. Circulation. 2005;112:2735-2752: waist circumference >= 102 cm (men) and >= 88 cm (women). NCEP ATP III (2001) states the same cut-offs as strictly greater; IDF (2005) uses 94 and 80 cm for Europids. Check the SAP for the population.

Source code in src/fleet/adam/metabolic_namespace.py
def visceral_fat_flag(
    self,
    target: str,
    *,
    waist_col: str,
    sex_col: str,
    sex_male_value: str = "M",
    sex_female_value: str = "F",
    male_threshold: float = 102.0,
    female_threshold: float = 88.0,
    flag_value: str = "Y",
) -> Self:
    """Flag subjects with abdominal obesity by waist circumference.

    Default ATP III / NCEP thresholds: male ≥ 102 cm, female ≥ 88 cm.
    Any other sex value (null, ``U``, ``UNDIFFERENTIATED``) gets no flag.

    Args:
        target: Name of the output flag column.
        waist_col: Column containing waist circumference in cm.
        sex_col: Column containing sex code.
        sex_male_value: Value indicating male (default ``"M"``).
        sex_female_value: Value indicating female (default ``"F"``).
        male_threshold: Threshold for males (default ``102.0``).
        female_threshold: Threshold for females (default ``88.0``).
        flag_value: Value to assign (default ``"Y"``).

    Returns:
        Self: The namespace with *target* appended.

    Examples:
        Flag abdominal obesity::

            advs = (
                vs_raw.adam.metabolic
                .visceral_fat_flag("ABDFL", waist_col="WSTCIR",
                                   sex_col="SEX")
                .to_frame()
            )

    References:
        Grundy SM et al. Diagnosis and management of the metabolic syndrome: an
        AHA/NHLBI scientific statement. Circulation. 2005;112:2735-2752: waist
        circumference >= 102 cm (men) and >= 88 cm (women). NCEP ATP III (2001)
        states the same cut-offs as strictly greater; IDF (2005) uses 94 and 80 cm
        for Europids. Check the SAP for the population.
    """
    is_male = pl.col(sex_col) == sex_male_value
    is_female = pl.col(sex_col) == sex_female_value
    waist = pl.col(waist_col)
    return self._chain(
        pl.when(
            (is_male & (waist >= male_threshold)) | (is_female & (waist >= female_threshold))
        )
        .then(pl.lit(flag_value))
        .otherwise(pl.lit(None))
        .alias(target)
    )

bmi_category_adult

bmi_category_adult(target, *, bmi_col, labels=None)

Categorise an adult BMI with the WHO cut-offs.

Default classes: Underweight (< 18.5), Normal weight (18.5 to < 25.0), Overweight (25.0 to < 30.0), Obese (>= 30.0). A null, NaN or infinite BMI gets null. For a child, use peds.bmi_percentile_category.

Parameters:

Name Type Description Default
target str

Name of the output column.

required
bmi_col str

Column containing the BMI value.

required
labels dict[str, float] | None

Optional {"label": upper_bound} dict, in increasing order, to override the default classes. A BMI that is not below the last bound gets null.

None

Returns:

Name Type Description
Self Self

The namespace with target appended.

References

WHO. Obesity: preventing and managing the global epidemic. WHO Technical Report Series 894 (2000): adult classes at 18.5, 25.0 and 30.0 kg/m2. admiral derive_vars_cat: a missing value gets no class. ADR-0026: the adult rule lives in metabolic.

Examples:

Categorise an adult BMI::

adsl = (
    dm_raw.adam.metabolic
    .bmi_category_adult("BMICG", bmi_col="BMI")
    .to_frame()
)
Source code in src/fleet/adam/metabolic_namespace.py
def bmi_category_adult(
    self,
    target: str,
    *,
    bmi_col: str,
    labels: dict[str, float] | None = None,
) -> Self:
    """Categorise an adult BMI with the WHO cut-offs.

    Default classes: Underweight (< 18.5), Normal weight (18.5 to < 25.0),
    Overweight (25.0 to < 30.0), Obese (>= 30.0).  A null, NaN or infinite
    BMI gets null.  For a child, use ``peds.bmi_percentile_category``.

    Args:
        target: Name of the output column.
        bmi_col: Column containing the BMI value.
        labels: Optional ``{"label": upper_bound}`` dict, in increasing
            order, to override the default classes.  A BMI that is not
            below the last bound gets null.

    Returns:
        Self: The namespace with *target* appended.

    References:
        WHO. Obesity: preventing and managing the global epidemic. WHO Technical
        Report Series 894 (2000): adult classes at 18.5, 25.0 and 30.0 kg/m2.
        admiral ``derive_vars_cat``: a missing value gets no class.
        ADR-0026: the adult rule lives in ``metabolic``.

    Examples:
        Categorise an adult BMI::

            adsl = (
                dm_raw.adam.metabolic
                .bmi_category_adult("BMICG", bmi_col="BMI")
                .to_frame()
            )
    """
    thresholds = (
        list(labels.items())
        if labels is not None
        else [
            ("Underweight", 18.5),
            ("Normal weight", 25.0),
            ("Overweight", 30.0),
            ("Obese", float("inf")),
        ]
    )
    bmi = pl.col(bmi_col).cast(pl.Float64).fill_nan(None)
    chain = pl.when(bmi.is_null()).then(pl.lit(None, dtype=pl.String))
    for label, upper in thresholds:
        chain = chain.when(bmi < upper).then(pl.lit(label))
    return self._chain(chain.otherwise(pl.lit(None, dtype=pl.String)).alias(target))

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

Neuroscience — df.adam.neuro

fleet.adam.NeuroNamespace

Bases: SharedADaMVerbsMixin

Immutable pipeline builder for ADaM neuroscience derivations.

Inherits shared verbs from SharedADaMVerbsMixin.

Source code in src/fleet/adam/neuro_namespace.py
class NeuroNamespace(SharedADaMVerbsMixin):
    """
    Immutable pipeline builder for ADaM neuroscience derivations.

    Inherits shared verbs from ``SharedADaMVerbsMixin``.
    """

    # ------------------------------------------------------------------ #
    # 1. centiloid — amyloid PET SUVR → Centiloid scale                  #
    # ------------------------------------------------------------------ #

    def centiloid(
        self,
        target: str,
        *,
        suvr_col: str,
        slope: float | None = None,
        intercept: float | None = None,
        tracer: str | None = None,
        pipeline: str | None = None,
        ref_region: str = "Whole Cerebellum",
        round_digits: int | None = 2,
    ) -> Self:
        """Convert amyloid PET SUVR to the Centiloid scale.

        ``Centiloid = slope * SUVR + intercept``.  Provide either *slope* and
        *intercept* directly or *tracer* + *pipeline* for a built-in lookup.

        Args:
            target: Name of the output column.
            suvr_col: Column containing the SUVR value.
            slope: Calibration slope (provide with *intercept*).
            intercept: Calibration intercept.
            tracer: Tracer name for built-in lookup.
            pipeline: Pipeline name for built-in lookup.
            ref_region: Reference region (default ``"Whole Cerebellum"``).
            round_digits: Decimal places to round to (default ``2``).

        Returns:
            Self: The namespace with *target* appended.

        Examples:
            Convert SUVR to Centiloid with custom parameters::

                adapet = (
                    pet_raw.adam.neuro
                    .centiloid("CLV", suvr_col="SUVR",
                               slope=183.07, intercept=-177.26)
                    .to_frame()
                )

        References:
            Klunk WE et al. The Centiloid Project: standardizing quantitative amyloid
            plaque estimation by PET. Alzheimers Dement. 2015;11(1):1-15. The built-in
            tracer and pipeline calibrations follow admiralneuro
            ``derive_param_centiloid`` (pharmaverse).
        """
        if slope is not None and intercept is not None:
            s, i = slope, intercept
        elif tracer and pipeline:
            key = (tracer, pipeline, ref_region)
            if key not in _CENTILOID_CALIBRATIONS:
                valid = list(_CENTILOID_CALIBRATIONS.keys())
                raise DerivationError(
                    f"No calibration found for tracer={tracer!r}, "
                    f"pipeline={pipeline!r}, ref_region={ref_region!r}. "
                    f"Valid combinations: {valid}"
                )
            s, i = _CENTILOID_CALIBRATIONS[key]
        else:
            raise DerivationError("Provide either (slope, intercept) or (tracer, pipeline).")

        expr = pl.lit(s) * pl.col(suvr_col) + pl.lit(i)
        if round_digits is not None:
            expr = expr.round(round_digits)
        return self._chain(expr.alias(target))

    # ------------------------------------------------------------------ #
    # 2. mmse_category — MMSE severity categories                        #
    # ------------------------------------------------------------------ #

    def mmse_category(
        self,
        target: str,
        *,
        score_col: str,
        normal_threshold: int = 24,
        mild_threshold: int = 19,
        moderate_threshold: int = 10,
    ) -> Self:
        """Categorise MMSE total score into severity levels.

        Defaults: Normal >= 24, Mild 19-23, Moderate 10-18, Severe 0-9.
        Each lower bound is an argument, so a SAP that uses other bands
        passes its own cut-offs.

        Args:
            target: Name of the output column.
            score_col: Column containing the MMSE total score.
            normal_threshold: Lower bound for Normal (default ``24``).
            mild_threshold: Lower bound for Mild (default ``19``).
            moderate_threshold: Lower bound for Moderate (default ``10``).

        Returns:
            Self: The namespace with *target* appended.

        Examples:
            Derive MMSE category::

                adcog = (
                    cog_raw.adam.neuro
                    .mmse_category("MMSECG", score_col="AVAL")
                    .to_frame()
                )

            Use the bands of a SAP that puts Mild at 21-26::

                adcog = (
                    cog_raw.adam.neuro
                    .mmse_category("MMSECG", score_col="AVAL",
                                   normal_threshold=27, mild_threshold=21)
                    .to_frame()
                )

        References:
            Folstein MF, Folstein SE, McHugh PR. Mini-mental state. J Psychiatr Res.
            1975;12:189-198 (the instrument). Default bands: Tombaugh TN, McIntyre
            NJ. The Mini-Mental State Examination: a comprehensive review. J Am
            Geriatr Soc. 1992;40:922-935 (24-30 normal, 19-23 mild, 10-18 moderate,
            9 and below severe). Other schemes are in use, for example mild 21-26
            and moderate 10-20; take the cut-offs from the SAP.
        """
        score = pl.col(score_col)
        return self._chain(
            pl.when(score >= normal_threshold)
            .then(pl.lit("Normal"))
            .when(score >= mild_threshold)
            .then(pl.lit("Mild"))
            .when(score >= moderate_threshold)
            .then(pl.lit("Moderate"))
            .when(score >= 0)
            .then(pl.lit("Severe"))
            .otherwise(pl.lit(None))
            .alias(target)
        )

    # ------------------------------------------------------------------ #
    # 3. cdrsob_total — CDR Sum of Boxes total                           #
    # ------------------------------------------------------------------ #

    def cdrsob_total(
        self,
        target: str,
        *,
        domain_cols: list[str],
        round_digits: int | None = 1,
    ) -> Self:
        """Compute CDR Sum of Boxes (CDR-SoB) from domain box scores.

        Standard domains: Memory, Orientation, Judgment, Community Affairs,
        Home & Hobbies, Personal Care (6 boxes, each 0–3).

        Args:
            target: Name of the output column.
            domain_cols: List of CDR domain score columns.
            round_digits: Decimal places to round to (default ``1``).

        Returns:
            Self: The namespace with *target* appended.

        Examples:
            Derive CDR-SoB total from 6 domains::

                adcog = (
                    cog_raw.adam.neuro
                    .cdrsob_total("CDRSOB", domain_cols=[
                        "CDRMEM", "CDRORNT", "CDRJDGM",
                        "CDRCOMM", "CDRHOME", "CDRPERS"])
                    .to_frame()
                )
        """
        total = sum(pl.col(c) for c in domain_cols)  # type: ignore[arg-type]
        if round_digits is not None:
            total = total.round(round_digits)
        return self._chain(total.alias(target))

    # ------------------------------------------------------------------ #
    # 4. moca_category — MoCA severity categories                        #
    # ------------------------------------------------------------------ #

    def moca_category(
        self,
        target: str,
        *,
        score_col: str,
        normal_threshold: int = 26,
        mci_threshold: int = 18,
    ) -> Self:
        """Categorise MoCA total score into Normal / MCI / Impaired.

        Defaults: Normal ≥ 26, MCI 18–25, Impaired < 18.

        Args:
            target: Name of the output column.
            score_col: Column containing the MoCA total score.
            normal_threshold: Lower bound for Normal (default ``26``).
            mci_threshold: Lower bound for MCI (default ``18``).

        Returns:
            Self: The namespace with *target* appended.

        Examples:
            Derive MoCA category::

                adcog = (
                    cog_raw.adam.neuro
                    .moca_category("MOACG", score_col="AVAL")
                    .to_frame()
                )

        References:
            Nasreddine ZS et al. The Montreal Cognitive Assessment, MoCA. J Am Geriatr
            Soc. 2005;53:695-699: a total of 26 or more is normal. The MCI lower
            bound of 18 is not fixed by the instrument; check the SAP.
        """
        score = pl.col(score_col)
        return self._chain(
            pl.when(score >= normal_threshold)
            .then(pl.lit("Normal"))
            .when(score >= mci_threshold)
            .then(pl.lit("MCI"))
            .when(score >= 0)
            .then(pl.lit("Impaired"))
            .otherwise(pl.lit(None))
            .alias(target)
        )

    # ------------------------------------------------------------------ #
    # 5. panss_total — PANSS composite total                             #
    # ------------------------------------------------------------------ #

    def panss_total(
        self,
        target: str,
        *,
        positive_col: str,
        negative_col: str,
        general_col: str,
    ) -> Self:
        """Compute PANSS total = positive + negative + general subscales.

        Args:
            target: Name of the output column.
            positive_col: Column containing the positive subscale total.
            negative_col: Column containing the negative subscale total.
            general_col: Column containing the general subscale total.

        Returns:
            Self: The namespace with *target* appended.

        Examples:
            Derive PANSS total score::

                adnpi = (
                    npi_raw.adam.neuro
                    .panss_total("PANSSTOT", positive_col="PANSSPOS",
                                 negative_col="PANSSNEG",
                                 general_col="PANSSGEN")
                    .to_frame()
                )
        """
        return self._chain(
            (pl.col(positive_col) + pl.col(negative_col) + pl.col(general_col)).alias(target)
        )

centiloid

centiloid(
    target,
    *,
    suvr_col,
    slope=None,
    intercept=None,
    tracer=None,
    pipeline=None,
    ref_region="Whole Cerebellum",
    round_digits=2
)

Convert amyloid PET SUVR to the Centiloid scale.

Centiloid = slope * SUVR + intercept. Provide either slope and intercept directly or tracer + pipeline for a built-in lookup.

Parameters:

Name Type Description Default
target str

Name of the output column.

required
suvr_col str

Column containing the SUVR value.

required
slope float | None

Calibration slope (provide with intercept).

None
intercept float | None

Calibration intercept.

None
tracer str | None

Tracer name for built-in lookup.

None
pipeline str | None

Pipeline name for built-in lookup.

None
ref_region str

Reference region (default "Whole Cerebellum").

'Whole Cerebellum'
round_digits int | None

Decimal places to round to (default 2).

2

Returns:

Name Type Description
Self Self

The namespace with target appended.

Examples:

Convert SUVR to Centiloid with custom parameters::

adapet = (
    pet_raw.adam.neuro
    .centiloid("CLV", suvr_col="SUVR",
               slope=183.07, intercept=-177.26)
    .to_frame()
)
References

Klunk WE et al. The Centiloid Project: standardizing quantitative amyloid plaque estimation by PET. Alzheimers Dement. 2015;11(1):1-15. The built-in tracer and pipeline calibrations follow admiralneuro derive_param_centiloid (pharmaverse).

Source code in src/fleet/adam/neuro_namespace.py
def centiloid(
    self,
    target: str,
    *,
    suvr_col: str,
    slope: float | None = None,
    intercept: float | None = None,
    tracer: str | None = None,
    pipeline: str | None = None,
    ref_region: str = "Whole Cerebellum",
    round_digits: int | None = 2,
) -> Self:
    """Convert amyloid PET SUVR to the Centiloid scale.

    ``Centiloid = slope * SUVR + intercept``.  Provide either *slope* and
    *intercept* directly or *tracer* + *pipeline* for a built-in lookup.

    Args:
        target: Name of the output column.
        suvr_col: Column containing the SUVR value.
        slope: Calibration slope (provide with *intercept*).
        intercept: Calibration intercept.
        tracer: Tracer name for built-in lookup.
        pipeline: Pipeline name for built-in lookup.
        ref_region: Reference region (default ``"Whole Cerebellum"``).
        round_digits: Decimal places to round to (default ``2``).

    Returns:
        Self: The namespace with *target* appended.

    Examples:
        Convert SUVR to Centiloid with custom parameters::

            adapet = (
                pet_raw.adam.neuro
                .centiloid("CLV", suvr_col="SUVR",
                           slope=183.07, intercept=-177.26)
                .to_frame()
            )

    References:
        Klunk WE et al. The Centiloid Project: standardizing quantitative amyloid
        plaque estimation by PET. Alzheimers Dement. 2015;11(1):1-15. The built-in
        tracer and pipeline calibrations follow admiralneuro
        ``derive_param_centiloid`` (pharmaverse).
    """
    if slope is not None and intercept is not None:
        s, i = slope, intercept
    elif tracer and pipeline:
        key = (tracer, pipeline, ref_region)
        if key not in _CENTILOID_CALIBRATIONS:
            valid = list(_CENTILOID_CALIBRATIONS.keys())
            raise DerivationError(
                f"No calibration found for tracer={tracer!r}, "
                f"pipeline={pipeline!r}, ref_region={ref_region!r}. "
                f"Valid combinations: {valid}"
            )
        s, i = _CENTILOID_CALIBRATIONS[key]
    else:
        raise DerivationError("Provide either (slope, intercept) or (tracer, pipeline).")

    expr = pl.lit(s) * pl.col(suvr_col) + pl.lit(i)
    if round_digits is not None:
        expr = expr.round(round_digits)
    return self._chain(expr.alias(target))

mmse_category

mmse_category(
    target,
    *,
    score_col,
    normal_threshold=24,
    mild_threshold=19,
    moderate_threshold=10
)

Categorise MMSE total score into severity levels.

Defaults: Normal >= 24, Mild 19-23, Moderate 10-18, Severe 0-9. Each lower bound is an argument, so a SAP that uses other bands passes its own cut-offs.

Parameters:

Name Type Description Default
target str

Name of the output column.

required
score_col str

Column containing the MMSE total score.

required
normal_threshold int

Lower bound for Normal (default 24).

24
mild_threshold int

Lower bound for Mild (default 19).

19
moderate_threshold int

Lower bound for Moderate (default 10).

10

Returns:

Name Type Description
Self Self

The namespace with target appended.

Examples:

Derive MMSE category::

adcog = (
    cog_raw.adam.neuro
    .mmse_category("MMSECG", score_col="AVAL")
    .to_frame()
)

Use the bands of a SAP that puts Mild at 21-26::

adcog = (
    cog_raw.adam.neuro
    .mmse_category("MMSECG", score_col="AVAL",
                   normal_threshold=27, mild_threshold=21)
    .to_frame()
)
References

Folstein MF, Folstein SE, McHugh PR. Mini-mental state. J Psychiatr Res. 1975;12:189-198 (the instrument). Default bands: Tombaugh TN, McIntyre NJ. The Mini-Mental State Examination: a comprehensive review. J Am Geriatr Soc. 1992;40:922-935 (24-30 normal, 19-23 mild, 10-18 moderate, 9 and below severe). Other schemes are in use, for example mild 21-26 and moderate 10-20; take the cut-offs from the SAP.

Source code in src/fleet/adam/neuro_namespace.py
def mmse_category(
    self,
    target: str,
    *,
    score_col: str,
    normal_threshold: int = 24,
    mild_threshold: int = 19,
    moderate_threshold: int = 10,
) -> Self:
    """Categorise MMSE total score into severity levels.

    Defaults: Normal >= 24, Mild 19-23, Moderate 10-18, Severe 0-9.
    Each lower bound is an argument, so a SAP that uses other bands
    passes its own cut-offs.

    Args:
        target: Name of the output column.
        score_col: Column containing the MMSE total score.
        normal_threshold: Lower bound for Normal (default ``24``).
        mild_threshold: Lower bound for Mild (default ``19``).
        moderate_threshold: Lower bound for Moderate (default ``10``).

    Returns:
        Self: The namespace with *target* appended.

    Examples:
        Derive MMSE category::

            adcog = (
                cog_raw.adam.neuro
                .mmse_category("MMSECG", score_col="AVAL")
                .to_frame()
            )

        Use the bands of a SAP that puts Mild at 21-26::

            adcog = (
                cog_raw.adam.neuro
                .mmse_category("MMSECG", score_col="AVAL",
                               normal_threshold=27, mild_threshold=21)
                .to_frame()
            )

    References:
        Folstein MF, Folstein SE, McHugh PR. Mini-mental state. J Psychiatr Res.
        1975;12:189-198 (the instrument). Default bands: Tombaugh TN, McIntyre
        NJ. The Mini-Mental State Examination: a comprehensive review. J Am
        Geriatr Soc. 1992;40:922-935 (24-30 normal, 19-23 mild, 10-18 moderate,
        9 and below severe). Other schemes are in use, for example mild 21-26
        and moderate 10-20; take the cut-offs from the SAP.
    """
    score = pl.col(score_col)
    return self._chain(
        pl.when(score >= normal_threshold)
        .then(pl.lit("Normal"))
        .when(score >= mild_threshold)
        .then(pl.lit("Mild"))
        .when(score >= moderate_threshold)
        .then(pl.lit("Moderate"))
        .when(score >= 0)
        .then(pl.lit("Severe"))
        .otherwise(pl.lit(None))
        .alias(target)
    )

cdrsob_total

cdrsob_total(target, *, domain_cols, round_digits=1)

Compute CDR Sum of Boxes (CDR-SoB) from domain box scores.

Standard domains: Memory, Orientation, Judgment, Community Affairs, Home & Hobbies, Personal Care (6 boxes, each 0–3).

Parameters:

Name Type Description Default
target str

Name of the output column.

required
domain_cols list[str]

List of CDR domain score columns.

required
round_digits int | None

Decimal places to round to (default 1).

1

Returns:

Name Type Description
Self Self

The namespace with target appended.

Examples:

Derive CDR-SoB total from 6 domains::

adcog = (
    cog_raw.adam.neuro
    .cdrsob_total("CDRSOB", domain_cols=[
        "CDRMEM", "CDRORNT", "CDRJDGM",
        "CDRCOMM", "CDRHOME", "CDRPERS"])
    .to_frame()
)
Source code in src/fleet/adam/neuro_namespace.py
def cdrsob_total(
    self,
    target: str,
    *,
    domain_cols: list[str],
    round_digits: int | None = 1,
) -> Self:
    """Compute CDR Sum of Boxes (CDR-SoB) from domain box scores.

    Standard domains: Memory, Orientation, Judgment, Community Affairs,
    Home & Hobbies, Personal Care (6 boxes, each 0–3).

    Args:
        target: Name of the output column.
        domain_cols: List of CDR domain score columns.
        round_digits: Decimal places to round to (default ``1``).

    Returns:
        Self: The namespace with *target* appended.

    Examples:
        Derive CDR-SoB total from 6 domains::

            adcog = (
                cog_raw.adam.neuro
                .cdrsob_total("CDRSOB", domain_cols=[
                    "CDRMEM", "CDRORNT", "CDRJDGM",
                    "CDRCOMM", "CDRHOME", "CDRPERS"])
                .to_frame()
            )
    """
    total = sum(pl.col(c) for c in domain_cols)  # type: ignore[arg-type]
    if round_digits is not None:
        total = total.round(round_digits)
    return self._chain(total.alias(target))

moca_category

moca_category(
    target,
    *,
    score_col,
    normal_threshold=26,
    mci_threshold=18
)

Categorise MoCA total score into Normal / MCI / Impaired.

Defaults: Normal ≥ 26, MCI 18–25, Impaired < 18.

Parameters:

Name Type Description Default
target str

Name of the output column.

required
score_col str

Column containing the MoCA total score.

required
normal_threshold int

Lower bound for Normal (default 26).

26
mci_threshold int

Lower bound for MCI (default 18).

18

Returns:

Name Type Description
Self Self

The namespace with target appended.

Examples:

Derive MoCA category::

adcog = (
    cog_raw.adam.neuro
    .moca_category("MOACG", score_col="AVAL")
    .to_frame()
)
References

Nasreddine ZS et al. The Montreal Cognitive Assessment, MoCA. J Am Geriatr Soc. 2005;53:695-699: a total of 26 or more is normal. The MCI lower bound of 18 is not fixed by the instrument; check the SAP.

Source code in src/fleet/adam/neuro_namespace.py
def moca_category(
    self,
    target: str,
    *,
    score_col: str,
    normal_threshold: int = 26,
    mci_threshold: int = 18,
) -> Self:
    """Categorise MoCA total score into Normal / MCI / Impaired.

    Defaults: Normal ≥ 26, MCI 18–25, Impaired < 18.

    Args:
        target: Name of the output column.
        score_col: Column containing the MoCA total score.
        normal_threshold: Lower bound for Normal (default ``26``).
        mci_threshold: Lower bound for MCI (default ``18``).

    Returns:
        Self: The namespace with *target* appended.

    Examples:
        Derive MoCA category::

            adcog = (
                cog_raw.adam.neuro
                .moca_category("MOACG", score_col="AVAL")
                .to_frame()
            )

    References:
        Nasreddine ZS et al. The Montreal Cognitive Assessment, MoCA. J Am Geriatr
        Soc. 2005;53:695-699: a total of 26 or more is normal. The MCI lower
        bound of 18 is not fixed by the instrument; check the SAP.
    """
    score = pl.col(score_col)
    return self._chain(
        pl.when(score >= normal_threshold)
        .then(pl.lit("Normal"))
        .when(score >= mci_threshold)
        .then(pl.lit("MCI"))
        .when(score >= 0)
        .then(pl.lit("Impaired"))
        .otherwise(pl.lit(None))
        .alias(target)
    )

panss_total

panss_total(
    target, *, positive_col, negative_col, general_col
)

Compute PANSS total = positive + negative + general subscales.

Parameters:

Name Type Description Default
target str

Name of the output column.

required
positive_col str

Column containing the positive subscale total.

required
negative_col str

Column containing the negative subscale total.

required
general_col str

Column containing the general subscale total.

required

Returns:

Name Type Description
Self Self

The namespace with target appended.

Examples:

Derive PANSS total score::

adnpi = (
    npi_raw.adam.neuro
    .panss_total("PANSSTOT", positive_col="PANSSPOS",
                 negative_col="PANSSNEG",
                 general_col="PANSSGEN")
    .to_frame()
)
Source code in src/fleet/adam/neuro_namespace.py
def panss_total(
    self,
    target: str,
    *,
    positive_col: str,
    negative_col: str,
    general_col: str,
) -> Self:
    """Compute PANSS total = positive + negative + general subscales.

    Args:
        target: Name of the output column.
        positive_col: Column containing the positive subscale total.
        negative_col: Column containing the negative subscale total.
        general_col: Column containing the general subscale total.

    Returns:
        Self: The namespace with *target* appended.

    Examples:
        Derive PANSS total score::

            adnpi = (
                npi_raw.adam.neuro
                .panss_total("PANSSTOT", positive_col="PANSSPOS",
                             negative_col="PANSSNEG",
                             general_col="PANSSGEN")
                .to_frame()
            )
    """
    return self._chain(
        (pl.col(positive_col) + pl.col(negative_col) + pl.col(general_col)).alias(target)
    )

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

Pharmacokinetics — df.adam.pk

fleet.adam.PKNamespace

Bases: SharedADaMVerbsMixin, MultiRowMixin

Immutable pipeline builder for PK (pharmacokinetics) derivations.

Covers concentration-time datasets such as ADPC and parameter datasets such as ADPP.

Inherits shared verbs from SharedADaMVerbsMixin (source, derivation, assign, recode, case_when, whereclauses, merge_adsl) and MultiRowMixin (seq), and adds PK-specific verbs for BLQ handling, time derivation, and dose normalisation.

Source code in src/fleet/adam/pk_namespace.py
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
class PKNamespace(SharedADaMVerbsMixin, MultiRowMixin):
    """
    Immutable pipeline builder for PK (pharmacokinetics) derivations.

    Covers concentration-time datasets such as ADPC and parameter datasets
    such as ADPP.

    Inherits shared verbs from ``SharedADaMVerbsMixin``
    (source, derivation, assign, recode, case_when,
    whereclauses, merge_adsl) and ``MultiRowMixin`` (seq), and adds
    PK-specific verbs for BLQ handling, time derivation, and
    dose normalisation.
    """

    # ------------------------------------------------------------------ #
    # PK-specific verbs                                                    #
    # ------------------------------------------------------------------ #

    def _is_blq(
        self,
        verb: str,
        conc: pl.Expr,
        lloq_col: str | None,
        text_col: str | None,
        blq_text: str,
        numeric_below_lloq: bool,
    ) -> pl.Expr:
        """BLQ on positive evidence: a number below the LLOQ, or no number and a BLQ text."""
        parts: list[pl.Expr] = []
        if numeric_below_lloq and lloq_col is not None:
            parts.append((conc < pl.col(lloq_col).cast(pl.Float64)).fill_null(False))
        if text_col is not None:
            if text_col not in self._lazy.collect_schema().names():
                raise DerivationError(
                    f"{verb}: text_col={text_col!r} is not in the frame. SDTM keeps a BLQ "
                    "result only as text in --STRESC; pass text_col= for that column, or "
                    "text_col=None if the frame holds numeric results only."
                )
            text = pl.col(text_col).cast(pl.String).str.contains(blq_text).fill_null(False)
            parts.append(conc.is_null() & text)
        out = pl.lit(False)
        for part in parts:
            out = out | part
        return out

    def blq_flag(
        self,
        target: str,
        *,
        conc_col: str,
        lloq_col: str,
        text_col: str | None = "PCSTRESC",
        blq_text: str = BLQ_TEXT,
        numeric_below_lloq: bool = True,
    ) -> Self:
        """Flag records below the LLOQ (``"Y"``, else null).

        A record is BLQ when *conc_col* is below *lloq_col*, or *conc_col* is
        null and *text_col* matches *blq_text* (``"<0.1"``, ``"BLQ"``).
        ``"ALQ"``, ``">1000"`` and a missed sample are not BLQ.

        Args:
            target: Name of the output flag column.
            conc_col: Numeric concentration column (``PCSTRESN``).
            lloq_col: Column containing the lower limit of quantification.
            text_col: Character result column (default ``"PCSTRESC"``);
                ``None`` when the frame holds numeric results only.
            blq_text: Regular expression of the BLQ texts.  The default
                matches a text that starts with ``<`` or is ``BLQ``, ``BQL``,
                ``BLOQ`` or ``LLOQ`` (any case); the data transfer agreement
                decides the real list.
            numeric_below_lloq: Count a number below the LLOQ as BLQ
                (default ``True``, ADaM popPK 1.0 BLQFL).  ``False`` lets only
                the text decide, as admiral.

        Returns:
            Self: The namespace with *target* appended.

        Raises:
            DerivationError: When *text_col* is not in the frame.

        References:
            SDTMIG 3.4 PC (PCSTRESC holds every result as text, PCSTRESN
            numeric results only); ADaMIG-NCA 1.0 and ADaM popPK 1.0 BLQFL.

        Examples:
            Derive BLQ flag from PC data::

                adpc = (
                    pc_raw.adam.pk
                    .blq_flag("BLQFL", conc_col="PCSTRESN",
                              lloq_col="PCLLOQ")
                    .to_frame()
                )
        """
        cond = self._is_blq(
            "blq_flag",
            pl.col(conc_col).cast(pl.Float64),
            lloq_col,
            text_col,
            blq_text,
            numeric_below_lloq,
        )
        return self._chain(pl.when(cond).then(pl.lit("Y")).otherwise(pl.lit(None)).alias(target))

    def blq_impute(
        self,
        target: str,
        *,
        conc_col: str,
        lloq_col: str,
        method: str = "half_lloq",
        text_col: str | None = "PCSTRESC",
        blq_text: str = BLQ_TEXT,
        numeric_below_lloq: bool = True,
    ) -> Self:
        """Impute BLQ concentrations with a standard substitution method.

        BLQ follows :meth:`blq_flag`.  Other records keep *conc_col*.

        Args:
            target: Name of the output numeric column.
            conc_col: Numeric concentration column (``PCSTRESN``).
            lloq_col: Column containing the LLOQ.
            method: One of ``"half_lloq"`` (default), ``"zero"``, ``"lloq"``,
                or ``"missing"``.
            text_col: Character result column; see :meth:`blq_flag`.
            blq_text: BLQ texts; see :meth:`blq_flag`.
            numeric_below_lloq: See :meth:`blq_flag`.

        Returns:
            Self: The namespace with *target* appended.

        Raises:
            DerivationError: When *method* is unknown or *text_col* is not in
                the frame.

        Examples:
            Impute BLQ values with half the LLOQ::

                adpc = (
                    pc_raw.adam.pk
                    .blq_impute("AVAL", conc_col="PCSTRESN",
                                lloq_col="PCLLOQ", method="half_lloq")
                    .to_frame()
                )
        """
        valid_methods = {"half_lloq", "zero", "lloq", "missing"}
        if method not in valid_methods:
            raise DerivationError(
                f"blq_impute method={method!r} is not supported. "
                f"Choose one of: {sorted(valid_methods)}"
            )

        conc = pl.col(conc_col).cast(pl.Float64)
        lloq = pl.col(lloq_col).cast(pl.Float64)
        is_blq = self._is_blq("blq_impute", conc, lloq_col, text_col, blq_text, numeric_below_lloq)

        if method == "half_lloq":
            imputed = lloq / 2.0
        elif method == "zero":
            imputed = pl.lit(0.0)
        elif method == "lloq":
            imputed = lloq
        else:  # missing
            imputed = pl.lit(None).cast(pl.Float64)

        return self._chain(pl.when(is_blq).then(imputed).otherwise(conc).alias(target))

    def nominal_time(
        self,
        target: str,
        *,
        from_col: str,
        input_unit: str = "h",
        output_unit: str = "h",
    ) -> Self:
        """Derive nominal elapsed time from a planned timepoint column.

        Applies a unit conversion from *input_unit* to *output_unit*.

        Args:
            target: Name of the output column.
            from_col: Source column of nominal time values (numeric).
            input_unit: Unit of *from_col* — ``"s"``, ``"min"``, ``"h"``, or ``"d"``.
            output_unit: Desired unit of *target* (same choices).

        Returns:
            Self: The namespace with *target* appended.

        Examples:
            Copy nominal time in hours::

                adpc = (
                    pc_raw.adam.pk
                    .nominal_time("NTIME", from_col="PCTPTNUM")
                    .to_frame()
                )
        """
        valid_units = set(_UNIT_SCALE)
        for u in (input_unit, output_unit):
            if u not in valid_units:
                raise DerivationError(
                    f"nominal_time unit={u!r} is not supported. "
                    f"Choose one of: {sorted(valid_units)}"
                )
        scale = _UNIT_SCALE[input_unit] / _UNIT_SCALE[output_unit]
        expr = (pl.col(from_col).cast(pl.Float64) * scale).alias(target)
        return self._chain(expr)

    def predose_flag(
        self,
        target: str,
        *,
        time_col: str,
        window_hrs: float = 1.0,
    ) -> Self:
        """Flag pre-dose samples within an allowable window before dosing.

        Sets *target* to ``"Y"`` when ``-window_hrs <= time_col < 0``.

        Args:
            target: Name of the output flag column.
            time_col: Column containing elapsed time relative to dose.
            window_hrs: Size of the pre-dose window (default ``1.0``).

        Returns:
            Self: The namespace with *target* appended.

        Examples:
            Flag pre-dose samples within 1 hour::

                adpc = (
                    pc_raw.adam.pk
                    .predose_flag("PREDFL", time_col="ATIME")
                    .to_frame()
                )
        """
        t = pl.col(time_col).cast(pl.Float64)
        cond = (t >= -window_hrs) & (t < 0.0)
        return self._chain(pl.when(cond).then(pl.lit("Y")).otherwise(pl.lit(None)).alias(target))

    def dose_normalized(
        self,
        target: str,
        *,
        conc_col: str,
        dose_col: str,
    ) -> Self:
        """Dose-normalise concentration: ``target = conc / dose``.

        Returns null when *dose_col* is null or zero.

        Args:
            target: Name of the output column.
            conc_col: Column containing the concentration.
            dose_col: Column containing the administered dose.

        Returns:
            Self: The namespace with *target* appended.

        Examples:
            Derive dose-normalised concentration::

                adpc = (
                    pc_raw.adam.pk
                    .dose_normalized("AVALDNM", conc_col="AVAL",
                                     dose_col="DOSE")
                    .to_frame()
                )
        """
        dose = pl.col(dose_col).cast(pl.Float64)
        conc = pl.col(conc_col).cast(pl.Float64)
        safe_dose = pl.when(dose.is_null() | (dose == 0.0)).then(pl.lit(None)).otherwise(dose)
        return self._chain((conc / safe_dose).alias(target))

    def evid(
        self,
        target: str = "EVID",
        *,
        from_col: str | None = None,
        conc_indicator: int = 0,
    ) -> Self:
        """Derive Event ID (EVID) for Population PK datasets.

        When *from_col* is provided, casts and aliases it.  Otherwise assigns
        *conc_indicator* to every row.

        Args:
            target: Name of the output column (default ``"EVID"``).
            from_col: Existing integer column encoding EVID.
            conc_indicator: Value for concentration records (default ``0``).

        Returns:
            Self: The namespace with *target* appended.

        Examples:
            Assign EVID=0 to all concentration records::

                adpc = (
                    pc_raw.adam.pk
                    .evid("EVID")
                    .to_frame()
                )
        """
        if from_col is not None:
            expr = pl.col(from_col).cast(pl.Int64).alias(target)
        else:
            expr = pl.lit(conc_indicator).cast(pl.Int64).alias(target)
        return self._chain(expr)

    def mrrlt(
        self,
        target: str,
        *,
        arrlt_col: str,
    ) -> Self:
        """Derive Modified Relative Time (MRRLT): ``max(ARRLT, 0)``.

        Clips negative pre-dose times to zero so they align with the
        reference dose timepoint.

        Args:
            target: Name of the output column.
            arrlt_col: Column containing the actual relative time (ARRLT).

        Returns:
            Self: The namespace with *target* appended.

        Examples:
            Clip pre-dose relative times to zero::

                adpc = (
                    pc_raw.adam.pk
                    .mrrlt("MRRLT", arrlt_col="ARRLT")
                    .to_frame()
                )
        """
        t = pl.col(arrlt_col).cast(pl.Float64)
        return self._chain(pl.when(t < 0.0).then(pl.lit(0.0)).otherwise(t).alias(target))

    def blqfn(
        self,
        target: str,
        *,
        conc_col: str,
        lloq_col: str,
        text_col: str | None = "PCSTRESC",
        blq_text: str = BLQ_TEXT,
        numeric_below_lloq: bool = True,
    ) -> Self:
        """Derive a numeric BLQ flag (``1`` / ``0``).

        Complements :meth:`blq_flag` which returns character ``"Y"``/null;
        BLQ follows the same rule.

        Args:
            target: Name of the output column.
            conc_col: Numeric concentration column (``PCSTRESN``).
            lloq_col: Column containing the LLOQ.
            text_col: Character result column; see :meth:`blq_flag`.
            blq_text: BLQ texts; see :meth:`blq_flag`.
            numeric_below_lloq: See :meth:`blq_flag`.

        Returns:
            Self: The namespace with *target* appended.

        Raises:
            DerivationError: When *text_col* is not in the frame.

        Examples:
            Derive numeric BLQ indicator::

                adpc = (
                    pc_raw.adam.pk
                    .blqfn("BLQFN", conc_col="PCSTRESN",
                           lloq_col="PCLLOQ")
                    .to_frame()
                )
        """
        cond = self._is_blq(
            "blqfn",
            pl.col(conc_col).cast(pl.Float64),
            lloq_col,
            text_col,
            blq_text,
            numeric_below_lloq,
        )
        return self._chain(
            pl.when(cond).then(pl.lit(1)).otherwise(pl.lit(0)).cast(pl.Int64).alias(target)
        )

    def log_conc(
        self,
        target: str,
        *,
        conc_col: str,
        base: str = "e",
    ) -> Self:
        """Derive the logarithm of concentration.

        Returns null when *conc_col* is null or <= 0.

        Args:
            target: Name of the output column.
            conc_col: Column containing the numeric concentration.
            base: Logarithm base — ``"e"`` (default), ``"2"``, or ``"10"``.

        Returns:
            Self: The namespace with *target* appended.

        Examples:
            Derive natural log of DV::

                adpc = (
                    pc_raw.adam.pk
                    .log_conc("DVL", conc_col="DV")
                    .to_frame()
                )
        """
        valid_bases = {"e", "2", "10"}
        if base not in valid_bases:
            raise DerivationError(
                f"log_conc base={base!r} is not supported. Choose one of: {sorted(valid_bases)}"
            )
        c = pl.col(conc_col).cast(pl.Float64)
        safe = pl.when(c.is_null() | (c <= 0.0)).then(pl.lit(None).cast(pl.Float64))
        if base == "e":
            expr = safe.otherwise(c.log(base=2.718281828459045))
        elif base == "2":
            expr = safe.otherwise(c.log(base=2.0))
        else:  # "10"
            expr = safe.otherwise(c.log(base=10.0))
        return self._chain(expr.alias(target))

    def mdv(
        self,
        target: str = "MDV",
        *,
        conc_col: str | None = None,
        evid_col: str | None = None,
    ) -> Self:
        """Derive MDV (Missing Dependent Variable) for PopPK datasets.

        ``MDV = 1`` when the dependent variable is missing or the record is
        a dosing record; ``0`` otherwise.

        Args:
            target: Name of the output column (default ``"MDV"``).
            conc_col: Concentration column (null → ``MDV = 1``).
            evid_col: Event ID column (``EVID = 1`` → ``MDV = 1``).

        Returns:
            Self: The namespace with *target* appended.

        Examples:
            Derive MDV from concentration and EVID::

                adpc = (
                    pc_raw.adam.pk
                    .mdv("MDV", conc_col="DV", evid_col="EVID")
                    .to_frame()
                )
        """
        conditions: list[pl.Expr] = []
        if evid_col is not None:
            conditions.append(pl.col(evid_col).cast(pl.Int64) == 1)
        if conc_col is not None:
            conditions.append(pl.col(conc_col).is_null())
        if not conditions:
            # No condition supplied — default to 0
            return self._chain(pl.lit(0).cast(pl.Int64).alias(target))
        combined = conditions[0]
        for cond in conditions[1:]:
            combined = combined | cond
        return self._chain(
            pl.when(combined).then(pl.lit(1)).otherwise(pl.lit(0)).cast(pl.Int64).alias(target)
        )

    def amt(
        self,
        target: str = "AMT",
        *,
        dose_col: str,
        evid_col: str = "EVID",
    ) -> Self:
        """Derive AMT (dose amount) for PopPK / NONMEM-style datasets.

        Sets *target* to the dose on dosing records (``EVID = 1``) and null
        on observation records.

        Args:
            target: Name of the output column (default ``"AMT"``).
            dose_col: Column containing the administered dose amount.
            evid_col: Column containing the Event ID (default ``"EVID"``).

        Returns:
            Self: The namespace with *target* appended.

        Examples:
            Derive AMT from the exposure dose::

                adpc = (
                    pc_raw.adam.pk
                    .amt("AMT", dose_col="EXDOSE", evid_col="EVID")
                    .to_frame()
                )
        """
        dose = pl.col(dose_col).cast(pl.Float64)
        evid = pl.col(evid_col).cast(pl.Int64)
        return self._chain(
            pl.when(evid == 1).then(dose).otherwise(pl.lit(None).cast(pl.Float64)).alias(target)
        )

    def cmt(
        self,
        target: str = "CMT",
        *,
        evid_col: str = "EVID",
        dose_cmt: int = 1,
        conc_cmt: int = 2,
    ) -> Self:
        """Derive CMT (compartment number) for PopPK datasets.

        Assigns *dose_cmt* on dosing records and *conc_cmt* on observation
        records, following NONMEM convention.

        Args:
            target: Name of the output column (default ``"CMT"``).
            evid_col: Column containing the Event ID (default ``"EVID"``).
            dose_cmt: Compartment number for dosing records (default ``1``).
            conc_cmt: Compartment number for concentration records (default ``2``).

        Returns:
            Self: The namespace with *target* appended.

        Examples:
            Assign compartment numbers::

                adpc = (
                    pc_raw.adam.pk
                    .cmt("CMT", evid_col="EVID", dose_cmt=1, conc_cmt=2)
                    .to_frame()
                )
        """
        evid = pl.col(evid_col).cast(pl.Int64)
        return self._chain(
            pl.when(evid == 1)
            .then(pl.lit(dose_cmt))
            .otherwise(pl.lit(conc_cmt))
            .cast(pl.Int64)
            .alias(target)
        )

    def avalcat(
        self,
        target: str,
        *,
        conc_col: str,
        lloq_col: str | None = None,
        blq_label: str = "BLQ",
        text_col: str | None = "PCSTRESC",
        blq_text: str = BLQ_TEXT,
        numeric_below_lloq: bool = True,
    ) -> Self:
        """Derive a listing-ready categorised analysis value (AVALCAT1).

        A BLQ record (as :meth:`blq_flag`) gets *blq_label*.  Another record
        gets its number as text (15 significant digits, no ``.0`` end, so
        ``5.0`` gives ``"5"``), else the *text_col* text (``">1000"``,
        ``"NQ"``), else null (a missed sample).

        Args:
            target: Name of the output column.
            conc_col: Concentration column (numeric, or text that holds
                numbers).
            lloq_col: Optional LLOQ column for the numeric BLQ check.
            blq_label: Label for BLQ records (default ``"BLQ"``).
            text_col: Character result column; see :meth:`blq_flag`.
            blq_text: BLQ texts; see :meth:`blq_flag`.
            numeric_below_lloq: See :meth:`blq_flag`.

        Returns:
            Self: The namespace with *target* appended.

        Raises:
            DerivationError: When *text_col* is not in the frame.

        Examples:
            Derive AVALCAT1 from concentration and LLOQ::

                adpc = (
                    pc_raw.adam.pk
                    .avalcat("AVALCAT1", conc_col="PCSTRESN",
                             lloq_col="PCLLOQ")
                    .to_frame()
                )
        """
        conc_num = pl.col(conc_col).cast(pl.Float64, strict=False)
        is_blq = self._is_blq("avalcat", conc_num, lloq_col, text_col, blq_text, numeric_below_lloq)
        shown = to_char(conc_num, pl.Float64)
        if text_col is not None:
            shown = pl.coalesce(shown, pl.col(text_col).cast(pl.String))

        return self._chain(pl.when(is_blq).then(pl.lit(blq_label)).otherwise(shown).alias(target))

    def anl_flag(
        self,
        target: str,
        *,
        exclude_dtype: bool = False,
        dtype_col: str = "DTYPE",
    ) -> Self:
        """Derive an analysis flag variable (ANL01FL, ANL02FL, etc.).

        When *exclude_dtype* is False (default), all records get ``"Y"``.
        When True, only records with null *dtype_col* get ``"Y"``.

        Args:
            target: Name of the output flag column.
            exclude_dtype: When True, exclude DTYPE records.
            dtype_col: Column to inspect (default ``"DTYPE"``).

        Returns:
            Self: The namespace with *target* appended.

        Examples:
            Flag all records for analysis::

                adpc = (
                    pc_raw.adam.pk
                    .anl_flag("ANL01FL")
                    .to_frame()
                )
        """
        if exclude_dtype:
            expr = (
                pl.when(pl.col(dtype_col).is_null())
                .then(pl.lit("Y"))
                .otherwise(pl.lit(None))
                .alias(target)
            )
        else:
            expr = pl.lit("Y").alias(target)
        return self._chain(expr)

blq_flag

blq_flag(
    target,
    *,
    conc_col,
    lloq_col,
    text_col="PCSTRESC",
    blq_text=BLQ_TEXT,
    numeric_below_lloq=True
)

Flag records below the LLOQ ("Y", else null).

A record is BLQ when conc_col is below lloq_col, or conc_col is null and text_col matches blq_text ("<0.1", "BLQ"). "ALQ", ">1000" and a missed sample are not BLQ.

Parameters:

Name Type Description Default
target str

Name of the output flag column.

required
conc_col str

Numeric concentration column (PCSTRESN).

required
lloq_col str

Column containing the lower limit of quantification.

required
text_col str | None

Character result column (default "PCSTRESC"); None when the frame holds numeric results only.

'PCSTRESC'
blq_text str

Regular expression of the BLQ texts. The default matches a text that starts with < or is BLQ, BQL, BLOQ or LLOQ (any case); the data transfer agreement decides the real list.

BLQ_TEXT
numeric_below_lloq bool

Count a number below the LLOQ as BLQ (default True, ADaM popPK 1.0 BLQFL). False lets only the text decide, as admiral.

True

Returns:

Name Type Description
Self Self

The namespace with target appended.

Raises:

Type Description
DerivationError

When text_col is not in the frame.

References

SDTMIG 3.4 PC (PCSTRESC holds every result as text, PCSTRESN numeric results only); ADaMIG-NCA 1.0 and ADaM popPK 1.0 BLQFL.

Examples:

Derive BLQ flag from PC data::

adpc = (
    pc_raw.adam.pk
    .blq_flag("BLQFL", conc_col="PCSTRESN",
              lloq_col="PCLLOQ")
    .to_frame()
)
Source code in src/fleet/adam/pk_namespace.py
def blq_flag(
    self,
    target: str,
    *,
    conc_col: str,
    lloq_col: str,
    text_col: str | None = "PCSTRESC",
    blq_text: str = BLQ_TEXT,
    numeric_below_lloq: bool = True,
) -> Self:
    """Flag records below the LLOQ (``"Y"``, else null).

    A record is BLQ when *conc_col* is below *lloq_col*, or *conc_col* is
    null and *text_col* matches *blq_text* (``"<0.1"``, ``"BLQ"``).
    ``"ALQ"``, ``">1000"`` and a missed sample are not BLQ.

    Args:
        target: Name of the output flag column.
        conc_col: Numeric concentration column (``PCSTRESN``).
        lloq_col: Column containing the lower limit of quantification.
        text_col: Character result column (default ``"PCSTRESC"``);
            ``None`` when the frame holds numeric results only.
        blq_text: Regular expression of the BLQ texts.  The default
            matches a text that starts with ``<`` or is ``BLQ``, ``BQL``,
            ``BLOQ`` or ``LLOQ`` (any case); the data transfer agreement
            decides the real list.
        numeric_below_lloq: Count a number below the LLOQ as BLQ
            (default ``True``, ADaM popPK 1.0 BLQFL).  ``False`` lets only
            the text decide, as admiral.

    Returns:
        Self: The namespace with *target* appended.

    Raises:
        DerivationError: When *text_col* is not in the frame.

    References:
        SDTMIG 3.4 PC (PCSTRESC holds every result as text, PCSTRESN
        numeric results only); ADaMIG-NCA 1.0 and ADaM popPK 1.0 BLQFL.

    Examples:
        Derive BLQ flag from PC data::

            adpc = (
                pc_raw.adam.pk
                .blq_flag("BLQFL", conc_col="PCSTRESN",
                          lloq_col="PCLLOQ")
                .to_frame()
            )
    """
    cond = self._is_blq(
        "blq_flag",
        pl.col(conc_col).cast(pl.Float64),
        lloq_col,
        text_col,
        blq_text,
        numeric_below_lloq,
    )
    return self._chain(pl.when(cond).then(pl.lit("Y")).otherwise(pl.lit(None)).alias(target))

blq_impute

blq_impute(
    target,
    *,
    conc_col,
    lloq_col,
    method="half_lloq",
    text_col="PCSTRESC",
    blq_text=BLQ_TEXT,
    numeric_below_lloq=True
)

Impute BLQ concentrations with a standard substitution method.

BLQ follows :meth:blq_flag. Other records keep conc_col.

Parameters:

Name Type Description Default
target str

Name of the output numeric column.

required
conc_col str

Numeric concentration column (PCSTRESN).

required
lloq_col str

Column containing the LLOQ.

required
method str

One of "half_lloq" (default), "zero", "lloq", or "missing".

'half_lloq'
text_col str | None

Character result column; see :meth:blq_flag.

'PCSTRESC'
blq_text str

BLQ texts; see :meth:blq_flag.

BLQ_TEXT
numeric_below_lloq bool

See :meth:blq_flag.

True

Returns:

Name Type Description
Self Self

The namespace with target appended.

Raises:

Type Description
DerivationError

When method is unknown or text_col is not in the frame.

Examples:

Impute BLQ values with half the LLOQ::

adpc = (
    pc_raw.adam.pk
    .blq_impute("AVAL", conc_col="PCSTRESN",
                lloq_col="PCLLOQ", method="half_lloq")
    .to_frame()
)
Source code in src/fleet/adam/pk_namespace.py
def blq_impute(
    self,
    target: str,
    *,
    conc_col: str,
    lloq_col: str,
    method: str = "half_lloq",
    text_col: str | None = "PCSTRESC",
    blq_text: str = BLQ_TEXT,
    numeric_below_lloq: bool = True,
) -> Self:
    """Impute BLQ concentrations with a standard substitution method.

    BLQ follows :meth:`blq_flag`.  Other records keep *conc_col*.

    Args:
        target: Name of the output numeric column.
        conc_col: Numeric concentration column (``PCSTRESN``).
        lloq_col: Column containing the LLOQ.
        method: One of ``"half_lloq"`` (default), ``"zero"``, ``"lloq"``,
            or ``"missing"``.
        text_col: Character result column; see :meth:`blq_flag`.
        blq_text: BLQ texts; see :meth:`blq_flag`.
        numeric_below_lloq: See :meth:`blq_flag`.

    Returns:
        Self: The namespace with *target* appended.

    Raises:
        DerivationError: When *method* is unknown or *text_col* is not in
            the frame.

    Examples:
        Impute BLQ values with half the LLOQ::

            adpc = (
                pc_raw.adam.pk
                .blq_impute("AVAL", conc_col="PCSTRESN",
                            lloq_col="PCLLOQ", method="half_lloq")
                .to_frame()
            )
    """
    valid_methods = {"half_lloq", "zero", "lloq", "missing"}
    if method not in valid_methods:
        raise DerivationError(
            f"blq_impute method={method!r} is not supported. "
            f"Choose one of: {sorted(valid_methods)}"
        )

    conc = pl.col(conc_col).cast(pl.Float64)
    lloq = pl.col(lloq_col).cast(pl.Float64)
    is_blq = self._is_blq("blq_impute", conc, lloq_col, text_col, blq_text, numeric_below_lloq)

    if method == "half_lloq":
        imputed = lloq / 2.0
    elif method == "zero":
        imputed = pl.lit(0.0)
    elif method == "lloq":
        imputed = lloq
    else:  # missing
        imputed = pl.lit(None).cast(pl.Float64)

    return self._chain(pl.when(is_blq).then(imputed).otherwise(conc).alias(target))

nominal_time

nominal_time(
    target, *, from_col, input_unit="h", output_unit="h"
)

Derive nominal elapsed time from a planned timepoint column.

Applies a unit conversion from input_unit to output_unit.

Parameters:

Name Type Description Default
target str

Name of the output column.

required
from_col str

Source column of nominal time values (numeric).

required
input_unit str

Unit of from_col — "s", "min", "h", or "d".

'h'
output_unit str

Desired unit of target (same choices).

'h'

Returns:

Name Type Description
Self Self

The namespace with target appended.

Examples:

Copy nominal time in hours::

adpc = (
    pc_raw.adam.pk
    .nominal_time("NTIME", from_col="PCTPTNUM")
    .to_frame()
)
Source code in src/fleet/adam/pk_namespace.py
def nominal_time(
    self,
    target: str,
    *,
    from_col: str,
    input_unit: str = "h",
    output_unit: str = "h",
) -> Self:
    """Derive nominal elapsed time from a planned timepoint column.

    Applies a unit conversion from *input_unit* to *output_unit*.

    Args:
        target: Name of the output column.
        from_col: Source column of nominal time values (numeric).
        input_unit: Unit of *from_col* — ``"s"``, ``"min"``, ``"h"``, or ``"d"``.
        output_unit: Desired unit of *target* (same choices).

    Returns:
        Self: The namespace with *target* appended.

    Examples:
        Copy nominal time in hours::

            adpc = (
                pc_raw.adam.pk
                .nominal_time("NTIME", from_col="PCTPTNUM")
                .to_frame()
            )
    """
    valid_units = set(_UNIT_SCALE)
    for u in (input_unit, output_unit):
        if u not in valid_units:
            raise DerivationError(
                f"nominal_time unit={u!r} is not supported. "
                f"Choose one of: {sorted(valid_units)}"
            )
    scale = _UNIT_SCALE[input_unit] / _UNIT_SCALE[output_unit]
    expr = (pl.col(from_col).cast(pl.Float64) * scale).alias(target)
    return self._chain(expr)

predose_flag

predose_flag(target, *, time_col, window_hrs=1.0)

Flag pre-dose samples within an allowable window before dosing.

Sets target to "Y" when -window_hrs <= time_col < 0.

Parameters:

Name Type Description Default
target str

Name of the output flag column.

required
time_col str

Column containing elapsed time relative to dose.

required
window_hrs float

Size of the pre-dose window (default 1.0).

1.0

Returns:

Name Type Description
Self Self

The namespace with target appended.

Examples:

Flag pre-dose samples within 1 hour::

adpc = (
    pc_raw.adam.pk
    .predose_flag("PREDFL", time_col="ATIME")
    .to_frame()
)
Source code in src/fleet/adam/pk_namespace.py
def predose_flag(
    self,
    target: str,
    *,
    time_col: str,
    window_hrs: float = 1.0,
) -> Self:
    """Flag pre-dose samples within an allowable window before dosing.

    Sets *target* to ``"Y"`` when ``-window_hrs <= time_col < 0``.

    Args:
        target: Name of the output flag column.
        time_col: Column containing elapsed time relative to dose.
        window_hrs: Size of the pre-dose window (default ``1.0``).

    Returns:
        Self: The namespace with *target* appended.

    Examples:
        Flag pre-dose samples within 1 hour::

            adpc = (
                pc_raw.adam.pk
                .predose_flag("PREDFL", time_col="ATIME")
                .to_frame()
            )
    """
    t = pl.col(time_col).cast(pl.Float64)
    cond = (t >= -window_hrs) & (t < 0.0)
    return self._chain(pl.when(cond).then(pl.lit("Y")).otherwise(pl.lit(None)).alias(target))

dose_normalized

dose_normalized(target, *, conc_col, dose_col)

Dose-normalise concentration: target = conc / dose.

Returns null when dose_col is null or zero.

Parameters:

Name Type Description Default
target str

Name of the output column.

required
conc_col str

Column containing the concentration.

required
dose_col str

Column containing the administered dose.

required

Returns:

Name Type Description
Self Self

The namespace with target appended.

Examples:

Derive dose-normalised concentration::

adpc = (
    pc_raw.adam.pk
    .dose_normalized("AVALDNM", conc_col="AVAL",
                     dose_col="DOSE")
    .to_frame()
)
Source code in src/fleet/adam/pk_namespace.py
def dose_normalized(
    self,
    target: str,
    *,
    conc_col: str,
    dose_col: str,
) -> Self:
    """Dose-normalise concentration: ``target = conc / dose``.

    Returns null when *dose_col* is null or zero.

    Args:
        target: Name of the output column.
        conc_col: Column containing the concentration.
        dose_col: Column containing the administered dose.

    Returns:
        Self: The namespace with *target* appended.

    Examples:
        Derive dose-normalised concentration::

            adpc = (
                pc_raw.adam.pk
                .dose_normalized("AVALDNM", conc_col="AVAL",
                                 dose_col="DOSE")
                .to_frame()
            )
    """
    dose = pl.col(dose_col).cast(pl.Float64)
    conc = pl.col(conc_col).cast(pl.Float64)
    safe_dose = pl.when(dose.is_null() | (dose == 0.0)).then(pl.lit(None)).otherwise(dose)
    return self._chain((conc / safe_dose).alias(target))

evid

evid(target='EVID', *, from_col=None, conc_indicator=0)

Derive Event ID (EVID) for Population PK datasets.

When from_col is provided, casts and aliases it. Otherwise assigns conc_indicator to every row.

Parameters:

Name Type Description Default
target str

Name of the output column (default "EVID").

'EVID'
from_col str | None

Existing integer column encoding EVID.

None
conc_indicator int

Value for concentration records (default 0).

0

Returns:

Name Type Description
Self Self

The namespace with target appended.

Examples:

Assign EVID=0 to all concentration records::

adpc = (
    pc_raw.adam.pk
    .evid("EVID")
    .to_frame()
)
Source code in src/fleet/adam/pk_namespace.py
def evid(
    self,
    target: str = "EVID",
    *,
    from_col: str | None = None,
    conc_indicator: int = 0,
) -> Self:
    """Derive Event ID (EVID) for Population PK datasets.

    When *from_col* is provided, casts and aliases it.  Otherwise assigns
    *conc_indicator* to every row.

    Args:
        target: Name of the output column (default ``"EVID"``).
        from_col: Existing integer column encoding EVID.
        conc_indicator: Value for concentration records (default ``0``).

    Returns:
        Self: The namespace with *target* appended.

    Examples:
        Assign EVID=0 to all concentration records::

            adpc = (
                pc_raw.adam.pk
                .evid("EVID")
                .to_frame()
            )
    """
    if from_col is not None:
        expr = pl.col(from_col).cast(pl.Int64).alias(target)
    else:
        expr = pl.lit(conc_indicator).cast(pl.Int64).alias(target)
    return self._chain(expr)

mrrlt

mrrlt(target, *, arrlt_col)

Derive Modified Relative Time (MRRLT): max(ARRLT, 0).

Clips negative pre-dose times to zero so they align with the reference dose timepoint.

Parameters:

Name Type Description Default
target str

Name of the output column.

required
arrlt_col str

Column containing the actual relative time (ARRLT).

required

Returns:

Name Type Description
Self Self

The namespace with target appended.

Examples:

Clip pre-dose relative times to zero::

adpc = (
    pc_raw.adam.pk
    .mrrlt("MRRLT", arrlt_col="ARRLT")
    .to_frame()
)
Source code in src/fleet/adam/pk_namespace.py
def mrrlt(
    self,
    target: str,
    *,
    arrlt_col: str,
) -> Self:
    """Derive Modified Relative Time (MRRLT): ``max(ARRLT, 0)``.

    Clips negative pre-dose times to zero so they align with the
    reference dose timepoint.

    Args:
        target: Name of the output column.
        arrlt_col: Column containing the actual relative time (ARRLT).

    Returns:
        Self: The namespace with *target* appended.

    Examples:
        Clip pre-dose relative times to zero::

            adpc = (
                pc_raw.adam.pk
                .mrrlt("MRRLT", arrlt_col="ARRLT")
                .to_frame()
            )
    """
    t = pl.col(arrlt_col).cast(pl.Float64)
    return self._chain(pl.when(t < 0.0).then(pl.lit(0.0)).otherwise(t).alias(target))

blqfn

blqfn(
    target,
    *,
    conc_col,
    lloq_col,
    text_col="PCSTRESC",
    blq_text=BLQ_TEXT,
    numeric_below_lloq=True
)

Derive a numeric BLQ flag (1 / 0).

Complements :meth:blq_flag which returns character "Y"/null; BLQ follows the same rule.

Parameters:

Name Type Description Default
target str

Name of the output column.

required
conc_col str

Numeric concentration column (PCSTRESN).

required
lloq_col str

Column containing the LLOQ.

required
text_col str | None

Character result column; see :meth:blq_flag.

'PCSTRESC'
blq_text str

BLQ texts; see :meth:blq_flag.

BLQ_TEXT
numeric_below_lloq bool

See :meth:blq_flag.

True

Returns:

Name Type Description
Self Self

The namespace with target appended.

Raises:

Type Description
DerivationError

When text_col is not in the frame.

Examples:

Derive numeric BLQ indicator::

adpc = (
    pc_raw.adam.pk
    .blqfn("BLQFN", conc_col="PCSTRESN",
           lloq_col="PCLLOQ")
    .to_frame()
)
Source code in src/fleet/adam/pk_namespace.py
def blqfn(
    self,
    target: str,
    *,
    conc_col: str,
    lloq_col: str,
    text_col: str | None = "PCSTRESC",
    blq_text: str = BLQ_TEXT,
    numeric_below_lloq: bool = True,
) -> Self:
    """Derive a numeric BLQ flag (``1`` / ``0``).

    Complements :meth:`blq_flag` which returns character ``"Y"``/null;
    BLQ follows the same rule.

    Args:
        target: Name of the output column.
        conc_col: Numeric concentration column (``PCSTRESN``).
        lloq_col: Column containing the LLOQ.
        text_col: Character result column; see :meth:`blq_flag`.
        blq_text: BLQ texts; see :meth:`blq_flag`.
        numeric_below_lloq: See :meth:`blq_flag`.

    Returns:
        Self: The namespace with *target* appended.

    Raises:
        DerivationError: When *text_col* is not in the frame.

    Examples:
        Derive numeric BLQ indicator::

            adpc = (
                pc_raw.adam.pk
                .blqfn("BLQFN", conc_col="PCSTRESN",
                       lloq_col="PCLLOQ")
                .to_frame()
            )
    """
    cond = self._is_blq(
        "blqfn",
        pl.col(conc_col).cast(pl.Float64),
        lloq_col,
        text_col,
        blq_text,
        numeric_below_lloq,
    )
    return self._chain(
        pl.when(cond).then(pl.lit(1)).otherwise(pl.lit(0)).cast(pl.Int64).alias(target)
    )

log_conc

log_conc(target, *, conc_col, base='e')

Derive the logarithm of concentration.

Returns null when conc_col is null or <= 0.

Parameters:

Name Type Description Default
target str

Name of the output column.

required
conc_col str

Column containing the numeric concentration.

required
base str

Logarithm base — "e" (default), "2", or "10".

'e'

Returns:

Name Type Description
Self Self

The namespace with target appended.

Examples:

Derive natural log of DV::

adpc = (
    pc_raw.adam.pk
    .log_conc("DVL", conc_col="DV")
    .to_frame()
)
Source code in src/fleet/adam/pk_namespace.py
def log_conc(
    self,
    target: str,
    *,
    conc_col: str,
    base: str = "e",
) -> Self:
    """Derive the logarithm of concentration.

    Returns null when *conc_col* is null or <= 0.

    Args:
        target: Name of the output column.
        conc_col: Column containing the numeric concentration.
        base: Logarithm base — ``"e"`` (default), ``"2"``, or ``"10"``.

    Returns:
        Self: The namespace with *target* appended.

    Examples:
        Derive natural log of DV::

            adpc = (
                pc_raw.adam.pk
                .log_conc("DVL", conc_col="DV")
                .to_frame()
            )
    """
    valid_bases = {"e", "2", "10"}
    if base not in valid_bases:
        raise DerivationError(
            f"log_conc base={base!r} is not supported. Choose one of: {sorted(valid_bases)}"
        )
    c = pl.col(conc_col).cast(pl.Float64)
    safe = pl.when(c.is_null() | (c <= 0.0)).then(pl.lit(None).cast(pl.Float64))
    if base == "e":
        expr = safe.otherwise(c.log(base=2.718281828459045))
    elif base == "2":
        expr = safe.otherwise(c.log(base=2.0))
    else:  # "10"
        expr = safe.otherwise(c.log(base=10.0))
    return self._chain(expr.alias(target))

mdv

mdv(target='MDV', *, conc_col=None, evid_col=None)

Derive MDV (Missing Dependent Variable) for PopPK datasets.

MDV = 1 when the dependent variable is missing or the record is a dosing record; 0 otherwise.

Parameters:

Name Type Description Default
target str

Name of the output column (default "MDV").

'MDV'
conc_col str | None

Concentration column (null → MDV = 1).

None
evid_col str | None

Event ID column (EVID = 1 → MDV = 1).

None

Returns:

Name Type Description
Self Self

The namespace with target appended.

Examples:

Derive MDV from concentration and EVID::

adpc = (
    pc_raw.adam.pk
    .mdv("MDV", conc_col="DV", evid_col="EVID")
    .to_frame()
)
Source code in src/fleet/adam/pk_namespace.py
def mdv(
    self,
    target: str = "MDV",
    *,
    conc_col: str | None = None,
    evid_col: str | None = None,
) -> Self:
    """Derive MDV (Missing Dependent Variable) for PopPK datasets.

    ``MDV = 1`` when the dependent variable is missing or the record is
    a dosing record; ``0`` otherwise.

    Args:
        target: Name of the output column (default ``"MDV"``).
        conc_col: Concentration column (null → ``MDV = 1``).
        evid_col: Event ID column (``EVID = 1`` → ``MDV = 1``).

    Returns:
        Self: The namespace with *target* appended.

    Examples:
        Derive MDV from concentration and EVID::

            adpc = (
                pc_raw.adam.pk
                .mdv("MDV", conc_col="DV", evid_col="EVID")
                .to_frame()
            )
    """
    conditions: list[pl.Expr] = []
    if evid_col is not None:
        conditions.append(pl.col(evid_col).cast(pl.Int64) == 1)
    if conc_col is not None:
        conditions.append(pl.col(conc_col).is_null())
    if not conditions:
        # No condition supplied — default to 0
        return self._chain(pl.lit(0).cast(pl.Int64).alias(target))
    combined = conditions[0]
    for cond in conditions[1:]:
        combined = combined | cond
    return self._chain(
        pl.when(combined).then(pl.lit(1)).otherwise(pl.lit(0)).cast(pl.Int64).alias(target)
    )

amt

amt(target='AMT', *, dose_col, evid_col='EVID')

Derive AMT (dose amount) for PopPK / NONMEM-style datasets.

Sets target to the dose on dosing records (EVID = 1) and null on observation records.

Parameters:

Name Type Description Default
target str

Name of the output column (default "AMT").

'AMT'
dose_col str

Column containing the administered dose amount.

required
evid_col str

Column containing the Event ID (default "EVID").

'EVID'

Returns:

Name Type Description
Self Self

The namespace with target appended.

Examples:

Derive AMT from the exposure dose::

adpc = (
    pc_raw.adam.pk
    .amt("AMT", dose_col="EXDOSE", evid_col="EVID")
    .to_frame()
)
Source code in src/fleet/adam/pk_namespace.py
def amt(
    self,
    target: str = "AMT",
    *,
    dose_col: str,
    evid_col: str = "EVID",
) -> Self:
    """Derive AMT (dose amount) for PopPK / NONMEM-style datasets.

    Sets *target* to the dose on dosing records (``EVID = 1``) and null
    on observation records.

    Args:
        target: Name of the output column (default ``"AMT"``).
        dose_col: Column containing the administered dose amount.
        evid_col: Column containing the Event ID (default ``"EVID"``).

    Returns:
        Self: The namespace with *target* appended.

    Examples:
        Derive AMT from the exposure dose::

            adpc = (
                pc_raw.adam.pk
                .amt("AMT", dose_col="EXDOSE", evid_col="EVID")
                .to_frame()
            )
    """
    dose = pl.col(dose_col).cast(pl.Float64)
    evid = pl.col(evid_col).cast(pl.Int64)
    return self._chain(
        pl.when(evid == 1).then(dose).otherwise(pl.lit(None).cast(pl.Float64)).alias(target)
    )

cmt

cmt(
    target="CMT", *, evid_col="EVID", dose_cmt=1, conc_cmt=2
)

Derive CMT (compartment number) for PopPK datasets.

Assigns dose_cmt on dosing records and conc_cmt on observation records, following NONMEM convention.

Parameters:

Name Type Description Default
target str

Name of the output column (default "CMT").

'CMT'
evid_col str

Column containing the Event ID (default "EVID").

'EVID'
dose_cmt int

Compartment number for dosing records (default 1).

1
conc_cmt int

Compartment number for concentration records (default 2).

2

Returns:

Name Type Description
Self Self

The namespace with target appended.

Examples:

Assign compartment numbers::

adpc = (
    pc_raw.adam.pk
    .cmt("CMT", evid_col="EVID", dose_cmt=1, conc_cmt=2)
    .to_frame()
)
Source code in src/fleet/adam/pk_namespace.py
def cmt(
    self,
    target: str = "CMT",
    *,
    evid_col: str = "EVID",
    dose_cmt: int = 1,
    conc_cmt: int = 2,
) -> Self:
    """Derive CMT (compartment number) for PopPK datasets.

    Assigns *dose_cmt* on dosing records and *conc_cmt* on observation
    records, following NONMEM convention.

    Args:
        target: Name of the output column (default ``"CMT"``).
        evid_col: Column containing the Event ID (default ``"EVID"``).
        dose_cmt: Compartment number for dosing records (default ``1``).
        conc_cmt: Compartment number for concentration records (default ``2``).

    Returns:
        Self: The namespace with *target* appended.

    Examples:
        Assign compartment numbers::

            adpc = (
                pc_raw.adam.pk
                .cmt("CMT", evid_col="EVID", dose_cmt=1, conc_cmt=2)
                .to_frame()
            )
    """
    evid = pl.col(evid_col).cast(pl.Int64)
    return self._chain(
        pl.when(evid == 1)
        .then(pl.lit(dose_cmt))
        .otherwise(pl.lit(conc_cmt))
        .cast(pl.Int64)
        .alias(target)
    )

avalcat

avalcat(
    target,
    *,
    conc_col,
    lloq_col=None,
    blq_label="BLQ",
    text_col="PCSTRESC",
    blq_text=BLQ_TEXT,
    numeric_below_lloq=True
)

Derive a listing-ready categorised analysis value (AVALCAT1).

A BLQ record (as :meth:blq_flag) gets blq_label. Another record gets its number as text (15 significant digits, no .0 end, so 5.0 gives "5"), else the text_col text (">1000", "NQ"), else null (a missed sample).

Parameters:

Name Type Description Default
target str

Name of the output column.

required
conc_col str

Concentration column (numeric, or text that holds numbers).

required
lloq_col str | None

Optional LLOQ column for the numeric BLQ check.

None
blq_label str

Label for BLQ records (default "BLQ").

'BLQ'
text_col str | None

Character result column; see :meth:blq_flag.

'PCSTRESC'
blq_text str

BLQ texts; see :meth:blq_flag.

BLQ_TEXT
numeric_below_lloq bool

See :meth:blq_flag.

True

Returns:

Name Type Description
Self Self

The namespace with target appended.

Raises:

Type Description
DerivationError

When text_col is not in the frame.

Examples:

Derive AVALCAT1 from concentration and LLOQ::

adpc = (
    pc_raw.adam.pk
    .avalcat("AVALCAT1", conc_col="PCSTRESN",
             lloq_col="PCLLOQ")
    .to_frame()
)
Source code in src/fleet/adam/pk_namespace.py
def avalcat(
    self,
    target: str,
    *,
    conc_col: str,
    lloq_col: str | None = None,
    blq_label: str = "BLQ",
    text_col: str | None = "PCSTRESC",
    blq_text: str = BLQ_TEXT,
    numeric_below_lloq: bool = True,
) -> Self:
    """Derive a listing-ready categorised analysis value (AVALCAT1).

    A BLQ record (as :meth:`blq_flag`) gets *blq_label*.  Another record
    gets its number as text (15 significant digits, no ``.0`` end, so
    ``5.0`` gives ``"5"``), else the *text_col* text (``">1000"``,
    ``"NQ"``), else null (a missed sample).

    Args:
        target: Name of the output column.
        conc_col: Concentration column (numeric, or text that holds
            numbers).
        lloq_col: Optional LLOQ column for the numeric BLQ check.
        blq_label: Label for BLQ records (default ``"BLQ"``).
        text_col: Character result column; see :meth:`blq_flag`.
        blq_text: BLQ texts; see :meth:`blq_flag`.
        numeric_below_lloq: See :meth:`blq_flag`.

    Returns:
        Self: The namespace with *target* appended.

    Raises:
        DerivationError: When *text_col* is not in the frame.

    Examples:
        Derive AVALCAT1 from concentration and LLOQ::

            adpc = (
                pc_raw.adam.pk
                .avalcat("AVALCAT1", conc_col="PCSTRESN",
                         lloq_col="PCLLOQ")
                .to_frame()
            )
    """
    conc_num = pl.col(conc_col).cast(pl.Float64, strict=False)
    is_blq = self._is_blq("avalcat", conc_num, lloq_col, text_col, blq_text, numeric_below_lloq)
    shown = to_char(conc_num, pl.Float64)
    if text_col is not None:
        shown = pl.coalesce(shown, pl.col(text_col).cast(pl.String))

    return self._chain(pl.when(is_blq).then(pl.lit(blq_label)).otherwise(shown).alias(target))

anl_flag

anl_flag(target, *, exclude_dtype=False, dtype_col='DTYPE')

Derive an analysis flag variable (ANL01FL, ANL02FL, etc.).

When exclude_dtype is False (default), all records get "Y". When True, only records with null dtype_col get "Y".

Parameters:

Name Type Description Default
target str

Name of the output flag column.

required
exclude_dtype bool

When True, exclude DTYPE records.

False
dtype_col str

Column to inspect (default "DTYPE").

'DTYPE'

Returns:

Name Type Description
Self Self

The namespace with target appended.

Examples:

Flag all records for analysis::

adpc = (
    pc_raw.adam.pk
    .anl_flag("ANL01FL")
    .to_frame()
)
Source code in src/fleet/adam/pk_namespace.py
def anl_flag(
    self,
    target: str,
    *,
    exclude_dtype: bool = False,
    dtype_col: str = "DTYPE",
) -> Self:
    """Derive an analysis flag variable (ANL01FL, ANL02FL, etc.).

    When *exclude_dtype* is False (default), all records get ``"Y"``.
    When True, only records with null *dtype_col* get ``"Y"``.

    Args:
        target: Name of the output flag column.
        exclude_dtype: When True, exclude DTYPE records.
        dtype_col: Column to inspect (default ``"DTYPE"``).

    Returns:
        Self: The namespace with *target* appended.

    Examples:
        Flag all records for analysis::

            adpc = (
                pc_raw.adam.pk
                .anl_flag("ANL01FL")
                .to_frame()
            )
    """
    if exclude_dtype:
        expr = (
            pl.when(pl.col(dtype_col).is_null())
            .then(pl.lit("Y"))
            .otherwise(pl.lit(None))
            .alias(target)
        )
    else:
        expr = pl.lit("Y").alias(target)
    return self._chain(expr)

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

Time-to-event — df.adam.tte

fleet.adam.TTENamespace

Bases: SharedADaMVerbsMixin

Immutable pipeline builder for ADTTE (time-to-event) derivations.

Inherits shared verbs from SharedADaMVerbsMixin; each verb returns a new TTENamespace; to_frame() materialises the result.

Source code in src/fleet/adam/tte_namespace.py
class TTENamespace(SharedADaMVerbsMixin):
    """
    Immutable pipeline builder for ADTTE (time-to-event) derivations.

    Inherits shared verbs from ``SharedADaMVerbsMixin``; each verb returns a
    new ``TTENamespace``; ``to_frame()`` materialises the result.
    """

    _domain = "ADTTE"

    # ------------------------------------------------------------------ #
    # 1. param — derive one TTE parameter (admiral derive_param_tte)       #
    # ------------------------------------------------------------------ #

    def param(
        self,
        paramcd: str,
        param: str | None = None,
        *,
        start: str,
        events: dict[str, pl.DataFrame | pl.LazyFrame],
        censors: dict[int, pl.DataFrame | pl.LazyFrame] | None = None,
        stop_at: list[str] | None = None,
        by: list[str] | None = None,
        set_values_to: dict[str, Any] | None = None,
        subject_keys: list[str] | None = None,
        create_datetime: bool = False,
        retain: Literal["drop", "censor_at_start"] = "drop",
        explain: bool = False,
    ) -> TTENamespace:
        """Derive one time-to-event parameter and append its rows.

        Each source is a plain frame with the subject keys and ``ADT``.
        The stop date of a subject is the earliest non-null *stop_at* date
        in ADSL; event and censor records after it are dropped. The first
        event left wins: ``CNSR = 0`` and ``EVNTDESC`` = its key. A subject
        without an event is censored at the last censor record left:
        ``CNSR`` = its key (on a date tie, the frame given last wins). A
        subject with no record left is dropped with a warning. ``STARTDT``
        comes from ADSL (the pinned ADSL, else the base frame). An event or
        censor date before it is set to it (admiral: ADT = max(ADT,
        STARTDT)); the CNSR does not change. AVAL comes from :meth:`aval`.

        A source frame may also carry ``EVNTDESC`` (censors only),
        ``CNSDTDSC``, ``SRCDOM``, ``SRCVAR`` and ``SRCSEQ``; they go onto the
        selected row, and ``SRCSEQ`` breaks a tie on one date. A censor
        frame without an ``EVNTDESC`` column gives a null ``EVNTDESC`` and a
        warning that names the frame: the reason of the censoring is study
        text, so Fleet does not invent it.

        Without *param* (and without PARAM in *set_values_to*), PARAM is
        the decode of *paramcd* in the study CT: the codelist of the
        ``PARAMCD`` variable in the ADaM ``define.yaml`` of the first
        ``study_config.yaml`` in the working directory or above it (ADTTE
        first). CDISC ADaM CT has no time-to-event PARAMCD codelist. If no
        decode is found, ``param()`` raises and names the places searched.

        For a favorable event (admiral ``event_type = "positive"``), censor
        at the stop date: add ``{1: adsl.select("USUBJID",
        ADT=pl.min_horizontal("EOSDT", "NACTDT"))}`` to *censors*.

        The first ``param()`` call replaces the pipeline frame with the
        derived rows; later calls append, so one chain builds the whole
        ADTTE. STUDYID is carried from ADSL as the first column. Other ADSL
        variables come from ``join_adsl()`` after the last ``param()``.

        Args:
            paramcd: PARAMCD of the new parameter.
            param: PARAM label (or give PARAM in *set_values_to*). When
                neither is given, the study CT gives it (see above).
            start: Date column in ADSL that starts the clock (``STARTDT``).
            events: ``EVNTDESC -> frame`` of event records.
            censors: ``CNSR -> frame`` of censor records (CNSR >= 1).
            stop_at: Date columns in ADSL. The earliest non-null one ends
                the observation: records after it are dropped.
            by: Stratum columns, present in every source frame. Give a
                per-stratum PARAMCD as an expression in *set_values_to*.
            set_values_to: Extra constant or expression columns on the new
                rows (PARAMN, PARCAT1, ...). A static PARAMCD with several
                strata raises (1:1 guard).
            subject_keys: Subject identifiers (default: the ADSL pin's join
                key, usually ``["USUBJID"]``).
            create_datetime: Give ``ADTM``/``STARTDTM`` instead of dates.
            retain: ``"drop"`` (admiral, warns) or ``"censor_at_start"``
                for a subject with no record.
            explain: Log the decision trace per subject (every candidate,
                the selected one and the reason) through the fleet logger.

        Returns:
            TTENamespace: A fresh namespace whose frame contains the
                accumulated ADTTE rows; call ``.to_frame()`` to materialise.

        Raises:
            DerivationError: On unknown columns (with did-you-mean), date
                columns that are not Date/Datetime, bad dict keys, PARAMCD
                collisions, by-group 1:1 violations, or no PARAM label.

        References:
            admiral 1.5 ``derive_param_tte`` (``end_dates``,
            ``event_type = "negative"``: records after the first end date
            are not used; ADT = max(ADT, STARTDT); ``censor_source`` has no
            default EVNTDESC). ADaM BDS-TTE v1.0: EVNTDESC is permissible
            free text with no codelist. ADaMIG v1.3: PARAM and PARAMCD map
            one to one. ADR-0043
            (docs/adr/0043-tte-censors-at-the-last-record-before-the-stop-date.md).

        Examples:
            PFS censored at the last assessment before new therapy::

                last_assessment = adrs.select(
                    "USUBJID", "ADT", EVNTDESC=pl.lit("NO PROGRESSION"),
                    CNSDTDSC=pl.lit("LAST ASSESSMENT"),
                )
                adtte = (
                    adsl.adam.tte
                    .param(
                        "PFS",
                        "Progression-Free Survival",
                        start="TRTSDT",
                        events={"PD": adrs.filter(pl.col("AVALC") == "PD")},
                        censors={2: last_assessment, 3: adsl.select("USUBJID", ADT="TRTSDT")},
                        stop_at=["EOSDT", "NACTDT"],
                    )
                    .aval(unit="days")
                    .to_frame()
                )
        """
        base = self.to_frame()
        pinned = getattr(self, "_pinned", {})
        universe = pinned["ADSL"][0] if "ADSL" in pinned else base
        keys = subject_keys or (self._pin_join_key("ADSL") if "ADSL" in pinned else ["USUBJID"])
        if param is None and "PARAM" not in (set_values_to or {}):
            if "PARAMCD" in (set_values_to or {}):
                raise DerivationError(
                    "param(): PARAMCD comes from set_values_to, so give PARAM there too."
                )
            param = param_label(paramcd, self._domain)

        rows, trace = select_tte(
            universe=universe,
            start=start,
            events=events,
            censors=censors or {},
            stop_at=stop_at,
            subject_keys=keys,
            by=by,
            create_datetime=create_datetime,
            retain=retain,
        )

        # Parameter identity + extra metadata.
        rows = rows.with_columns(pl.lit(paramcd).alias("PARAMCD"))
        if param is not None:
            rows = rows.with_columns(pl.lit(param).alias("PARAM"))
        for name, value in (set_values_to or {}).items():
            expr = value if isinstance(value, pl.Expr) else pl.lit(value)
            rows = rows.with_columns(expr.alias(name))

        # by-strata 1:1 guard: PARAMCD must uniquely identify a stratum.
        if by:
            n_combos = rows.select(["PARAMCD", *by]).unique().height
            n_params = rows.select("PARAMCD").unique().height
            if n_params < n_combos:
                raise DerivationError(
                    f"param(): PARAMCD is constant across {n_combos} {by} strata — "
                    "the PARAMCD ↔ parameter mapping must be 1:1. Derive PARAMCD "
                    "per stratum via an expression in set_values_to."
                )

        if explain and not trace.is_empty():
            with pl.Config(
                tbl_hide_dataframe_shape=True, tbl_hide_column_data_types=True, tbl_rows=-1
            ):
                logger.info("TTE decision trace — %s (%s):\n%s", paramcd, param or "", trace)

        # Accumulate: a base frame that already carries PARAMCD holds prior
        # ADTTE rows → append (with collision guard); otherwise replace.
        if "PARAMCD" in base.columns and base.height:
            if (base.get_column("PARAMCD") == paramcd).any():
                raise DerivationError(
                    f"param(): PARAMCD '{paramcd}' already exists in the dataset — "
                    "the PARAMCD ↔ PARAM mapping must stay one-to-one."
                )
            for c in base.columns:
                if c not in rows.columns:
                    rows = rows.with_columns(pl.lit(None).cast(base.schema[c]).alias(c))
            for c in rows.columns:
                if c not in base.columns:
                    base = base.with_columns(pl.lit(None).cast(rows.schema[c]).alias(c))
            combined = pl.concat([base, rows.select(base.columns)], how="vertical_relaxed")
        else:
            combined = rows

        new = self._materialise_then(combined)
        if "ADSL" not in pinned and "PARAMCD" not in base.columns:
            # The base frame was ADSL: later param(), join_adsl() and km_data() read it.
            new = new.pin("ADSL", universe, join_on=keys)
        from fleet.core.lineage import record_lineage

        record_lineage(
            new,
            (pl.col(start).alias(paramcd),),
            verb="param",
            params={
                "param": param,
                "events": list(events),
                "censors": [f"CNSR {c}" for c in censors or {}],
                "stop_at": list(stop_at or []),
            },
        )
        return new

    # ------------------------------------------------------------------ #
    # 2. aval — analysis value + unit from STARTDT/ADT                     #
    # ------------------------------------------------------------------ #

    def aval(
        self,
        *,
        unit: Literal["days", "weeks", "months", "years"] = "days",
        add_one: bool = True,
        avalu: bool = True,
    ) -> TTENamespace:
        """Derive ``AVAL`` (and ``AVALU``) from ``STARTDT``/``ADT``.

        ``AVAL = (ADT − STARTDT [+ 1 day]) / unit`` using the CDISC
        conventions (7, 30.4375, 365.25 days per week/month/year).  The
        ``+ 1`` inclusive convention matches admiral's
        ``derive_vars_duration(add_one=TRUE)``.  Each row takes its end as
        the date of ``ADTM``, else ``ADT``, and its start as the date of
        ``STARTDTM``, else ``STARTDT``, so one chain can mix date and
        date-time parameters.

        Args:
            unit: Output unit (default ``"days"``).
            add_one: Include both endpoints (CDISC day convention).
            avalu: Also stamp the ``AVALU`` unit variable (default True —
                a required BDS variable admiral leaves to the user).

        Returns:
            TTENamespace: The namespace with ``AVAL`` (and ``AVALU``)
                appended; call ``.to_frame()`` to materialise.

        Examples:
            Analysis value in months::

                adtte = (
                    adsl.adam.tte
                    .param("OS", "Overall Survival", start="TRTSDT",
                           events={"DEATH": adsl.filter(pl.col("DTHFL") == "Y")
                                                .select("USUBJID", ADT="DTHDT")},
                           censors={1: adsl.select("USUBJID", ADT="LSTALVDT",
                                                   EVNTDESC=pl.lit("ALIVE"))})
                    .aval(unit="months")
                    .to_frame()
                )
        """
        if unit not in _UNIT_DAYS:
            raise DerivationError(
                f"aval() unit={unit!r} is not supported. Choose one of {sorted(_UNIT_DAYS)}."
            )
        schema = self._lazy.collect_schema()

        def day(*names: str) -> pl.Expr:
            present = [
                to_day(pl.col(n), schema.get(n), verb="aval").cast(pl.Date)
                for n in names
                if n in schema.names()
            ]
            return pl.coalesce(present) if present else pl.lit(None, dtype=pl.Date)

        days = (day("ADTM", "ADT") - day("STARTDTM", "STARTDT")).dt.total_days()
        if add_one:
            days = pl.when(days >= 0).then(days + 1).otherwise(days)
        exprs = [(days / _UNIT_DAYS[unit]).alias("AVAL")]
        if avalu:
            exprs.append(pl.lit(unit.upper()).alias("AVALU"))
        return self._chain(*exprs, verb="aval")

    # ------------------------------------------------------------------ #
    # 3. km_data — bridge to the Python survival stack                     #
    # ------------------------------------------------------------------ #

    def km_data(
        self,
        paramcd: str | None = None,
        *,
        by: list[str] | None = None,
    ) -> pl.DataFrame:
        """Return the ``(duration, event)`` frame survival libraries consume.

        ``duration = AVAL`` and ``event = CNSR == 0`` — exactly the inputs of
        ``lifelines.KaplanMeierFitter.fit`` / scikit-survival, with optional
        grouping columns carried through.  No new dependency: just the shape.

        Args:
            paramcd: Restrict to one parameter (required when the frame
                holds several).
            by: Grouping columns to carry (e.g. ``["TRT01P"]``).  Columns
                not present on the ADTTE rows are pulled from the pinned
                ADSL automatically.

        Returns:
            pl.DataFrame: ``USUBJID | duration | event [| by...]``.

        Raises:
            DerivationError: When AVAL/CNSR are missing (call ``aval()``
                first) or several parameters are present and *paramcd* is
                not given.

        Examples:
            Fit a KM curve per treatment arm::

                km = adtte_ns.km_data("OS", by=["TRT01P"])
                # lifelines: kmf.fit(km["duration"], km["event"])
        """
        df = self.to_frame()
        missing = [c for c in ("AVAL", "CNSR") if c not in df.columns]
        if missing:
            raise DerivationError(
                f"km_data(): missing column(s) {missing} — derive them with "
                "param() and aval() first."
            )
        if paramcd is not None:
            df = df.filter(pl.col("PARAMCD") == paramcd)
        elif "PARAMCD" in df.columns and df.get_column("PARAMCD").n_unique() > 1:
            raise DerivationError(
                "km_data(): several parameters present — pass paramcd= to pick one."
            )

        # Group columns absent from the ADTTE rows resolve from the pinned
        # ADSL (the admiral template's post-hoc derive_vars_merged, built in).
        needed = [c for c in (by or []) if c not in df.columns]
        if needed:
            pinned = getattr(self, "_pinned", {})
            if "ADSL" not in pinned:
                raise DerivationError(
                    f"km_data(): column(s) {needed} not on the ADTTE rows and no "
                    "ADSL is pinned to resolve them — pin ADSL or join_adsl() first."
                )
            adsl_df, join_on = pinned["ADSL"]
            missing = [c for c in needed if c not in adsl_df.columns]
            if missing:
                raise DerivationError(
                    f"km_data(): column(s) {missing} not found on the ADTTE rows "
                    "nor in the pinned ADSL."
                )
            df = df.join(
                adsl_df.select(list(join_on) + needed),
                on=list(join_on),
                how="left",
                nulls_equal=True,
            )

        cols = [
            pl.col("USUBJID"),
            pl.col("AVAL").alias("duration"),
            (pl.col("CNSR") == 0).alias("event"),
        ]
        return df.select(cols + [pl.col(c) for c in (by or [])])

param

param(
    paramcd,
    param=None,
    *,
    start,
    events,
    censors=None,
    stop_at=None,
    by=None,
    set_values_to=None,
    subject_keys=None,
    create_datetime=False,
    retain="drop",
    explain=False
)

Derive one time-to-event parameter and append its rows.

Each source is a plain frame with the subject keys and ADT. The stop date of a subject is the earliest non-null stop_at date in ADSL; event and censor records after it are dropped. The first event left wins: CNSR = 0 and EVNTDESC = its key. A subject without an event is censored at the last censor record left: CNSR = its key (on a date tie, the frame given last wins). A subject with no record left is dropped with a warning. STARTDT comes from ADSL (the pinned ADSL, else the base frame). An event or censor date before it is set to it (admiral: ADT = max(ADT, STARTDT)); the CNSR does not change. AVAL comes from :meth:aval.

A source frame may also carry EVNTDESC (censors only), CNSDTDSC, SRCDOM, SRCVAR and SRCSEQ; they go onto the selected row, and SRCSEQ breaks a tie on one date. A censor frame without an EVNTDESC column gives a null EVNTDESC and a warning that names the frame: the reason of the censoring is study text, so Fleet does not invent it.

Without param (and without PARAM in set_values_to), PARAM is the decode of paramcd in the study CT: the codelist of the PARAMCD variable in the ADaM define.yaml of the first study_config.yaml in the working directory or above it (ADTTE first). CDISC ADaM CT has no time-to-event PARAMCD codelist. If no decode is found, param() raises and names the places searched.

For a favorable event (admiral event_type = "positive"), censor at the stop date: add {1: adsl.select("USUBJID", ADT=pl.min_horizontal("EOSDT", "NACTDT"))} to censors.

The first param() call replaces the pipeline frame with the derived rows; later calls append, so one chain builds the whole ADTTE. STUDYID is carried from ADSL as the first column. Other ADSL variables come from join_adsl() after the last param().

Parameters:

Name Type Description Default
paramcd str

PARAMCD of the new parameter.

required
param str | None

PARAM label (or give PARAM in set_values_to). When neither is given, the study CT gives it (see above).

None
start str

Date column in ADSL that starts the clock (STARTDT).

required
events dict[str, DataFrame | LazyFrame]

EVNTDESC -> frame of event records.

required
censors dict[int, DataFrame | LazyFrame] | None

CNSR -> frame of censor records (CNSR >= 1).

None
stop_at list[str] | None

Date columns in ADSL. The earliest non-null one ends the observation: records after it are dropped.

None
by list[str] | None

Stratum columns, present in every source frame. Give a per-stratum PARAMCD as an expression in set_values_to.

None
set_values_to dict[str, Any] | None

Extra constant or expression columns on the new rows (PARAMN, PARCAT1, ...). A static PARAMCD with several strata raises (1:1 guard).

None
subject_keys list[str] | None

Subject identifiers (default: the ADSL pin's join key, usually ["USUBJID"]).

None
create_datetime bool

Give ADTM/STARTDTM instead of dates.

False
retain Literal['drop', 'censor_at_start']

"drop" (admiral, warns) or "censor_at_start" for a subject with no record.

'drop'
explain bool

Log the decision trace per subject (every candidate, the selected one and the reason) through the fleet logger.

False

Returns:

Name Type Description
TTENamespace TTENamespace

A fresh namespace whose frame contains the accumulated ADTTE rows; call .to_frame() to materialise.

Raises:

Type Description
DerivationError

On unknown columns (with did-you-mean), date columns that are not Date/Datetime, bad dict keys, PARAMCD collisions, by-group 1:1 violations, or no PARAM label.

References

admiral 1.5 derive_param_tte (end_dates, event_type = "negative": records after the first end date are not used; ADT = max(ADT, STARTDT); censor_source has no default EVNTDESC). ADaM BDS-TTE v1.0: EVNTDESC is permissible free text with no codelist. ADaMIG v1.3: PARAM and PARAMCD map one to one. ADR-0043 (docs/adr/0043-tte-censors-at-the-last-record-before-the-stop-date.md).

Examples:

PFS censored at the last assessment before new therapy::

last_assessment = adrs.select(
    "USUBJID", "ADT", EVNTDESC=pl.lit("NO PROGRESSION"),
    CNSDTDSC=pl.lit("LAST ASSESSMENT"),
)
adtte = (
    adsl.adam.tte
    .param(
        "PFS",
        "Progression-Free Survival",
        start="TRTSDT",
        events={"PD": adrs.filter(pl.col("AVALC") == "PD")},
        censors={2: last_assessment, 3: adsl.select("USUBJID", ADT="TRTSDT")},
        stop_at=["EOSDT", "NACTDT"],
    )
    .aval(unit="days")
    .to_frame()
)
Source code in src/fleet/adam/tte_namespace.py
def param(
    self,
    paramcd: str,
    param: str | None = None,
    *,
    start: str,
    events: dict[str, pl.DataFrame | pl.LazyFrame],
    censors: dict[int, pl.DataFrame | pl.LazyFrame] | None = None,
    stop_at: list[str] | None = None,
    by: list[str] | None = None,
    set_values_to: dict[str, Any] | None = None,
    subject_keys: list[str] | None = None,
    create_datetime: bool = False,
    retain: Literal["drop", "censor_at_start"] = "drop",
    explain: bool = False,
) -> TTENamespace:
    """Derive one time-to-event parameter and append its rows.

    Each source is a plain frame with the subject keys and ``ADT``.
    The stop date of a subject is the earliest non-null *stop_at* date
    in ADSL; event and censor records after it are dropped. The first
    event left wins: ``CNSR = 0`` and ``EVNTDESC`` = its key. A subject
    without an event is censored at the last censor record left:
    ``CNSR`` = its key (on a date tie, the frame given last wins). A
    subject with no record left is dropped with a warning. ``STARTDT``
    comes from ADSL (the pinned ADSL, else the base frame). An event or
    censor date before it is set to it (admiral: ADT = max(ADT,
    STARTDT)); the CNSR does not change. AVAL comes from :meth:`aval`.

    A source frame may also carry ``EVNTDESC`` (censors only),
    ``CNSDTDSC``, ``SRCDOM``, ``SRCVAR`` and ``SRCSEQ``; they go onto the
    selected row, and ``SRCSEQ`` breaks a tie on one date. A censor
    frame without an ``EVNTDESC`` column gives a null ``EVNTDESC`` and a
    warning that names the frame: the reason of the censoring is study
    text, so Fleet does not invent it.

    Without *param* (and without PARAM in *set_values_to*), PARAM is
    the decode of *paramcd* in the study CT: the codelist of the
    ``PARAMCD`` variable in the ADaM ``define.yaml`` of the first
    ``study_config.yaml`` in the working directory or above it (ADTTE
    first). CDISC ADaM CT has no time-to-event PARAMCD codelist. If no
    decode is found, ``param()`` raises and names the places searched.

    For a favorable event (admiral ``event_type = "positive"``), censor
    at the stop date: add ``{1: adsl.select("USUBJID",
    ADT=pl.min_horizontal("EOSDT", "NACTDT"))}`` to *censors*.

    The first ``param()`` call replaces the pipeline frame with the
    derived rows; later calls append, so one chain builds the whole
    ADTTE. STUDYID is carried from ADSL as the first column. Other ADSL
    variables come from ``join_adsl()`` after the last ``param()``.

    Args:
        paramcd: PARAMCD of the new parameter.
        param: PARAM label (or give PARAM in *set_values_to*). When
            neither is given, the study CT gives it (see above).
        start: Date column in ADSL that starts the clock (``STARTDT``).
        events: ``EVNTDESC -> frame`` of event records.
        censors: ``CNSR -> frame`` of censor records (CNSR >= 1).
        stop_at: Date columns in ADSL. The earliest non-null one ends
            the observation: records after it are dropped.
        by: Stratum columns, present in every source frame. Give a
            per-stratum PARAMCD as an expression in *set_values_to*.
        set_values_to: Extra constant or expression columns on the new
            rows (PARAMN, PARCAT1, ...). A static PARAMCD with several
            strata raises (1:1 guard).
        subject_keys: Subject identifiers (default: the ADSL pin's join
            key, usually ``["USUBJID"]``).
        create_datetime: Give ``ADTM``/``STARTDTM`` instead of dates.
        retain: ``"drop"`` (admiral, warns) or ``"censor_at_start"``
            for a subject with no record.
        explain: Log the decision trace per subject (every candidate,
            the selected one and the reason) through the fleet logger.

    Returns:
        TTENamespace: A fresh namespace whose frame contains the
            accumulated ADTTE rows; call ``.to_frame()`` to materialise.

    Raises:
        DerivationError: On unknown columns (with did-you-mean), date
            columns that are not Date/Datetime, bad dict keys, PARAMCD
            collisions, by-group 1:1 violations, or no PARAM label.

    References:
        admiral 1.5 ``derive_param_tte`` (``end_dates``,
        ``event_type = "negative"``: records after the first end date
        are not used; ADT = max(ADT, STARTDT); ``censor_source`` has no
        default EVNTDESC). ADaM BDS-TTE v1.0: EVNTDESC is permissible
        free text with no codelist. ADaMIG v1.3: PARAM and PARAMCD map
        one to one. ADR-0043
        (docs/adr/0043-tte-censors-at-the-last-record-before-the-stop-date.md).

    Examples:
        PFS censored at the last assessment before new therapy::

            last_assessment = adrs.select(
                "USUBJID", "ADT", EVNTDESC=pl.lit("NO PROGRESSION"),
                CNSDTDSC=pl.lit("LAST ASSESSMENT"),
            )
            adtte = (
                adsl.adam.tte
                .param(
                    "PFS",
                    "Progression-Free Survival",
                    start="TRTSDT",
                    events={"PD": adrs.filter(pl.col("AVALC") == "PD")},
                    censors={2: last_assessment, 3: adsl.select("USUBJID", ADT="TRTSDT")},
                    stop_at=["EOSDT", "NACTDT"],
                )
                .aval(unit="days")
                .to_frame()
            )
    """
    base = self.to_frame()
    pinned = getattr(self, "_pinned", {})
    universe = pinned["ADSL"][0] if "ADSL" in pinned else base
    keys = subject_keys or (self._pin_join_key("ADSL") if "ADSL" in pinned else ["USUBJID"])
    if param is None and "PARAM" not in (set_values_to or {}):
        if "PARAMCD" in (set_values_to or {}):
            raise DerivationError(
                "param(): PARAMCD comes from set_values_to, so give PARAM there too."
            )
        param = param_label(paramcd, self._domain)

    rows, trace = select_tte(
        universe=universe,
        start=start,
        events=events,
        censors=censors or {},
        stop_at=stop_at,
        subject_keys=keys,
        by=by,
        create_datetime=create_datetime,
        retain=retain,
    )

    # Parameter identity + extra metadata.
    rows = rows.with_columns(pl.lit(paramcd).alias("PARAMCD"))
    if param is not None:
        rows = rows.with_columns(pl.lit(param).alias("PARAM"))
    for name, value in (set_values_to or {}).items():
        expr = value if isinstance(value, pl.Expr) else pl.lit(value)
        rows = rows.with_columns(expr.alias(name))

    # by-strata 1:1 guard: PARAMCD must uniquely identify a stratum.
    if by:
        n_combos = rows.select(["PARAMCD", *by]).unique().height
        n_params = rows.select("PARAMCD").unique().height
        if n_params < n_combos:
            raise DerivationError(
                f"param(): PARAMCD is constant across {n_combos} {by} strata — "
                "the PARAMCD ↔ parameter mapping must be 1:1. Derive PARAMCD "
                "per stratum via an expression in set_values_to."
            )

    if explain and not trace.is_empty():
        with pl.Config(
            tbl_hide_dataframe_shape=True, tbl_hide_column_data_types=True, tbl_rows=-1
        ):
            logger.info("TTE decision trace — %s (%s):\n%s", paramcd, param or "", trace)

    # Accumulate: a base frame that already carries PARAMCD holds prior
    # ADTTE rows → append (with collision guard); otherwise replace.
    if "PARAMCD" in base.columns and base.height:
        if (base.get_column("PARAMCD") == paramcd).any():
            raise DerivationError(
                f"param(): PARAMCD '{paramcd}' already exists in the dataset — "
                "the PARAMCD ↔ PARAM mapping must stay one-to-one."
            )
        for c in base.columns:
            if c not in rows.columns:
                rows = rows.with_columns(pl.lit(None).cast(base.schema[c]).alias(c))
        for c in rows.columns:
            if c not in base.columns:
                base = base.with_columns(pl.lit(None).cast(rows.schema[c]).alias(c))
        combined = pl.concat([base, rows.select(base.columns)], how="vertical_relaxed")
    else:
        combined = rows

    new = self._materialise_then(combined)
    if "ADSL" not in pinned and "PARAMCD" not in base.columns:
        # The base frame was ADSL: later param(), join_adsl() and km_data() read it.
        new = new.pin("ADSL", universe, join_on=keys)
    from fleet.core.lineage import record_lineage

    record_lineage(
        new,
        (pl.col(start).alias(paramcd),),
        verb="param",
        params={
            "param": param,
            "events": list(events),
            "censors": [f"CNSR {c}" for c in censors or {}],
            "stop_at": list(stop_at or []),
        },
    )
    return new

aval

aval(*, unit='days', add_one=True, avalu=True)

Derive AVAL (and AVALU) from STARTDT/ADT.

AVAL = (ADT − STARTDT [+ 1 day]) / unit using the CDISC conventions (7, 30.4375, 365.25 days per week/month/year). The + 1 inclusive convention matches admiral's derive_vars_duration(add_one=TRUE). Each row takes its end as the date of ADTM, else ADT, and its start as the date of STARTDTM, else STARTDT, so one chain can mix date and date-time parameters.

Parameters:

Name Type Description Default
unit Literal['days', 'weeks', 'months', 'years']

Output unit (default "days").

'days'
add_one bool

Include both endpoints (CDISC day convention).

True
avalu bool

Also stamp the AVALU unit variable (default True — a required BDS variable admiral leaves to the user).

True

Returns:

Name Type Description
TTENamespace TTENamespace

The namespace with AVAL (and AVALU) appended; call .to_frame() to materialise.

Examples:

Analysis value in months::

adtte = (
    adsl.adam.tte
    .param("OS", "Overall Survival", start="TRTSDT",
           events={"DEATH": adsl.filter(pl.col("DTHFL") == "Y")
                                .select("USUBJID", ADT="DTHDT")},
           censors={1: adsl.select("USUBJID", ADT="LSTALVDT",
                                   EVNTDESC=pl.lit("ALIVE"))})
    .aval(unit="months")
    .to_frame()
)
Source code in src/fleet/adam/tte_namespace.py
def aval(
    self,
    *,
    unit: Literal["days", "weeks", "months", "years"] = "days",
    add_one: bool = True,
    avalu: bool = True,
) -> TTENamespace:
    """Derive ``AVAL`` (and ``AVALU``) from ``STARTDT``/``ADT``.

    ``AVAL = (ADT − STARTDT [+ 1 day]) / unit`` using the CDISC
    conventions (7, 30.4375, 365.25 days per week/month/year).  The
    ``+ 1`` inclusive convention matches admiral's
    ``derive_vars_duration(add_one=TRUE)``.  Each row takes its end as
    the date of ``ADTM``, else ``ADT``, and its start as the date of
    ``STARTDTM``, else ``STARTDT``, so one chain can mix date and
    date-time parameters.

    Args:
        unit: Output unit (default ``"days"``).
        add_one: Include both endpoints (CDISC day convention).
        avalu: Also stamp the ``AVALU`` unit variable (default True —
            a required BDS variable admiral leaves to the user).

    Returns:
        TTENamespace: The namespace with ``AVAL`` (and ``AVALU``)
            appended; call ``.to_frame()`` to materialise.

    Examples:
        Analysis value in months::

            adtte = (
                adsl.adam.tte
                .param("OS", "Overall Survival", start="TRTSDT",
                       events={"DEATH": adsl.filter(pl.col("DTHFL") == "Y")
                                            .select("USUBJID", ADT="DTHDT")},
                       censors={1: adsl.select("USUBJID", ADT="LSTALVDT",
                                               EVNTDESC=pl.lit("ALIVE"))})
                .aval(unit="months")
                .to_frame()
            )
    """
    if unit not in _UNIT_DAYS:
        raise DerivationError(
            f"aval() unit={unit!r} is not supported. Choose one of {sorted(_UNIT_DAYS)}."
        )
    schema = self._lazy.collect_schema()

    def day(*names: str) -> pl.Expr:
        present = [
            to_day(pl.col(n), schema.get(n), verb="aval").cast(pl.Date)
            for n in names
            if n in schema.names()
        ]
        return pl.coalesce(present) if present else pl.lit(None, dtype=pl.Date)

    days = (day("ADTM", "ADT") - day("STARTDTM", "STARTDT")).dt.total_days()
    if add_one:
        days = pl.when(days >= 0).then(days + 1).otherwise(days)
    exprs = [(days / _UNIT_DAYS[unit]).alias("AVAL")]
    if avalu:
        exprs.append(pl.lit(unit.upper()).alias("AVALU"))
    return self._chain(*exprs, verb="aval")

km_data

km_data(paramcd=None, *, by=None)

Return the (duration, event) frame survival libraries consume.

duration = AVAL and event = CNSR == 0 — exactly the inputs of lifelines.KaplanMeierFitter.fit / scikit-survival, with optional grouping columns carried through. No new dependency: just the shape.

Parameters:

Name Type Description Default
paramcd str | None

Restrict to one parameter (required when the frame holds several).

None
by list[str] | None

Grouping columns to carry (e.g. ["TRT01P"]). Columns not present on the ADTTE rows are pulled from the pinned ADSL automatically.

None

Returns:

Type Description
DataFrame

pl.DataFrame: USUBJID | duration | event [| by...].

Raises:

Type Description
DerivationError

When AVAL/CNSR are missing (call aval() first) or several parameters are present and paramcd is not given.

Examples:

Fit a KM curve per treatment arm::

km = adtte_ns.km_data("OS", by=["TRT01P"])
# lifelines: kmf.fit(km["duration"], km["event"])
Source code in src/fleet/adam/tte_namespace.py
def km_data(
    self,
    paramcd: str | None = None,
    *,
    by: list[str] | None = None,
) -> pl.DataFrame:
    """Return the ``(duration, event)`` frame survival libraries consume.

    ``duration = AVAL`` and ``event = CNSR == 0`` — exactly the inputs of
    ``lifelines.KaplanMeierFitter.fit`` / scikit-survival, with optional
    grouping columns carried through.  No new dependency: just the shape.

    Args:
        paramcd: Restrict to one parameter (required when the frame
            holds several).
        by: Grouping columns to carry (e.g. ``["TRT01P"]``).  Columns
            not present on the ADTTE rows are pulled from the pinned
            ADSL automatically.

    Returns:
        pl.DataFrame: ``USUBJID | duration | event [| by...]``.

    Raises:
        DerivationError: When AVAL/CNSR are missing (call ``aval()``
            first) or several parameters are present and *paramcd* is
            not given.

    Examples:
        Fit a KM curve per treatment arm::

            km = adtte_ns.km_data("OS", by=["TRT01P"])
            # lifelines: kmf.fit(km["duration"], km["event"])
    """
    df = self.to_frame()
    missing = [c for c in ("AVAL", "CNSR") if c not in df.columns]
    if missing:
        raise DerivationError(
            f"km_data(): missing column(s) {missing} — derive them with "
            "param() and aval() first."
        )
    if paramcd is not None:
        df = df.filter(pl.col("PARAMCD") == paramcd)
    elif "PARAMCD" in df.columns and df.get_column("PARAMCD").n_unique() > 1:
        raise DerivationError(
            "km_data(): several parameters present — pass paramcd= to pick one."
        )

    # Group columns absent from the ADTTE rows resolve from the pinned
    # ADSL (the admiral template's post-hoc derive_vars_merged, built in).
    needed = [c for c in (by or []) if c not in df.columns]
    if needed:
        pinned = getattr(self, "_pinned", {})
        if "ADSL" not in pinned:
            raise DerivationError(
                f"km_data(): column(s) {needed} not on the ADTTE rows and no "
                "ADSL is pinned to resolve them — pin ADSL or join_adsl() first."
            )
        adsl_df, join_on = pinned["ADSL"]
        missing = [c for c in needed if c not in adsl_df.columns]
        if missing:
            raise DerivationError(
                f"km_data(): column(s) {missing} not found on the ADTTE rows "
                "nor in the pinned ADSL."
            )
        df = df.join(
            adsl_df.select(list(join_on) + needed),
            on=list(join_on),
            how="left",
            nulls_equal=True,
        )

    cols = [
        pl.col("USUBJID"),
        pl.col("AVAL").alias("duration"),
        (pl.col("CNSR") == 0).alias("event"),
    ]
    return df.select(cols + [pl.col(c) for c in (by or [])])

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

fleet.adam.tte

Time-to-event (ADTTE) selection engine behind df.adam.tte.param().

Each event or censor source is a plain Polars frame with the subject keys and an ADT column. :func:select_tte selects one record per subject: the first event on or before the first stop date (CNSR = 0), else the last censor record on or before it (CNSR = the key of its frame). It also returns a decision trace that tells why each record was selected.

param_label

param_label(paramcd, domain='ADTTE')

Return the PARAM of paramcd from the study's controlled terminology.

The study is the first study_config.yaml in the working directory or above it. The label is the decode of the paramcd item in a codelist that a PARAMCD variable of the ADaM define.yaml references (the domain dataset first, then the others). fleet init ct writes the CDISC CT preferred terms as these decodes, so a PARAMCD in a pinned CDISC CT codelist resolves here too.

Parameters:

Name Type Description Default
paramcd str

The parameter code, for example "OS".

required
domain str

The dataset whose PARAMCD codelist is read first.

'ADTTE'

Returns:

Name Type Description
str str

The decode, for example "Overall Survival".

Raises:

Type Description
DerivationError

When no source gives a label. The message names paramcd, the places searched and the fix (param=).

References

ADaMIG v1.3, BDS analysis parameter variables: PARAM and PARAMCD map one to one. CDISC ADaM CT (NCI EVS) has no time-to-event PARAMCD codelist; its parameter codelists are questionnaire and scale codes. ADR-0043.

Examples:

The label of OS in a study whose ADTTE.PARAMCD has a codelist::

label = param_label("OS")  # "Overall Survival"
Source code in src/fleet/adam/tte.py
def param_label(paramcd: str, domain: str = "ADTTE") -> str:
    """Return the PARAM of *paramcd* from the study's controlled terminology.

    The study is the first ``study_config.yaml`` in the working directory
    or above it. The label is the ``decode`` of the *paramcd* item in a
    codelist that a ``PARAMCD`` variable of the ADaM ``define.yaml``
    references (the *domain* dataset first, then the others). ``fleet init
    ct`` writes the CDISC CT preferred terms as these decodes, so a PARAMCD
    in a pinned CDISC CT codelist resolves here too.

    Args:
        paramcd: The parameter code, for example ``"OS"``.
        domain: The dataset whose ``PARAMCD`` codelist is read first.

    Returns:
        str: The decode, for example ``"Overall Survival"``.

    Raises:
        DerivationError: When no source gives a label. The message names
            *paramcd*, the places searched and the fix (``param=``).

    References:
        ADaMIG v1.3, BDS analysis parameter variables: PARAM and PARAMCD
        map one to one. CDISC
        ADaM CT (NCI EVS) has no time-to-event PARAMCD codelist; its
        parameter codelists are questionnaire and scale codes. ADR-0043.

    Examples:
        The label of OS in a study whose ADTTE.PARAMCD has a codelist::

            label = param_label("OS")  # "Overall Survival"
    """
    searched: list[str] = []
    config = find_study_config()
    if config is None:
        searched.append(f"no study_config.yaml in {Path.cwd()} or above it")
    else:
        try:
            define = load_study_context(config).metadata_adam_dir / "define.yaml"
        except StudyConfigError as err:
            searched.append(f"{config} (cannot be read: {err})")
        else:
            label = _define_decode(define, paramcd, domain) if define.is_file() else None
            if label is not None:
                return label
            searched.append(f"the PARAMCD codelists of {define}")
    searched.append("CDISC ADaM CT (it has no time-to-event PARAMCD codelist)")
    raise DerivationError(
        f"param(): no PARAM label for PARAMCD '{paramcd}'. Searched: {'; '.join(searched)}. "
        f'Pass param=, for example param("{paramcd}", "Overall Survival", ...), or add '
        f"'{paramcd}' with a decode to the PARAMCD codelist of {domain} in the ADaM define.yaml."
    )

select_tte

select_tte(
    *,
    universe,
    start,
    events,
    censors,
    subject_keys,
    stop_at=None,
    by=None,
    create_datetime=False,
    retain="drop"
)

Select one time-to-event record per subject (per stratum).

The stop date of a subject is the earliest non-null stop_at date in universe. Event and censor records after it are dropped. The first event left wins (CNSR = 0, EVNTDESC = its key). A subject without an event takes the last censor record left (CNSR = its key); on a date tie the censor frame given last wins. An event or censor date before the start date is set to the start date; the CNSR does not change.

Parameters:

Name Type Description Default
universe DataFrame

Subject-level frame (ADSL) with start, stop_at and the subject keys.

required
start str

Date column in universe that starts the clock (STARTDT).

required
events dict[str, DataFrame | LazyFrame]

EVNTDESC -> frame. Each frame holds the subject keys and ADT.

required
censors dict[int, DataFrame | LazyFrame]

CNSR -> frame (CNSR >= 1). Each frame holds the subject keys and ADT; EVNTDESC comes from a frame column, else it is null and a warning names the frame.

required
subject_keys list[str]

Subject identifier columns (usually ["USUBJID"]).

required
stop_at list[str] | None

Date columns in universe; the earliest non-null one ends the observation of the subject.

None
by list[str] | None

Stratum columns, present in every source frame.

None
create_datetime bool

Give ADTM/STARTDTM instead of dates.

False
retain Literal['drop', 'censor_at_start']

"drop" (a subject with no record left is dropped with a warning) or "censor_at_start" (censored at STARTDT with EVNTDESC = "NO EVENT OBSERVED").

'drop'

Returns:

Type Description
tuple[DataFrame, DataFrame]

tuple[pl.DataFrame, pl.DataFrame]: The selected rows, and the decision trace (one row per candidate: kind, source, date, selected, reason).

Raises:

Type Description
DerivationError

On a missing column (with a did-you-mean hint), a date column that is not Date/Datetime, or a bad dict key.

References

admiral 1.5 derive_param_tte (end_dates, event_type = "negative"); ADR-0043 (docs/adr/0043-tte-censors-at-the-last-record-before-the-stop-date.md).

Examples:

PFS, censored at the last assessment before new therapy::

rows, trace = select_tte(
    universe=adsl,
    start="TRTSDT",
    events={"PD": adrs.filter(pl.col("AVALC") == "PD")},
    censors={2: adrs.select("USUBJID", "ADT")},
    subject_keys=["USUBJID"],
    stop_at=["EOSDT", "NACTDT"],
)
Source code in src/fleet/adam/tte.py
def select_tte(
    *,
    universe: pl.DataFrame,
    start: str,
    events: dict[str, pl.DataFrame | pl.LazyFrame],
    censors: dict[int, pl.DataFrame | pl.LazyFrame],
    subject_keys: list[str],
    stop_at: list[str] | None = None,
    by: list[str] | None = None,
    create_datetime: bool = False,
    retain: Literal["drop", "censor_at_start"] = "drop",
) -> tuple[pl.DataFrame, pl.DataFrame]:
    """Select one time-to-event record per subject (per stratum).

    The stop date of a subject is the earliest non-null *stop_at* date in
    *universe*. Event and censor records after it are dropped. The first
    event left wins (``CNSR = 0``, ``EVNTDESC`` = its key). A subject
    without an event takes the last censor record left (``CNSR`` = its
    key); on a date tie the censor frame given last wins. An event or
    censor date before the start date is set to the start date; the CNSR
    does not change.

    Args:
        universe: Subject-level frame (ADSL) with *start*, *stop_at* and the
            subject keys.
        start: Date column in *universe* that starts the clock
            (``STARTDT``).
        events: ``EVNTDESC -> frame``. Each frame holds the subject keys
            and ``ADT``.
        censors: ``CNSR -> frame`` (CNSR >= 1). Each frame holds the
            subject keys and ``ADT``; ``EVNTDESC`` comes from a frame
            column, else it is null and a warning names the frame.
        subject_keys: Subject identifier columns (usually ``["USUBJID"]``).
        stop_at: Date columns in *universe*; the earliest non-null one
            ends the observation of the subject.
        by: Stratum columns, present in every source frame.
        create_datetime: Give ``ADTM``/``STARTDTM`` instead of dates.
        retain: ``"drop"`` (a subject with no record left is dropped with a
            warning) or ``"censor_at_start"`` (censored at ``STARTDT`` with
            ``EVNTDESC = "NO EVENT OBSERVED"``).

    Returns:
        tuple[pl.DataFrame, pl.DataFrame]: The selected rows, and the
            decision trace (one row per candidate: ``kind``, ``source``,
            ``date``, ``selected``, ``reason``).

    Raises:
        DerivationError: On a missing column (with a did-you-mean hint), a
            date column that is not Date/Datetime, or a bad dict key.

    References:
        admiral 1.5 ``derive_param_tte`` (``end_dates``,
        ``event_type = "negative"``); ADR-0043
        (docs/adr/0043-tte-censors-at-the-last-record-before-the-stop-date.md).

    Examples:
        PFS, censored at the last assessment before new therapy::

            rows, trace = select_tte(
                universe=adsl,
                start="TRTSDT",
                events={"PD": adrs.filter(pl.col("AVALC") == "PD")},
                censors={2: adrs.select("USUBJID", "ADT")},
                subject_keys=["USUBJID"],
                stop_at=["EOSDT", "NACTDT"],
            )
    """
    by = by or []
    stop_at = stop_at or []
    sources = _sources(events, censors)
    keys = subject_keys + by

    no_desc = [lb for lb, kd, _, fr in sources if kd == "censor" and "EVNTDESC" not in fr.columns]
    if no_desc:
        warnings.warn(
            f"TTE censor frame(s) {', '.join(no_desc)} have no EVNTDESC column, so EVNTDESC "
            "is null on their rows. Give the reason of the censoring on the frame, for "
            'example adsl.select("USUBJID", ADT="LSTALVDT", EVNTDESC=pl.lit("ALIVE")).',
            UserWarning,
            stacklevel=3,
        )

    _check_columns("ADSL", universe, subject_keys + [start, *stop_at])
    for col in [start, *stop_at]:
        _check_date("ADSL", universe, col)

    date_dtype: pl.DataType = pl.Datetime("us") if create_datetime else pl.Date
    base = universe.select(subject_keys + [pl.col(start).cast(date_dtype).alias(_START)]).unique(
        subject_keys, maintain_order=True
    )
    stops = (
        universe.select(
            subject_keys
            + [pl.min_horizontal([pl.col(c).cast(date_dtype) for c in stop_at]).alias(_STOP)]
        ).unique(subject_keys, maintain_order=True)
        if stop_at
        else None
    )

    pools: dict[str, list[pl.DataFrame]] = {"event": [], "censor": []}
    for index, (label, kind, cnsr, frame) in enumerate(sources):
        where = f"TTE {kind} {label}"
        _check_columns(where, frame, keys + ["ADT"])
        _check_date(where, frame, "ADT")
        cand = _candidates(label, kind, cnsr, index, frame, keys, stops, subject_keys, date_dtype)
        if not cand.is_empty():
            pools[kind].append(cand)
    event_pool, censor_pool = (
        pl.concat(pools[k], how="diagonal_relaxed") if pools[k] else pl.DataFrame()
        for k in ("event", "censor")
    )

    def winner(pool: pl.DataFrame, first: bool) -> pl.DataFrame:
        if pool.is_empty():
            return pool
        grouped = pool.sort(keys + [_ADT, _IDX]).group_by(keys, maintain_order=True)
        return grouped.first() if first else grouped.last()

    chosen = winner(event_pool, first=True)
    censor_win = winner(censor_pool, first=False)
    if not censor_win.is_empty():
        extra = (
            censor_win
            if chosen.is_empty()
            else censor_win.join(chosen.select(keys), on=keys, how="anti", nulls_equal=True)
        )
        chosen = extra if chosen.is_empty() else pl.concat([chosen, extra], how="diagonal_relaxed")

    pooled = [p for p in (event_pool, censor_pool) if not p.is_empty()]
    if by and pooled:
        strata = pl.concat([p.select(by) for p in pooled], how="vertical_relaxed").unique(
            maintain_order=True
        )
        base = base.join(strata, how="cross")
    rows = (
        base.join(chosen, on=keys, how="left", nulls_equal=True)
        if not chosen.is_empty()
        else base.with_columns(
            pl.lit(None, dtype=date_dtype).alias(_ADT),
            pl.lit(None, dtype=pl.String).alias(_KIND),
            pl.lit(None, dtype=pl.Int64).alias(_CNSR),
            pl.lit(None, dtype=pl.String).alias(_SRC),
            pl.lit(None, dtype=pl.Int64).alias(_IDX),
        )
    )

    unresolved = rows.filter(pl.col(_KIND).is_null())
    rows = rows.filter(pl.col(_KIND).is_not_null())
    if unresolved.height:
        if retain == "censor_at_start":
            filled = unresolved.with_columns(
                pl.col(_START).alias(_ADT),
                pl.lit("censor").alias(_KIND),
                pl.lit(1).cast(pl.Int64).alias(_CNSR),
                pl.lit("NO EVENT OBSERVED").alias("EVNTDESC"),
                pl.lit("ADSL").alias("SRCDOM"),
                pl.lit(start).alias("SRCVAR"),
            )
            rows = pl.concat([rows, filled], how="diagonal_relaxed") if rows.height else filled
        else:
            ids = unresolved.get_column(subject_keys[-1]).unique(maintain_order=True)
            window = " on or before the first stop_at date" if stop_at else ""
            warnings.warn(
                f"select_tte(): {ids.len()} subject(s) have no event and no censor "
                f"record{window} and were dropped: {ids.head(5).to_list()}"
                f"{' ...' if ids.len() > 5 else ''}. Add a censor frame on the start date "
                f'(for example {{3: adsl.select("USUBJID", ADT="{start}")}}) or use '
                "retain='censor_at_start'.",
                UserWarning,
                stacklevel=3,
            )

    # admiral: ADT = max(ADT, STARTDT).
    floored = (pl.col(_ADT) < pl.col(_START)) & pl.col(_START).is_not_null()
    rows = rows.with_columns(
        floored.fill_null(False).alias("__floored__"),
        pl.when(floored).then(pl.col(_START)).otherwise(pl.col(_ADT)).alias(_ADT),
    )

    trace = _trace(pooled, rows, keys, date_dtype)
    if unresolved.height and retain == "drop":
        dropped = unresolved.select(
            keys
            + [
                pl.lit(None, dtype=pl.String).alias("kind"),
                pl.lit(None, dtype=pl.String).alias("source"),
                pl.lit(None, dtype=date_dtype).alias("date"),
                pl.lit(False).alias("selected"),
                pl.lit("dropped: no event or censor record").alias("reason"),
            ]
        )
        trace = pl.concat([trace, dropped], how="diagonal_relaxed") if trace.height else dropped

    start_name, adt_name = ("STARTDTM", "ADTM") if create_datetime else ("STARTDT", "ADT")
    rows = rows.rename({_START: start_name, _ADT: adt_name, _CNSR: "CNSR"}).drop(
        _KIND, _SRC, _IDX, "__floored__"
    )
    if "STUDYID" in universe.columns and "STUDYID" not in rows.columns:
        study = universe.select(subject_keys + ["STUDYID"]).unique()
        if study.select(subject_keys).is_duplicated().any():
            raise DerivationError(
                f"select_tte(): a subject key {subject_keys} has two STUDYID values in ADSL. "
                'Give subject_keys=["STUDYID", "USUBJID"].'
            )
        rows = rows.join(study, on=subject_keys, how="left", nulls_equal=True).select(
            "STUDYID", pl.exclude("STUDYID")
        )
    return rows, trace

options: show_root_heading: true heading_level: 3 members_order: source show_source: false