Skip to content

ADaM Namespace

The df.adam namespace builds ADaM BDS datasets (ADVS, ADLB, …).

fleet.adam.AdamNamespace

Bases: SharedADaMVerbsMixin

Immutable pipeline builder for ADaM derivations.

Each verb appends to a lazy expression list; to_frame() materialises everything in one with_columns call (unless the verb requires a join/filter). Accepts both pl.DataFrame and pl.LazyFrame inputs, so scanned sources stay lazy end-to-end.

Inherits shared verbs from SharedADaMVerbsMixin (assign, case_when, merge, source, derivation, whereclauses, ...). Discover the full set with df.adam.verbs().

Source code in src/fleet/adam/namespace.py
  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
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
@pl.api.register_dataframe_namespace("adam")
@pl.api.register_lazyframe_namespace("adam")
class AdamNamespace(SharedADaMVerbsMixin):
    """
    Immutable pipeline builder for ADaM derivations.

    Each verb appends to a lazy expression list; ``to_frame()`` materialises
    everything in one ``with_columns`` call (unless the verb requires a join/filter).
    Accepts both ``pl.DataFrame`` and ``pl.LazyFrame`` inputs, so scanned
    sources stay lazy end-to-end.

    Inherits shared verbs from ``SharedADaMVerbsMixin`` (``assign``,
    ``case_when``, ``merge``, ``source``, ``derivation``, ``whereclauses``,
    ...).  Discover the full set with ``df.adam.verbs()``.
    """

    # ------------------------------------------------------------------ #
    # 9.  baseline — propagate baseline value to all group records        #
    # ------------------------------------------------------------------ #

    def baseline(
        self,
        target: str,
        *,
        aval: str = "AVAL",
        baseline_flag: str = "ABLFL",
        by: list[str] | None = None,
        strict: bool = True,
    ) -> AdamNamespace:
        """Derive BASE as the AVAL where the baseline flag equals ``"Y"``.

        Uses a window function so all records in the same group receive the
        same baseline value.  A group with **more than one** flagged
        record has an ambiguous baseline: with ``strict=True`` (default)
        this raises a ``DerivationError`` naming the offending groups
        (admiral semantics); ``strict=False`` keeps the legacy behaviour
        (silently taking the maximum flagged value) but emits a
        ``UserWarning``.

        Args:
            target: Name of the output column (e.g. ``"BASE"``).
            aval: Analysis value column (default ``"AVAL"``).
            baseline_flag: Flag column indicating the baseline record.
            by: Partition columns (default ``["USUBJID", "PARAMCD"]``).
            strict: Raise when a group has multiple baseline-flagged
                records (default ``True``).

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

        Raises:
            DerivationError: When ``strict=True`` and at least one group
                carries more than one baseline-flagged record.

        Examples:
            Propagate baseline AVAL to all records::

                advs = (
                    vs_raw.adam
                    .baseline("BASE", aval="AVAL", baseline_flag="ABLFL",
                              by=["USUBJID", "PARAMCD"])
                    .to_frame()
                )
        """
        import warnings

        grps = by or ["USUBJID", "PARAMCD"]
        schema_names = self._lazy.collect_schema().names()
        if baseline_flag not in schema_names or any(g not in schema_names for g in grps):
            # Missing columns — defer to _chain's verb-attributed error.
            return self._chain(
                baseline(aval=aval, baseline_flag_col=baseline_flag, group_by=grps, target=target),
                verb="baseline",
            )
        dup_groups = (
            self._lazy.filter(pl.col(baseline_flag) == "Y")
            .group_by(grps)
            .agg(pl.len().alias("__n_baseline__"))
            .filter(pl.col("__n_baseline__") > 1)
            .collect()
        )
        if dup_groups.height:
            sample = dup_groups.select(grps).head(5).rows()
            keys = "; ".join(", ".join(f"{k}={v!r}" for k, v in zip(grps, row)) for row in sample)
            more = f" (+{dup_groups.height - 5} more)" if dup_groups.height > 5 else ""
            detail = (
                f"baseline('{target}'): {dup_groups.height} group(s) have more than one "
                f"record flagged {baseline_flag}='Y' — the baseline is ambiguous. "
                f"Offending groups: {keys}{more}."
            )
            if strict:
                raise DerivationError(
                    f"{detail} Deduplicate the baseline flag (e.g. via "
                    ".flag(..., criteria='last') or .nodup(...)) or pass strict=False "
                    "to keep the legacy max() behaviour."
                )
            warnings.warn(
                f"{detail} Taking the maximum flagged value per group (strict=False).",
                stacklevel=2,
            )
        return self._chain(
            baseline(aval=aval, baseline_flag_col=baseline_flag, group_by=grps, target=target),
            verb="baseline",
        )

    # ------------------------------------------------------------------ #
    # 10. chg — change from baseline                                      #
    # ------------------------------------------------------------------ #

    def chg(
        self,
        target: str,
        *,
        aval: str = "AVAL",
        base: str = "BASE",
    ) -> AdamNamespace:
        """Compute change from baseline: ``CHG = AVAL - BASE``.

        Args:
            target: Name of the output column (e.g. ``"CHG"``).
            aval: Analysis value column.
            base: Baseline value column.

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

        Examples:
            Derive CHG from AVAL and BASE::

                advs = (
                    vs_raw.adam
                    .chg("CHG", aval="AVAL", base="BASE")
                    .to_frame()
                )
        """
        return self._chain(chg(aval=aval, base=base, target=target), verb="chg")

    # ------------------------------------------------------------------ #
    # 11. pchg — percent change from baseline                             #
    # ------------------------------------------------------------------ #

    def pchg(
        self,
        target: str,
        *,
        aval: str = "AVAL",
        base: str = "BASE",
    ) -> AdamNamespace:
        """Compute percent change from baseline.

        ``PCHG = (AVAL - BASE) / BASE * 100``.  Returns null when BASE is
        null or zero.

        Args:
            target: Name of the output column (e.g. ``"PCHG"``).
            aval: Analysis value column.
            base: Baseline value column.

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

        Examples:
            Derive PCHG from AVAL and BASE::

                advs = (
                    vs_raw.adam
                    .pchg("PCHG", aval="AVAL", base="BASE")
                    .to_frame()
                )
        """
        return self._chain(pchg(aval=aval, base=base, target=target), verb="pchg")

    # ------------------------------------------------------------------ #
    # 13. bmi — Body Mass Index                                            #
    # ------------------------------------------------------------------ #

    def bmi(
        self,
        target: str,
        *,
        weight: str,
        height: str,
        round_digits: int | None = None,
    ) -> AdamNamespace:
        """Derive Body Mass Index: ``weight_kg / (height_cm / 100) ** 2``.

        The value keeps full precision.  A height of 0 gives null, as SAS
        gives a missing value for a division by zero.

        Args:
            target: Name of the output column.
            weight: Column containing weight in kg.
            height: Column containing height in cm.
            round_digits: Decimal places, rounded as SAS ``ROUND`` (half away
                from zero).  Default ``None``: no rounding.

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

        References:
            admiral ``compute_bmi`` (pharmaverse): full precision, NA for height 0.
            ADR-0025: a derived value is rounded only when the call says so.

        Examples:
            Compute BMI from weight and height::

                advs = (
                    vs_raw.adam
                    .bmi("BMI", weight="WEIGHT", height="HEIGHT")
                    .to_frame()
                )
        """
        return self._chain(
            _bmi_expr(weight=weight, height=height, target=target, round_digits=round_digits),
            verb="bmi",
        )

    # ------------------------------------------------------------------ #
    # 14. nrind — normal range indicator                                   #
    # ------------------------------------------------------------------ #

    def nrind(
        self,
        target: str,
        *,
        value: str,
        low: str,
        high: str,
        signif_dig: int = 15,
    ) -> AdamNamespace:
        """Categorise *value* relative to normal range: LOW / NORMAL / HIGH.

        The value and the limits are compared at *signif_dig* significant
        digits, so float noise (1.3 x 88.4 = 114.92000000000002) does not
        move a value at the limit out of the range.  A null or NaN value gives
        null.

        Args:
            target: Name of the output column (e.g. ``"NRIND"``).
            value: Column containing the numeric result.
            low: Column containing the lower limit of normal.
            high: Column containing the upper limit of normal.
            signif_dig: Significant digits for the comparison (default 15).

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

        References:
            admiral ``derive_var_anrind`` (pharmaverse): ``signif(x, 15)`` on AVAL,
            ANRLO and ANRHI before the comparison.

        Examples:
            Derive normal range indicator for lab results::

                adlb = (
                    lb_raw.adam
                    .nrind("NRIND", value="LBSTRESN",
                           low="LBSTNRLO", high="LBSTNRHI")
                    .to_frame()
                )
        """
        return self._chain(
            _nrind_expr(value=value, low=low, high=high, target=target, signif_dig=signif_dig),
            verb="nrind",
        )

    # ------------------------------------------------------------------ #
    # 15. on_treatment — derive ONTRTFL                                    #
    # ------------------------------------------------------------------ #

    def on_treatment(
        self,
        target: str = "ONTRTFL",
        *,
        adt: str,
        trtsdt: str,
        trtedt: str,
        open_ended: bool = True,
    ) -> AdamNamespace:
        """Set *target* to ``"Y"`` when *adt* is within [trtsdt, trtedt].

        When *open_ended* is ``True`` (default) and *trtedt* is null, the
        interval is treated as ongoing (``adt >= trtsdt`` suffices).
        ``--DTC`` text is read by its date portion (a partial or blank
        value gives null); a number raises.  When *adt* and *trtsdt* are
        both ``pl.Datetime``, the start comparison keeps the time, so a
        pre-dose record on the first dose day is not on treatment; the end
        comparison is at date level.

        Args:
            target: Name of the output column (default ``"ONTRTFL"``).
            adt: Analysis date column.
            trtsdt: Treatment start date column.
            trtedt: Treatment end date column.
            open_ended: Treat null *trtedt* as open-ended (default ``True``).

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

        References:
            admiral ``derive_var_ontrtfl`` (start compared with time when
            both are date-times); ADR-0011 and ADR-0022.

        Examples:
            Derive on-treatment flag::

                advs = (
                    vs_raw.adam
                    .on_treatment("ONTRTFL", adt="ADT",
                                  trtsdt="TRTSDT", trtedt="TRTEDT")
                    .to_frame()
                )
        """
        return self._chain(
            _on_treatment_expr(
                adt=adt,
                trtsdt=trtsdt,
                trtedt=trtedt,
                target=target,
                open_ended=open_ended,
                dtypes=self._lazy.collect_schema(),
            ),
            verb="on_treatment",
        )

    # ------------------------------------------------------------------ #
    # 16. shift — baseline-to-post categorical shift string               #
    # ------------------------------------------------------------------ #

    def shift(
        self,
        target: str,
        *,
        baseline_cat: str,
        post_cat: str,
        sep: str = " to ",
    ) -> AdamNamespace:
        """Derive a categorical shift label: ``"<baseline><sep><post>"``.

        Args:
            target: Name of the output column (e.g. ``"SHIFT1"``).
            baseline_cat: Column with baseline category (e.g. ``"BNRIND"``).
            post_cat: Column with post-baseline category (e.g. ``"NRIND"``).
            sep: Separator string (default ``" to "``).

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

        Examples:
            Create a shift variable from baseline and post normal range::

                adlb = (
                    lb_raw.adam
                    .shift("SHIFT1", baseline_cat="BNRIND",
                           post_cat="NRIND")
                    .to_frame()
                )
        """
        return self._chain(
            _shift_expr(baseline_cat=baseline_cat, post_cat=post_cat, target=target, sep=sep),
            verb="shift",
        )

    # ------------------------------------------------------------------ #
    # 17. bsa — Body Surface Area                                          #
    # ------------------------------------------------------------------ #

    def bsa(
        self,
        target: str,
        *,
        weight: str,
        height: str,
        method: str = "Mosteller",
        round_digits: int | None = None,
    ) -> AdamNamespace:
        """Derive Body Surface Area in m², at full precision.

        Args:
            target: Name of the output column.
            weight: Column containing weight in kg.
            height: Column containing height in cm.
            method: Formula to use — ``"Mosteller"`` (default), ``"DuBois"``,
                ``"Haycock"``, or ``"Gehan-George"``.
            round_digits: Decimal places, rounded as SAS ``ROUND`` (half away
                from zero).  Default ``None``: no rounding.

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

        References:
            admiral ``compute_bsa`` (pharmaverse): full precision.
            ADR-0025: a derived value is rounded only when the call says so.

        Examples:
            Compute BSA using the Mosteller formula::

                advs = (
                    vs_raw.adam
                    .bsa("BSA", weight="WEIGHT", height="HEIGHT")
                    .to_frame()
                )
        """
        return self._chain(
            _bsa_expr(
                weight=weight,
                height=height,
                method=method,
                target=target,
                round_digits=round_digits,
            ),
            verb="bsa",
        )

    # ------------------------------------------------------------------ #
    # 18. map — Mean Arterial Pressure                                     #
    # ------------------------------------------------------------------ #

    def map(
        self,
        target: str = "MAP",
        *,
        systolic: str = "SYSBP",
        diastolic: str = "DIABP",
        round_digits: int | None = None,
    ) -> AdamNamespace:
        """Derive Mean Arterial Pressure: ``DBP + (SBP - DBP) / 3``, at full precision.

        Args:
            target: Name of the output column (default ``"MAP"``).
            systolic: Systolic blood pressure column.
            diastolic: Diastolic blood pressure column.
            round_digits: Decimal places, rounded as SAS ``ROUND`` (half away
                from zero).  Default ``None``: no rounding.

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

        References:
            admiral ``compute_map`` (pharmaverse): full precision.
            ADR-0025: a derived value is rounded only when the call says so.

        Examples:
            Compute MAP from blood pressure columns::

                advs = (
                    vs_raw.adam
                    .map("MAP", systolic="SYSBP", diastolic="DIABP")
                    .to_frame()
                )
        """
        return self._chain(
            _map_expr(
                systolic=systolic, diastolic=diastolic, target=target, round_digits=round_digits
            ),
            verb="map",
        )

    # ------------------------------------------------------------------ #
    # 19. qtc — Corrected QT interval                                      #
    # ------------------------------------------------------------------ #

    def qtc(
        self,
        target: str = "QTC",
        *,
        qt: str = "QT",
        rr: str = "RR",
        method: str = "Fridericia",
        rr_unit: str = "ms",
        round_digits: int | None = None,
    ) -> AdamNamespace:
        """Derive corrected QT interval, as admiral ``compute_qtc``, at full precision.

        Args:
            target: Name of the output column (default ``"QTC"``).
            qt: QT interval column, in ms.
            rr: RR interval column, in *rr_unit*.
            method: Correction formula — ``"Fridericia"`` (default) or
                ``"Bazett"``.
            rr_unit: Unit of *rr*: ``"ms"`` (default) or ``"msec"``, or
                ``"s"`` or ``"sec"``.
            round_digits: Decimal places, rounded as SAS ``ROUND`` (half away
                from zero).  Default ``None``: no rounding.

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

        Raises:
            DerivationError: When *rr_unit* is unknown, or a value cannot be
                in its unit: an RR under 10 in ms, an RR of 10 or more in
                seconds, or a QT under 10 ms.

        References:
            admiral ``compute_qtc`` (pharmaverse): RR in ms, QT in ms, full precision.
            ADR-0025: a derived value is rounded only when the call says so.

        Examples:
            Derive QTcF from QT and RR, both in ms::

                adeg = (
                    eg_raw.adam
                    .qtc("QTCF", qt="QT", rr="RR", method="Fridericia")
                    .to_frame()
                )
        """
        expr = _qtc_expr(
            qt=qt, rr=rr, method=method, target=target, rr_unit=rr_unit, round_digits=round_digits
        )
        schema_names = self._lazy.collect_schema().names()
        if qt in schema_names and rr in schema_names:
            seconds = rr_unit.lower() in ("s", "sec")
            rr_num = pl.col(rr).cast(pl.Float64, strict=False)
            bad_rr = rr_num >= 10 if seconds else rr_num < 10
            counts = (
                self._lazy.select(
                    bad_rr.sum().alias("rr"),
                    (pl.col(qt).cast(pl.Float64, strict=False) < 10).sum().alias("qt"),
                )
                .collect()
                .row(0)
            )
            if counts[0]:
                raise DerivationError(
                    f"qtc('{target}'): {counts[0]} {rr} value(s) cannot be in "
                    f"rr_unit={rr_unit!r} (RR in ms is 10 or more; in seconds it is under 10). "
                    "State the unit of the data with rr_unit=."
                )
            if counts[1]:
                raise DerivationError(
                    f"qtc('{target}'): {counts[1]} {qt} value(s) are under 10. QT must be in ms."
                )
        return self._chain(expr, verb="qtc")

    # ------------------------------------------------------------------ #
    # 20. derive_summary_records — aggregate and append new rows          #
    # ------------------------------------------------------------------ #

    def derive_summary_records(
        self,
        *,
        by: list[str],
        analysis_var: str = "AVAL",
        set_values_to: dict[str, Any],
        stat: Literal["mean", "sum", "min", "max", "median", "count"] = "mean",
        where: str | pl.Expr | None = None,
    ) -> AdamNamespace:
        """
        Compute a summary statistic per group and append the results as new records.

        *set_values_to*: column → value mapping applied to every new record
        (e.g. ``{"PARAMCD": "AVGBP", "DTYPE": "AVERAGE"}``).

        *stat*: ``"mean"`` (default), ``"sum"``, ``"min"``, ``"max"``, ``"median"``,
        ``"count"``. A group with only null values gives null for every stat
        except ``"count"``, which gives 0, as SAS ``SUM()`` and PROC MEANS.

        *where*: filter on the source records of the summary. The rows of the
        dataset are all kept. A second call in one chain reads the rows that
        the first call added: give ``where=pl.col("DTYPE").is_null()`` to
        summarise only collected records. When *where* is None and the source
        holds a non-null DTYPE, the verb warns.

        Materialises the current pipeline before concatenation.

        Examples:
            Compute mean AVAL per subject and parameter::

                advs = (
                    vs_raw.adam
                    .derive_summary_records(
                        by=["USUBJID", "PARAMCD"],
                        analysis_var="AVAL",
                        set_values_to={"DTYPE": "AVERAGE"},
                        stat="mean",
                    )
                    .to_frame()
                )
        """
        stat_lower = stat.lower()
        agg_map = {
            "mean": pl.col(analysis_var).mean(),
            "sum": pl.when(pl.col(analysis_var).count() > 0).then(pl.col(analysis_var).sum()),
            "min": pl.col(analysis_var).min(),
            "max": pl.col(analysis_var).max(),
            "median": pl.col(analysis_var).median(),
            "count": pl.col(analysis_var).count().cast(pl.Float64),
        }
        if stat_lower not in agg_map:
            raise DerivationError(f"Unknown stat '{stat}'. Supported: {', '.join(agg_map)}.")

        df = self.to_frame()
        source = df
        if where is not None:
            from fleet.sdtm.utils import parse_expression

            source = df.filter(where if isinstance(where, pl.Expr) else parse_expression(where))
        elif "DTYPE" in df.columns and df.get_column("DTYPE").is_not_null().any():
            warnings.warn(
                "derive_summary_records(): the source holds records with a non-null DTYPE, "
                "and they enter the summary. Give where=pl.col('DTYPE').is_null() to "
                "summarise only collected records.",
                UserWarning,
                stacklevel=2,
            )
        summary = source.group_by(by, maintain_order=True).agg(
            agg_map[stat_lower].alias(analysis_var)
        )

        # Apply constant values to the summary rows
        for col_name, col_val in set_values_to.items():
            summary = summary.with_columns(pl.lit(col_val).alias(col_name))

        # Align schemas before concat: add missing columns as null in both directions
        for c in df.columns:
            if c not in summary.columns:
                summary = summary.with_columns(pl.lit(None).cast(df.schema[c]).alias(c))
        for c in summary.columns:
            if c not in df.columns:
                df = df.with_columns(pl.lit(None).cast(summary.schema[c]).alias(c))

        col_order = df.columns
        summary = summary.select(col_order)

        combined = pl.concat([df, summary], how="vertical_relaxed")
        from fleet.core.lineage import record_row_step

        return record_row_step(self._materialise_then(combined), "derive_summary_records", {})

    # ------------------------------------------------------------------ #
    # 21. derive_locf_records — last observation carried forward          #
    # ------------------------------------------------------------------ #

    def derive_locf_records(
        self,
        *,
        dataset_ref: pl.DataFrame,
        by: list[str],
        order_by: str | list[str],
        analysis_var: str = "AVAL",
        imputation: Literal["add", "update", "update_add"] = "add",
        keep_vars: list[str] | None = None,
    ) -> AdamNamespace:
        """Add LOCF records for missed visits and for a null *analysis_var*.

        For each *by* group, every row of *dataset_ref* (the expected visits)
        that has no record with a non-null *analysis_var* gets a value carried
        forward from the previous record, sorted by *by* and *order_by*. Each
        imputed record has DTYPE ``"LOCF"``; an existing DTYPE on the other
        records is kept. A group with no earlier value keeps a null value.

        Args:
            dataset_ref: Expected observations, for example AVISIT and AVISITN,
                or PARAMCD, AVISIT and AVISITN. Add USUBJID for a per-subject
                list. Each of its columns must be in the dataset.
            by: Group columns, for example ``["STUDYID", "USUBJID", "PARAMCD"]``.
            order_by: Sort column(s) within a group. The first one must be in
                *dataset_ref*, so that a new record has a sort value.
            analysis_var: Column to carry forward (default ``"AVAL"``).
            imputation: ``"add"`` (default, as admiral) keeps each record with a
                null value and adds an imputed record. ``"update"`` puts the
                value on that record. ``"update_add"`` does both.
            keep_vars: Other columns to carry forward, for example PARAMN.
                A new record has values only in *by*, *dataset_ref*,
                *analysis_var*, *keep_vars* and DTYPE; other columns are null.

        Returns:
            AdamNamespace: The namespace with the LOCF records; call
                ``.to_frame()`` to materialise.

        Raises:
            DerivationError: On an unknown *imputation*, a missing column, a
                first *order_by* column that is not in *dataset_ref*, or a null
                *order_by* value on a record to sort.

        Examples:
            Add WEEK 24 by LOCF for each subject and parameter::

                visits = pl.DataFrame(
                    {"AVISIT": ["BASELINE", "WEEK 8", "WEEK 16", "WEEK 24"],
                     "AVISITN": [0, 8, 16, 24]}
                )
                adqs = (
                    qs_raw.adam
                    .derive_locf_records(
                        dataset_ref=visits,
                        by=["STUDYID", "USUBJID", "PARAMCD"],
                        order_by=["AVISITN"],
                        keep_vars=["PARAM"],
                    )
                    .to_frame()
                )

        References:
            ADaMIG v1.3 section 4.4 (BDS): DTYPE must be populated on a record
            whose AVAL is imputed; "LOCF" is in CDISC CT codelist DTYPE (C81224).
            admiral ``derive_locf_records`` (pharmaverse) defines the three
            imputation modes. ADR-0029.
        """
        order = [order_by] if isinstance(order_by, str) else list(order_by)
        keep = list(keep_vars or [])
        if imputation not in ("add", "update", "update_add"):
            raise DerivationError(
                f"derive_locf_records(): imputation={imputation!r} is not supported. "
                "Choose 'add', 'update' or 'update_add'."
            )
        if not order:
            raise DerivationError("derive_locf_records(): order_by needs at least one column.")
        ref_cols = dataset_ref.columns
        if order[0] not in ref_cols:
            raise DerivationError(
                f"derive_locf_records(): the first order_by column {order[0]!r} is not in "
                f"dataset_ref (columns {ref_cols}). A new record would have no sort value. "
                "Sort by a visit column of dataset_ref, for example order_by=['AVISITN']."
            )
        df = self.to_frame()
        needed = dict.fromkeys([*by, analysis_var, *order, *keep, *ref_cols])
        missing = [c for c in needed if c not in df.columns]
        if missing:
            raise DerivationError(f"derive_locf_records(): column(s) {missing} not in the dataset.")

        ref = dataset_ref.cast({c: df.schema[c] for c in ref_cols})
        ids = df.select([c for c in by if c not in ref_cols]).unique(maintain_order=True)
        expected = ids.join(ref, how="cross") if ids.width else ref
        exp_by = list(dict.fromkeys([*by, *ref_cols]))

        is_null = pl.col(analysis_var).is_null()
        fill_base = df.filter(~is_null) if imputation == "add" else df
        to_add = expected.join(fill_base.select(exp_by), on=exp_by, how="anti", nulls_equal=True)
        stacked = pl.concat([fill_base, to_add], how="diagonal_relaxed")
        dtype = pl.when(is_null).then(pl.lit("LOCF"))
        if "DTYPE" in df.columns:
            dtype = dtype.otherwise(pl.col("DTYPE"))
        stacked = stacked.with_columns(dtype.alias("DTYPE"))

        n_null = stacked.select(pl.any_horizontal(pl.col(order).is_null()).sum()).item()
        if n_null:
            raise DerivationError(
                f"derive_locf_records(): {n_null} record(s) have a null value in order_by "
                f"{order}, so their place in the visit order is unknown."
            )
        filled = stacked.sort([*by, *order], maintain_order=True).with_columns(
            pl.col([analysis_var, *keep]).forward_fill().over(by)
        )
        if imputation != "update":
            filled = pl.concat([filled, df.filter(is_null)], how="diagonal_relaxed")
        from fleet.core.lineage import record_row_step

        new = self._materialise_then(filled.select(list(dict.fromkeys([*df.columns, "DTYPE"]))))
        return record_row_step(new, "derive_locf_records", {})

    # ------------------------------------------------------------------ #
    # 22. derive_param — append a computed parameter as new records        #
    # ------------------------------------------------------------------ #

    def derive_param(
        self,
        *,
        by: list[str] | None = None,
        set_values_to: dict[str, Any],
        parameter_filter: dict[str, str],
        analysis_value: pl.Expr | str,
        from_dataset: pl.DataFrame | None = None,
        where: str | pl.Expr | None = None,
    ) -> AdamNamespace:
        """
        Derive a new parameter (e.g. BMI) from existing records and append
        the computed rows to the dataset.

        *parameter_filter*: ``{alias: PARAMCD}`` pairs identifying the source
        records to pivot on (e.g. ``{"WEIGHT": "WEIGHT", "HEIGHT": "HEIGHT"}``).
        Each key is a local alias; the value is the ``PARAMCD`` it matches.
        Every source parameter must be unique per *by* group — duplicates
        raise instead of silently multiplying the derived rows.

        *analysis_value*: a Polars expression (or YAML-friendly string)
        referencing the aliases to compute the new AVAL
        (e.g. ``pl.col("WEIGHT") / (pl.col("HEIGHT")/100)**2``).

        *set_values_to*: constant columns on the new rows — including the
        parameter-level identifiers ``PARAM``, ``PARAMN``, ``PARCATy`` /
        ``PARCATyN``, and ``DTYPE`` (e.g. ``{"PARAMCD": "BMI",
        "PARAM": "Body Mass Index", "PARAMN": 3, "PARCAT1": "ANTHRO"}``).
        Columns that don't exist yet are added to the dataset.  The new
        ``PARAMCD`` must not already exist in the dataset: appending under
        an existing code would break the PARAMCD ↔ PARAM/PARAMN one-to-one
        mapping that ADaM conformance checks enforce.

        *from_dataset*: optional BDS-shaped frame (``PARAMCD`` + ``AVAL``)
        to pivot the source parameters from — derive into this dataset
        **from another one** (e.g. compute a param in ADVS from ADLB rows).
        Defaults to the current pipeline frame.

        *where*: optional filter applied to the source records before the
        pivot (e.g. restrict to ``ANL01FL == "Y"`` or baseline rows) —
        the current dataset's rows are never dropped.

        A new AVAL that is infinite or NaN (for example a division by zero)
        becomes null, with a warning that gives the count, as SAS gives a
        missing value.

        Materialises the pipeline before appending.

        Examples:
            Derive BMI as a new PARAMCD from WEIGHT and HEIGHT::

                advs = (
                    vs_raw.adam
                    .derive_param(
                        by=["USUBJID", "ADT"],
                        set_values_to={"PARAMCD": "BMI",
                                       "PARAM": "Body Mass Index"},
                        parameter_filter={"WEIGHT": "WEIGHT",
                                          "HEIGHT": "HEIGHT"},
                        analysis_value=(
                            pl.col("WEIGHT") / (pl.col("HEIGHT") / 100) ** 2
                        ),
                    )
                    .to_frame()
                )

            Add a parameter computed from ANOTHER dataset's records::

                advs = (
                    advs.adam
                    .derive_param(
                        by=["USUBJID", "AVISIT"],
                        set_values_to={"PARAMCD": "BSCRCL",
                                       "PARAM": "Creatinine Clearance"},
                        parameter_filter={"CREAT": "CREAT"},
                        analysis_value='pl.col("CREAT") * 1.1',
                        from_dataset=adlb,
                        where='pl.col("ANL01FL") == "Y"',
                    )
                    .to_frame()
                )
        """
        from fleet.sdtm.utils import parse_expression

        if not parameter_filter:
            raise DerivationError("derive_param() requires at least one parameter_filter entry.")

        grps = by or ["USUBJID"]
        df = self.to_frame()

        # Guard the BDS one-to-one parameter mapping: appending rows under an
        # already-used PARAMCD would mix parameter-level metadata (PARAM,
        # PARAMN, PARCATy) for one code — a guaranteed conformance finding.
        new_paramcd = set_values_to.get("PARAMCD")
        if (
            isinstance(new_paramcd, str)
            and "PARAMCD" in df.columns
            and (df.get_column("PARAMCD") == new_paramcd).any()
        ):
            raise DerivationError(
                f"derive_param(): PARAMCD '{new_paramcd}' already exists in the dataset — "
                "appending would break the PARAMCD ↔ PARAM/PARAMN one-to-one mapping. "
                "Choose a new PARAMCD, or remove the existing rows first."
            )

        source = from_dataset if from_dataset is not None else df
        missing = [c for c in ("PARAMCD", "AVAL") if c not in source.columns]
        if missing:
            origin = "from_dataset" if from_dataset is not None else "the current frame"
            raise DerivationError(
                f"derive_param(): {origin} is missing required column(s) {missing} — "
                "the source must be BDS-shaped (PARAMCD + AVAL)."
            )
        if where is not None:
            where_expr = where if isinstance(where, pl.Expr) else parse_expression(str(where))
            source = source.filter(where_expr)

        # Pivot: for each alias in parameter_filter, get AVAL as that alias
        pivoted_parts = []
        for alias, paramcd_val in parameter_filter.items():
            part = source.filter(pl.col("PARAMCD") == paramcd_val).select(
                grps + [pl.col("AVAL").alias(alias)]
            )
            dup = part.group_by(grps).len().filter(pl.col("len") > 1)
            if dup.height:
                raise DerivationError(
                    f"derive_param(): PARAMCD '{paramcd_val}' has multiple records for "
                    f"{dup.height} {grps} group(s) (e.g. {dup.select(grps).row(0)}). "
                    "The derived rows would multiply — deduplicate the source, extend "
                    "by=, or narrow the records with where=."
                )
            pivoted_parts.append(part)

        # Join all pivoted parts on the by keys
        joined = pivoted_parts[0]
        for part in pivoted_parts[1:]:
            joined = joined.join(part, on=grps, how="inner", nulls_equal=True)

        # Compute the new AVAL
        aval_expr = (
            analysis_value
            if isinstance(analysis_value, pl.Expr)
            else parse_expression(str(analysis_value))
        )
        new_rows = joined.with_columns(aval_expr.alias("AVAL")).select(grps + ["AVAL"])
        if new_rows.schema["AVAL"].is_float():
            non_finite = new_rows.select((~pl.col("AVAL").is_finite()).sum()).item()
            if non_finite:
                import warnings

                warnings.warn(
                    f"derive_param(): {non_finite} new AVAL value(s) are infinite or NaN "
                    "(for example a division by zero) and are set to null.",
                    stacklevel=2,
                )
                new_rows = new_rows.with_columns(
                    pl.when(pl.col("AVAL").is_finite()).then(pl.col("AVAL")).alias("AVAL")
                )

        # Apply set_values_to constants
        for col_name, col_val in set_values_to.items():
            new_rows = new_rows.with_columns(pl.lit(col_val).alias(col_name))

        # Align schemas both ways: new set_values_to columns (e.g. DTYPE)
        # are added to the base frame instead of being silently dropped.
        for c in df.columns:
            if c not in new_rows.columns:
                new_rows = new_rows.with_columns(pl.lit(None).cast(df.schema[c]).alias(c))
        for c in new_rows.columns:
            if c not in df.columns:
                df = df.with_columns(pl.lit(None).cast(new_rows.schema[c]).alias(c))
        new_rows = new_rows.select(df.columns)

        combined = pl.concat([df, new_rows], how="vertical_relaxed")
        from fleet.core.lineage import record_row_step

        return record_row_step(self._materialise_then(combined), "derive_param", {})

    # ------------------------------------------------------------------ #
    # Private: YAML spec dispatcher for algorithm: std_function           #
    # ------------------------------------------------------------------ #

    # ------------------------------------------------------------------ #
    # 17. atoxgr — toxicity grading via criteria files                     #
    # ------------------------------------------------------------------ #

    def atoxgr(
        self,
        target: str,
        *,
        system: str = "ctcae_v5",
        direction: Literal["L", "H"],
        term_var: str,
        unit_var: str,
        signif_dig: int = 15,
        indicators: dict[str, list[str]] | None = None,
    ) -> AdamNamespace:
        """Derive a toxicity grade, as admiral ``derive_var_atoxgr_dir``.

        Materialises the pipeline and grades every row whose term has
        criteria in *direction*.  The bundled criteria are generated from the
        admiral metadata (``scripts/regen_grading_criteria.R``), so each term
        follows the admiral ``case_when``: for example, a null ``BNRIND``
        counts as not abnormal and the ULN criteria apply, and CTCAE v5 INR
        takes the worse of the absolute and the baseline cut-offs (admiral
        COMMENT: worst case, assume on anticoagulation).  The term and the
        unit match without case.  A row with another unit, a null unit, no
        criteria or a population no criteria cover gets a null grade.  Every
        row stays, in its order.

        The ``ctcae_*``, ``daids`` systems hold SI cut-offs (hemoglobin in
        g/L); the ``*_uscv`` systems hold US conventional units (g/dL).  A
        row whose unit is not a unit of the criteria gets null, with a
        warning that gives the count.

        Args:
            target: Name of the output grade column (e.g. ``"ATOXGRL"``).
            system: Grading system name (e.g. ``"ctcae_v5"``, ``"daids"``)
                or path to a custom JSON criteria file (schema version 2).
            direction: ``"L"`` (low) or ``"H"`` (high).
            term_var: Column holding the lab-test / term name.
            unit_var: Column holding the unit of measure (e.g. ``"AVALU"``).
                Required, as admiral: each row is graded with the cut-offs
                of its own unit.
            signif_dig: Significant digits for comparison (default 15, as
                admiral ``signif_digits``).
            indicators: Values of the indicator params of the criteria
                (default ``{"high_indicator": ["HIGH", "H"],
                "low_indicator": ["LOW", "L"]}``).

        Returns:
            AdamNamespace: A fresh namespace wrapping the graded frame.

        Raises:
            DerivationError: When *direction* is not ``"L"`` or ``"H"``, or a
                needed column is missing.

        References:
            admiral ``derive_var_atoxgr_dir`` and the metadata tables
            ``atoxgr_criteria_ctcv4/5/6`` and ``atoxgr_criteria_daids``
            (SI and USCV), admiral 1.4.1, where ``get_unit_expr`` is required;
            NCI CTCAE v4.03, v5.0, v6.0; DAIDS grading table v2.1. ADR-0028.

        Examples:
            Grade low-direction anemia using CTCAE v5::

                adlb = (
                    lb_raw.adam
                    .atoxgr("ATOXGRL", system="ctcae_v5",
                            direction="L", term_var="PARAMCD",
                            unit_var="AVALU")
                    .to_frame()
                )
        """
        from .grading._compiler import grade_dataset
        from .grading._registry import load_criteria

        criteria = load_criteria(system)
        df = self.to_frame()
        # Provide standard BNRIND defaults when no indicators are given.
        if indicators is None:
            indicators = {
                "high_indicator": ["HIGH", "H"],
                "low_indicator": ["LOW", "L"],
            }
        graded = grade_dataset(
            df,
            criteria,
            target=target,
            direction=direction,
            term_var=term_var,
            unit_var=unit_var,
            signif_dig=signif_dig,
            indicators=indicators,
        )
        return self._materialise_then(graded)

    # ------------------------------------------------------------------ #
    # 18. combine_grades — merge low/high toxicity grades                  #
    # ------------------------------------------------------------------ #

    def combine_grades(
        self,
        target: str = "ATOXGR",
        *,
        low_var: str = "ATOXGRL",
        high_var: str = "ATOXGRH",
        low_desc_var: str = "ATOXDSCL",
        high_desc_var: str = "ATOXDSCH",
    ) -> AdamNamespace:
        """Combine low and high toxicity grades into a signed grade, as admiral.

        Low grades are prefixed with ``"-"``; high grades are kept as-is.
        Both null → null.  ``"0"`` only when each side is ``"0"`` or its
        description is null (no criteria in that direction).  Low ``"0"``
        with a null high grade and a present high description gives null:
        the high grade is unknown (for example ANRHI is missing).

        Args:
            target: Name of the output column (default ``"ATOXGR"``).
            low_var: Low-direction grade column (default ``"ATOXGRL"``).
            high_var: High-direction grade column (default ``"ATOXGRH"``).
            low_desc_var: Low-grade term description column (default
                ``"ATOXDSCL"``).  Required in the data; for a
                one-direction study, add it as a null column.
            high_desc_var: High-grade term description column (default
                ``"ATOXDSCH"``).  Required in the data, as *low_desc_var*.

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

        Raises:
            DerivationError: When a grade or description column is missing.

        References:
            admiral ``derive_var_atoxgr`` (admiral 1.4.1): ``lowgrade == "0" |
            is.na(lowdesc)`` and the same for high give "0". ADR-0028.

        Examples:
            Combine low/high grades into ATOXGR::

                adlb = (
                    lb_raw.adam
                    .atoxgr("ATOXGRL", system="ctcae_v5", direction="L",
                            term_var="ATOXDSCL", unit_var="AVALU")
                    .atoxgr("ATOXGRH", system="ctcae_v5", direction="H",
                            term_var="ATOXDSCH", unit_var="AVALU")
                    .combine_grades("ATOXGR")
                    .to_frame()
                )
        """
        from .grading._compiler import combine_grades_expr

        names = self._lazy.collect_schema().names()
        missing = [c for c in (low_var, high_var, low_desc_var, high_desc_var) if c not in names]
        if missing:
            raise DerivationError(
                f"combine_grades('{target}'): column(s) {missing} are missing. The "
                "descriptions tell a direction with no criteria from an unknown grade; "
                "for a one-direction study add the other description as a null column."
            )
        return self._chain(
            combine_grades_expr(
                low_var,
                high_var,
                low_desc_var=low_desc_var,
                high_desc_var=high_desc_var,
            ).alias(target),
            verb="combine_grades",
        )

    # ------------------------------------------------------------------ #
    # 19. transform — arbitrary DataFrame → DataFrame function            #
    # ------------------------------------------------------------------ #

    def transform(
        self,
        fn: str | Callable[[pl.DataFrame], pl.DataFrame],
        *,
        label: str | None = None,  # noqa: ARG002  — cosmetic, intentionally unused
    ) -> AdamNamespace:
        """
        Apply an arbitrary ``(pl.DataFrame) -> pl.DataFrame`` function.

        The pending expression pipeline is materialised before the function
        is called, so the function always receives a fully committed frame.

        Args:
            fn: Either a callable directly, or the registered name of a
                transform (see :func:`fleet.adam.transforms.register_transform`).
            label: Optional cosmetic label for documentation/lineage; has no
                effect on the output.

        Raises:
            KeyError: If *fn* is a string that has not been registered.
            TypeError: If *fn* is neither a callable nor a string, or if the
                function does not return a ``pl.DataFrame``.

        Returns:
            AdamNamespace: A fresh namespace wrapping the transformed frame.

        Examples:
            Register and apply a custom age-group transform::

                from fleet.adam.transforms import register_transform

                @register_transform("add_agegr1")
                def add_agegr1(df):
                    return df.with_columns(
                        pl.when(pl.col("AGE") < 65).then(pl.lit("<65"))
                          .otherwise(pl.lit(">=65")).alias("AGEGR1")
                    )

                adsl = (
                    dm_raw.adam
                    .assign("STUDYID", value="S01")
                    .transform("add_agegr1")
                    .to_frame()
                )
        """
        from .transforms import get_transform

        if isinstance(fn, str):
            fn = get_transform(fn)  # raises KeyError if not found
        elif not callable(fn):
            raise VerbUsageError(
                f"transform() expects a callable or a registered name string, "
                f"got {type(fn).__name__!r}."
            )

        # Materialise pending expressions so the function sees a full frame.
        committed = self.to_frame()
        result = fn(committed)

        if not isinstance(result, pl.DataFrame):
            raise VerbUsageError(
                f"Transform function must return a polars DataFrame, got {type(result).__name__!r}."
            )

        return self._materialise_then(result)

    # ------------------------------------------------------------------ #
    # Spec-driven pipeline: from_spec() is inherited from                  #
    # SharedVerbsMixin and executes through fleet.core.spec_registry.      #
    # ------------------------------------------------------------------ #

    # ------------------------------------------------------------------ #
    # ------------------------------------------------------------------ #
    # ADaM sub-structures (accessed as df.adam.adsl / df.adam.occds)       #
    # ------------------------------------------------------------------ #

    def _sub_namespace(self, cls: type[_SubNS]) -> _SubNS:
        """Hand the accumulated state over to a sub-namespace.

        The lazy plan is passed through unchanged (no materialisation)
        and pins, pin lineage, variable lineage, pending FK checks, and
        FK policy all propagate, so ``.pin("ADSL", adsl).occds`` keeps
        its pins.  The parent domain tag carries over unless the
        sub-namespace sets its own (ADSL).
        """
        new = cls(self._lazy)
        new._pinned = dict(getattr(self, "_pinned", {}))
        new._pin_lineage = list(getattr(self, "_pin_lineage", []))
        new._lineage = list(getattr(self, "_lineage", []))
        new._row_steps = list(getattr(self, "_row_steps", []))
        new._root_lazy = getattr(self, "_root_lazy", self._lazy)
        new._pending_fk_checks = list(getattr(self, "_pending_fk_checks", []))
        new._pending_join_checks = list(getattr(self, "_pending_join_checks", []))
        fk_severity = getattr(self, "_fk_severity", None)
        if fk_severity is not None:
            new._fk_severity = fk_severity
        if getattr(new, "_domain", None) is None:
            new._domain = getattr(self, "_domain", None)
        return new

    @property
    def adsl(self) -> ADSLNamespace:
        """ADSL (one-row-per-subject) derivations: treatment dates, duration, population flags."""
        from .adsl_namespace import ADSLNamespace

        return self._sub_namespace(ADSLNamespace)

    @property
    def occds(self) -> OCCDSNamespace:
        """OCCDS (one-row-per-event) derivations: sequencing, worst flag, treatment-emergent."""
        from .occds_namespace import OCCDSNamespace

        return self._sub_namespace(OCCDSNamespace)

    # ------------------------------------------------------------------ #
    # Therapeutic-area extensions (accessed as df.adam.<ta>)               #
    # ------------------------------------------------------------------ #

    @property
    def onco(self) -> OncoNamespace:
        """Oncology derivations (admiralonco-inspired): RECIST, BOR, response flags."""
        from .onco_namespace import OncoNamespace

        return self._sub_namespace(OncoNamespace)

    @property
    def ophtha(self) -> OphthaNamespace:
        """Ophthalmology derivations (admiralophtha-inspired): ETDRS/LogMAR, study eye."""
        from .ophtha_namespace import OphthaNamespace

        return self._sub_namespace(OphthaNamespace)

    @property
    def peds(self) -> PedsNamespace:
        """Pediatrics derivations (admiralpeds-inspired): age, prematurity, BMI."""
        from .peds_namespace import PedsNamespace

        return self._sub_namespace(PedsNamespace)

    @property
    def vaccine(self) -> VaccineNamespace:
        """Vaccine derivations (admiralvaccine-inspired): fever, seroconversion."""
        from .vaccine_namespace import VaccineNamespace

        return self._sub_namespace(VaccineNamespace)

    @property
    def metabolic(self) -> MetabolicNamespace:
        """Metabolic derivations (admiralmetabolic-inspired): waist ratios, body fat."""
        from .metabolic_namespace import MetabolicNamespace

        return self._sub_namespace(MetabolicNamespace)

    @property
    def neuro(self) -> NeuroNamespace:
        """Neuroscience derivations (admiralneuro-inspired): Centiloid, MMSE, CDR-SoB."""
        from .neuro_namespace import NeuroNamespace

        return self._sub_namespace(NeuroNamespace)

    @property
    def pk(self) -> PKNamespace:
        """PK (pharmacokinetics) derivations: BLQ flags, actual/nominal time, dose normalisation."""
        from .pk_namespace import PKNamespace

        return self._sub_namespace(PKNamespace)

    @property
    def tte(self) -> TTENamespace:
        """Time-to-event (ADTTE) derivations: event/censor sources, param, AVAL, KM inputs."""
        from .tte_namespace import TTENamespace

        return self._sub_namespace(TTENamespace)

adsl property

adsl

ADSL (one-row-per-subject) derivations: treatment dates, duration, population flags.

occds property

occds

OCCDS (one-row-per-event) derivations: sequencing, worst flag, treatment-emergent.

onco property

onco

Oncology derivations (admiralonco-inspired): RECIST, BOR, response flags.

ophtha property

ophtha

Ophthalmology derivations (admiralophtha-inspired): ETDRS/LogMAR, study eye.

peds property

peds

Pediatrics derivations (admiralpeds-inspired): age, prematurity, BMI.

vaccine property

vaccine

Vaccine derivations (admiralvaccine-inspired): fever, seroconversion.

metabolic property

metabolic

Metabolic derivations (admiralmetabolic-inspired): waist ratios, body fat.

neuro property

neuro

Neuroscience derivations (admiralneuro-inspired): Centiloid, MMSE, CDR-SoB.

pk property

pk

PK (pharmacokinetics) derivations: BLQ flags, actual/nominal time, dose normalisation.

tte property

tte

Time-to-event (ADTTE) derivations: event/censor sources, param, AVAL, KM inputs.

baseline

baseline(
    target,
    *,
    aval="AVAL",
    baseline_flag="ABLFL",
    by=None,
    strict=True
)

Derive BASE as the AVAL where the baseline flag equals "Y".

Uses a window function so all records in the same group receive the same baseline value. A group with more than one flagged record has an ambiguous baseline: with strict=True (default) this raises a DerivationError naming the offending groups (admiral semantics); strict=False keeps the legacy behaviour (silently taking the maximum flagged value) but emits a UserWarning.

Parameters:

Name Type Description Default
target str

Name of the output column (e.g. "BASE").

required
aval str

Analysis value column (default "AVAL").

'AVAL'
baseline_flag str

Flag column indicating the baseline record.

'ABLFL'
by list[str] | None

Partition columns (default ["USUBJID", "PARAMCD"]).

None
strict bool

Raise when a group has multiple baseline-flagged records (default True).

True

Returns:

Name Type Description
AdamNamespace AdamNamespace

The namespace with target appended.

Raises:

Type Description
DerivationError

When strict=True and at least one group carries more than one baseline-flagged record.

Examples:

Propagate baseline AVAL to all records::

advs = (
    vs_raw.adam
    .baseline("BASE", aval="AVAL", baseline_flag="ABLFL",
              by=["USUBJID", "PARAMCD"])
    .to_frame()
)
Source code in src/fleet/adam/namespace.py
def baseline(
    self,
    target: str,
    *,
    aval: str = "AVAL",
    baseline_flag: str = "ABLFL",
    by: list[str] | None = None,
    strict: bool = True,
) -> AdamNamespace:
    """Derive BASE as the AVAL where the baseline flag equals ``"Y"``.

    Uses a window function so all records in the same group receive the
    same baseline value.  A group with **more than one** flagged
    record has an ambiguous baseline: with ``strict=True`` (default)
    this raises a ``DerivationError`` naming the offending groups
    (admiral semantics); ``strict=False`` keeps the legacy behaviour
    (silently taking the maximum flagged value) but emits a
    ``UserWarning``.

    Args:
        target: Name of the output column (e.g. ``"BASE"``).
        aval: Analysis value column (default ``"AVAL"``).
        baseline_flag: Flag column indicating the baseline record.
        by: Partition columns (default ``["USUBJID", "PARAMCD"]``).
        strict: Raise when a group has multiple baseline-flagged
            records (default ``True``).

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

    Raises:
        DerivationError: When ``strict=True`` and at least one group
            carries more than one baseline-flagged record.

    Examples:
        Propagate baseline AVAL to all records::

            advs = (
                vs_raw.adam
                .baseline("BASE", aval="AVAL", baseline_flag="ABLFL",
                          by=["USUBJID", "PARAMCD"])
                .to_frame()
            )
    """
    import warnings

    grps = by or ["USUBJID", "PARAMCD"]
    schema_names = self._lazy.collect_schema().names()
    if baseline_flag not in schema_names or any(g not in schema_names for g in grps):
        # Missing columns — defer to _chain's verb-attributed error.
        return self._chain(
            baseline(aval=aval, baseline_flag_col=baseline_flag, group_by=grps, target=target),
            verb="baseline",
        )
    dup_groups = (
        self._lazy.filter(pl.col(baseline_flag) == "Y")
        .group_by(grps)
        .agg(pl.len().alias("__n_baseline__"))
        .filter(pl.col("__n_baseline__") > 1)
        .collect()
    )
    if dup_groups.height:
        sample = dup_groups.select(grps).head(5).rows()
        keys = "; ".join(", ".join(f"{k}={v!r}" for k, v in zip(grps, row)) for row in sample)
        more = f" (+{dup_groups.height - 5} more)" if dup_groups.height > 5 else ""
        detail = (
            f"baseline('{target}'): {dup_groups.height} group(s) have more than one "
            f"record flagged {baseline_flag}='Y' — the baseline is ambiguous. "
            f"Offending groups: {keys}{more}."
        )
        if strict:
            raise DerivationError(
                f"{detail} Deduplicate the baseline flag (e.g. via "
                ".flag(..., criteria='last') or .nodup(...)) or pass strict=False "
                "to keep the legacy max() behaviour."
            )
        warnings.warn(
            f"{detail} Taking the maximum flagged value per group (strict=False).",
            stacklevel=2,
        )
    return self._chain(
        baseline(aval=aval, baseline_flag_col=baseline_flag, group_by=grps, target=target),
        verb="baseline",
    )

chg

chg(target, *, aval='AVAL', base='BASE')

Compute change from baseline: CHG = AVAL - BASE.

Parameters:

Name Type Description Default
target str

Name of the output column (e.g. "CHG").

required
aval str

Analysis value column.

'AVAL'
base str

Baseline value column.

'BASE'

Returns:

Name Type Description
AdamNamespace AdamNamespace

The namespace with target appended.

Examples:

Derive CHG from AVAL and BASE::

advs = (
    vs_raw.adam
    .chg("CHG", aval="AVAL", base="BASE")
    .to_frame()
)
Source code in src/fleet/adam/namespace.py
def chg(
    self,
    target: str,
    *,
    aval: str = "AVAL",
    base: str = "BASE",
) -> AdamNamespace:
    """Compute change from baseline: ``CHG = AVAL - BASE``.

    Args:
        target: Name of the output column (e.g. ``"CHG"``).
        aval: Analysis value column.
        base: Baseline value column.

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

    Examples:
        Derive CHG from AVAL and BASE::

            advs = (
                vs_raw.adam
                .chg("CHG", aval="AVAL", base="BASE")
                .to_frame()
            )
    """
    return self._chain(chg(aval=aval, base=base, target=target), verb="chg")

pchg

pchg(target, *, aval='AVAL', base='BASE')

Compute percent change from baseline.

PCHG = (AVAL - BASE) / BASE * 100. Returns null when BASE is null or zero.

Parameters:

Name Type Description Default
target str

Name of the output column (e.g. "PCHG").

required
aval str

Analysis value column.

'AVAL'
base str

Baseline value column.

'BASE'

Returns:

Name Type Description
AdamNamespace AdamNamespace

The namespace with target appended.

Examples:

Derive PCHG from AVAL and BASE::

advs = (
    vs_raw.adam
    .pchg("PCHG", aval="AVAL", base="BASE")
    .to_frame()
)
Source code in src/fleet/adam/namespace.py
def pchg(
    self,
    target: str,
    *,
    aval: str = "AVAL",
    base: str = "BASE",
) -> AdamNamespace:
    """Compute percent change from baseline.

    ``PCHG = (AVAL - BASE) / BASE * 100``.  Returns null when BASE is
    null or zero.

    Args:
        target: Name of the output column (e.g. ``"PCHG"``).
        aval: Analysis value column.
        base: Baseline value column.

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

    Examples:
        Derive PCHG from AVAL and BASE::

            advs = (
                vs_raw.adam
                .pchg("PCHG", aval="AVAL", base="BASE")
                .to_frame()
            )
    """
    return self._chain(pchg(aval=aval, base=base, target=target), verb="pchg")

bmi

bmi(target, *, weight, height, round_digits=None)

Derive Body Mass Index: weight_kg / (height_cm / 100) ** 2.

The value keeps full precision. A height of 0 gives null, as SAS gives a missing value for a division by zero.

Parameters:

Name Type Description Default
target str

Name of the output column.

required
weight str

Column containing weight in kg.

required
height str

Column containing height in cm.

required
round_digits int | None

Decimal places, rounded as SAS ROUND (half away from zero). Default None: no rounding.

None

Returns:

Name Type Description
AdamNamespace AdamNamespace

The namespace with target appended.

References

admiral compute_bmi (pharmaverse): full precision, NA for height 0. ADR-0025: a derived value is rounded only when the call says so.

Examples:

Compute BMI from weight and height::

advs = (
    vs_raw.adam
    .bmi("BMI", weight="WEIGHT", height="HEIGHT")
    .to_frame()
)
Source code in src/fleet/adam/namespace.py
def bmi(
    self,
    target: str,
    *,
    weight: str,
    height: str,
    round_digits: int | None = None,
) -> AdamNamespace:
    """Derive Body Mass Index: ``weight_kg / (height_cm / 100) ** 2``.

    The value keeps full precision.  A height of 0 gives null, as SAS
    gives a missing value for a division by zero.

    Args:
        target: Name of the output column.
        weight: Column containing weight in kg.
        height: Column containing height in cm.
        round_digits: Decimal places, rounded as SAS ``ROUND`` (half away
            from zero).  Default ``None``: no rounding.

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

    References:
        admiral ``compute_bmi`` (pharmaverse): full precision, NA for height 0.
        ADR-0025: a derived value is rounded only when the call says so.

    Examples:
        Compute BMI from weight and height::

            advs = (
                vs_raw.adam
                .bmi("BMI", weight="WEIGHT", height="HEIGHT")
                .to_frame()
            )
    """
    return self._chain(
        _bmi_expr(weight=weight, height=height, target=target, round_digits=round_digits),
        verb="bmi",
    )

nrind

nrind(target, *, value, low, high, signif_dig=15)

Categorise value relative to normal range: LOW / NORMAL / HIGH.

The value and the limits are compared at signif_dig significant digits, so float noise (1.3 x 88.4 = 114.92000000000002) does not move a value at the limit out of the range. A null or NaN value gives null.

Parameters:

Name Type Description Default
target str

Name of the output column (e.g. "NRIND").

required
value str

Column containing the numeric result.

required
low str

Column containing the lower limit of normal.

required
high str

Column containing the upper limit of normal.

required
signif_dig int

Significant digits for the comparison (default 15).

15

Returns:

Name Type Description
AdamNamespace AdamNamespace

The namespace with target appended.

References

admiral derive_var_anrind (pharmaverse): signif(x, 15) on AVAL, ANRLO and ANRHI before the comparison.

Examples:

Derive normal range indicator for lab results::

adlb = (
    lb_raw.adam
    .nrind("NRIND", value="LBSTRESN",
           low="LBSTNRLO", high="LBSTNRHI")
    .to_frame()
)
Source code in src/fleet/adam/namespace.py
def nrind(
    self,
    target: str,
    *,
    value: str,
    low: str,
    high: str,
    signif_dig: int = 15,
) -> AdamNamespace:
    """Categorise *value* relative to normal range: LOW / NORMAL / HIGH.

    The value and the limits are compared at *signif_dig* significant
    digits, so float noise (1.3 x 88.4 = 114.92000000000002) does not
    move a value at the limit out of the range.  A null or NaN value gives
    null.

    Args:
        target: Name of the output column (e.g. ``"NRIND"``).
        value: Column containing the numeric result.
        low: Column containing the lower limit of normal.
        high: Column containing the upper limit of normal.
        signif_dig: Significant digits for the comparison (default 15).

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

    References:
        admiral ``derive_var_anrind`` (pharmaverse): ``signif(x, 15)`` on AVAL,
        ANRLO and ANRHI before the comparison.

    Examples:
        Derive normal range indicator for lab results::

            adlb = (
                lb_raw.adam
                .nrind("NRIND", value="LBSTRESN",
                       low="LBSTNRLO", high="LBSTNRHI")
                .to_frame()
            )
    """
    return self._chain(
        _nrind_expr(value=value, low=low, high=high, target=target, signif_dig=signif_dig),
        verb="nrind",
    )

on_treatment

on_treatment(
    target="ONTRTFL",
    *,
    adt,
    trtsdt,
    trtedt,
    open_ended=True
)

Set target to "Y" when adt is within [trtsdt, trtedt].

When open_ended is True (default) and trtedt is null, the interval is treated as ongoing (adt >= trtsdt suffices). --DTC text is read by its date portion (a partial or blank value gives null); a number raises. When adt and trtsdt are both pl.Datetime, the start comparison keeps the time, so a pre-dose record on the first dose day is not on treatment; the end comparison is at date level.

Parameters:

Name Type Description Default
target str

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

'ONTRTFL'
adt str

Analysis date column.

required
trtsdt str

Treatment start date column.

required
trtedt str

Treatment end date column.

required
open_ended bool

Treat null trtedt as open-ended (default True).

True

Returns:

Name Type Description
AdamNamespace AdamNamespace

The namespace with target appended.

References

admiral derive_var_ontrtfl (start compared with time when both are date-times); ADR-0011 and ADR-0022.

Examples:

Derive on-treatment flag::

advs = (
    vs_raw.adam
    .on_treatment("ONTRTFL", adt="ADT",
                  trtsdt="TRTSDT", trtedt="TRTEDT")
    .to_frame()
)
Source code in src/fleet/adam/namespace.py
def on_treatment(
    self,
    target: str = "ONTRTFL",
    *,
    adt: str,
    trtsdt: str,
    trtedt: str,
    open_ended: bool = True,
) -> AdamNamespace:
    """Set *target* to ``"Y"`` when *adt* is within [trtsdt, trtedt].

    When *open_ended* is ``True`` (default) and *trtedt* is null, the
    interval is treated as ongoing (``adt >= trtsdt`` suffices).
    ``--DTC`` text is read by its date portion (a partial or blank
    value gives null); a number raises.  When *adt* and *trtsdt* are
    both ``pl.Datetime``, the start comparison keeps the time, so a
    pre-dose record on the first dose day is not on treatment; the end
    comparison is at date level.

    Args:
        target: Name of the output column (default ``"ONTRTFL"``).
        adt: Analysis date column.
        trtsdt: Treatment start date column.
        trtedt: Treatment end date column.
        open_ended: Treat null *trtedt* as open-ended (default ``True``).

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

    References:
        admiral ``derive_var_ontrtfl`` (start compared with time when
        both are date-times); ADR-0011 and ADR-0022.

    Examples:
        Derive on-treatment flag::

            advs = (
                vs_raw.adam
                .on_treatment("ONTRTFL", adt="ADT",
                              trtsdt="TRTSDT", trtedt="TRTEDT")
                .to_frame()
            )
    """
    return self._chain(
        _on_treatment_expr(
            adt=adt,
            trtsdt=trtsdt,
            trtedt=trtedt,
            target=target,
            open_ended=open_ended,
            dtypes=self._lazy.collect_schema(),
        ),
        verb="on_treatment",
    )

shift

shift(target, *, baseline_cat, post_cat, sep=' to ')

Derive a categorical shift label: "<baseline><sep><post>".

Parameters:

Name Type Description Default
target str

Name of the output column (e.g. "SHIFT1").

required
baseline_cat str

Column with baseline category (e.g. "BNRIND").

required
post_cat str

Column with post-baseline category (e.g. "NRIND").

required
sep str

Separator string (default " to ").

' to '

Returns:

Name Type Description
AdamNamespace AdamNamespace

The namespace with target appended.

Examples:

Create a shift variable from baseline and post normal range::

adlb = (
    lb_raw.adam
    .shift("SHIFT1", baseline_cat="BNRIND",
           post_cat="NRIND")
    .to_frame()
)
Source code in src/fleet/adam/namespace.py
def shift(
    self,
    target: str,
    *,
    baseline_cat: str,
    post_cat: str,
    sep: str = " to ",
) -> AdamNamespace:
    """Derive a categorical shift label: ``"<baseline><sep><post>"``.

    Args:
        target: Name of the output column (e.g. ``"SHIFT1"``).
        baseline_cat: Column with baseline category (e.g. ``"BNRIND"``).
        post_cat: Column with post-baseline category (e.g. ``"NRIND"``).
        sep: Separator string (default ``" to "``).

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

    Examples:
        Create a shift variable from baseline and post normal range::

            adlb = (
                lb_raw.adam
                .shift("SHIFT1", baseline_cat="BNRIND",
                       post_cat="NRIND")
                .to_frame()
            )
    """
    return self._chain(
        _shift_expr(baseline_cat=baseline_cat, post_cat=post_cat, target=target, sep=sep),
        verb="shift",
    )

bsa

bsa(
    target,
    *,
    weight,
    height,
    method="Mosteller",
    round_digits=None
)

Derive Body Surface Area in m², at full precision.

Parameters:

Name Type Description Default
target str

Name of the output column.

required
weight str

Column containing weight in kg.

required
height str

Column containing height in cm.

required
method str

Formula to use — "Mosteller" (default), "DuBois", "Haycock", or "Gehan-George".

'Mosteller'
round_digits int | None

Decimal places, rounded as SAS ROUND (half away from zero). Default None: no rounding.

None

Returns:

Name Type Description
AdamNamespace AdamNamespace

The namespace with target appended.

References

admiral compute_bsa (pharmaverse): full precision. ADR-0025: a derived value is rounded only when the call says so.

Examples:

Compute BSA using the Mosteller formula::

advs = (
    vs_raw.adam
    .bsa("BSA", weight="WEIGHT", height="HEIGHT")
    .to_frame()
)
Source code in src/fleet/adam/namespace.py
def bsa(
    self,
    target: str,
    *,
    weight: str,
    height: str,
    method: str = "Mosteller",
    round_digits: int | None = None,
) -> AdamNamespace:
    """Derive Body Surface Area in m², at full precision.

    Args:
        target: Name of the output column.
        weight: Column containing weight in kg.
        height: Column containing height in cm.
        method: Formula to use — ``"Mosteller"`` (default), ``"DuBois"``,
            ``"Haycock"``, or ``"Gehan-George"``.
        round_digits: Decimal places, rounded as SAS ``ROUND`` (half away
            from zero).  Default ``None``: no rounding.

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

    References:
        admiral ``compute_bsa`` (pharmaverse): full precision.
        ADR-0025: a derived value is rounded only when the call says so.

    Examples:
        Compute BSA using the Mosteller formula::

            advs = (
                vs_raw.adam
                .bsa("BSA", weight="WEIGHT", height="HEIGHT")
                .to_frame()
            )
    """
    return self._chain(
        _bsa_expr(
            weight=weight,
            height=height,
            method=method,
            target=target,
            round_digits=round_digits,
        ),
        verb="bsa",
    )

map

map(
    target="MAP",
    *,
    systolic="SYSBP",
    diastolic="DIABP",
    round_digits=None
)

Derive Mean Arterial Pressure: DBP + (SBP - DBP) / 3, at full precision.

Parameters:

Name Type Description Default
target str

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

'MAP'
systolic str

Systolic blood pressure column.

'SYSBP'
diastolic str

Diastolic blood pressure column.

'DIABP'
round_digits int | None

Decimal places, rounded as SAS ROUND (half away from zero). Default None: no rounding.

None

Returns:

Name Type Description
AdamNamespace AdamNamespace

The namespace with target appended.

References

admiral compute_map (pharmaverse): full precision. ADR-0025: a derived value is rounded only when the call says so.

Examples:

Compute MAP from blood pressure columns::

advs = (
    vs_raw.adam
    .map("MAP", systolic="SYSBP", diastolic="DIABP")
    .to_frame()
)
Source code in src/fleet/adam/namespace.py
def map(
    self,
    target: str = "MAP",
    *,
    systolic: str = "SYSBP",
    diastolic: str = "DIABP",
    round_digits: int | None = None,
) -> AdamNamespace:
    """Derive Mean Arterial Pressure: ``DBP + (SBP - DBP) / 3``, at full precision.

    Args:
        target: Name of the output column (default ``"MAP"``).
        systolic: Systolic blood pressure column.
        diastolic: Diastolic blood pressure column.
        round_digits: Decimal places, rounded as SAS ``ROUND`` (half away
            from zero).  Default ``None``: no rounding.

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

    References:
        admiral ``compute_map`` (pharmaverse): full precision.
        ADR-0025: a derived value is rounded only when the call says so.

    Examples:
        Compute MAP from blood pressure columns::

            advs = (
                vs_raw.adam
                .map("MAP", systolic="SYSBP", diastolic="DIABP")
                .to_frame()
            )
    """
    return self._chain(
        _map_expr(
            systolic=systolic, diastolic=diastolic, target=target, round_digits=round_digits
        ),
        verb="map",
    )

qtc

qtc(
    target="QTC",
    *,
    qt="QT",
    rr="RR",
    method="Fridericia",
    rr_unit="ms",
    round_digits=None
)

Derive corrected QT interval, as admiral compute_qtc, at full precision.

Parameters:

Name Type Description Default
target str

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

'QTC'
qt str

QT interval column, in ms.

'QT'
rr str

RR interval column, in rr_unit.

'RR'
method str

Correction formula — "Fridericia" (default) or "Bazett".

'Fridericia'
rr_unit str

Unit of rr: "ms" (default) or "msec", or "s" or "sec".

'ms'
round_digits int | None

Decimal places, rounded as SAS ROUND (half away from zero). Default None: no rounding.

None

Returns:

Name Type Description
AdamNamespace AdamNamespace

The namespace with target appended.

Raises:

Type Description
DerivationError

When rr_unit is unknown, or a value cannot be in its unit: an RR under 10 in ms, an RR of 10 or more in seconds, or a QT under 10 ms.

References

admiral compute_qtc (pharmaverse): RR in ms, QT in ms, full precision. ADR-0025: a derived value is rounded only when the call says so.

Examples:

Derive QTcF from QT and RR, both in ms::

adeg = (
    eg_raw.adam
    .qtc("QTCF", qt="QT", rr="RR", method="Fridericia")
    .to_frame()
)
Source code in src/fleet/adam/namespace.py
def qtc(
    self,
    target: str = "QTC",
    *,
    qt: str = "QT",
    rr: str = "RR",
    method: str = "Fridericia",
    rr_unit: str = "ms",
    round_digits: int | None = None,
) -> AdamNamespace:
    """Derive corrected QT interval, as admiral ``compute_qtc``, at full precision.

    Args:
        target: Name of the output column (default ``"QTC"``).
        qt: QT interval column, in ms.
        rr: RR interval column, in *rr_unit*.
        method: Correction formula — ``"Fridericia"`` (default) or
            ``"Bazett"``.
        rr_unit: Unit of *rr*: ``"ms"`` (default) or ``"msec"``, or
            ``"s"`` or ``"sec"``.
        round_digits: Decimal places, rounded as SAS ``ROUND`` (half away
            from zero).  Default ``None``: no rounding.

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

    Raises:
        DerivationError: When *rr_unit* is unknown, or a value cannot be
            in its unit: an RR under 10 in ms, an RR of 10 or more in
            seconds, or a QT under 10 ms.

    References:
        admiral ``compute_qtc`` (pharmaverse): RR in ms, QT in ms, full precision.
        ADR-0025: a derived value is rounded only when the call says so.

    Examples:
        Derive QTcF from QT and RR, both in ms::

            adeg = (
                eg_raw.adam
                .qtc("QTCF", qt="QT", rr="RR", method="Fridericia")
                .to_frame()
            )
    """
    expr = _qtc_expr(
        qt=qt, rr=rr, method=method, target=target, rr_unit=rr_unit, round_digits=round_digits
    )
    schema_names = self._lazy.collect_schema().names()
    if qt in schema_names and rr in schema_names:
        seconds = rr_unit.lower() in ("s", "sec")
        rr_num = pl.col(rr).cast(pl.Float64, strict=False)
        bad_rr = rr_num >= 10 if seconds else rr_num < 10
        counts = (
            self._lazy.select(
                bad_rr.sum().alias("rr"),
                (pl.col(qt).cast(pl.Float64, strict=False) < 10).sum().alias("qt"),
            )
            .collect()
            .row(0)
        )
        if counts[0]:
            raise DerivationError(
                f"qtc('{target}'): {counts[0]} {rr} value(s) cannot be in "
                f"rr_unit={rr_unit!r} (RR in ms is 10 or more; in seconds it is under 10). "
                "State the unit of the data with rr_unit=."
            )
        if counts[1]:
            raise DerivationError(
                f"qtc('{target}'): {counts[1]} {qt} value(s) are under 10. QT must be in ms."
            )
    return self._chain(expr, verb="qtc")

derive_summary_records

derive_summary_records(
    *,
    by,
    analysis_var="AVAL",
    set_values_to,
    stat="mean",
    where=None
)

Compute a summary statistic per group and append the results as new records.

set_values_to: column → value mapping applied to every new record (e.g. {"PARAMCD": "AVGBP", "DTYPE": "AVERAGE"}).

stat: "mean" (default), "sum", "min", "max", "median", "count". A group with only null values gives null for every stat except "count", which gives 0, as SAS SUM() and PROC MEANS.

where: filter on the source records of the summary. The rows of the dataset are all kept. A second call in one chain reads the rows that the first call added: give where=pl.col("DTYPE").is_null() to summarise only collected records. When where is None and the source holds a non-null DTYPE, the verb warns.

Materialises the current pipeline before concatenation.

Examples:

Compute mean AVAL per subject and parameter::

advs = (
    vs_raw.adam
    .derive_summary_records(
        by=["USUBJID", "PARAMCD"],
        analysis_var="AVAL",
        set_values_to={"DTYPE": "AVERAGE"},
        stat="mean",
    )
    .to_frame()
)
Source code in src/fleet/adam/namespace.py
def derive_summary_records(
    self,
    *,
    by: list[str],
    analysis_var: str = "AVAL",
    set_values_to: dict[str, Any],
    stat: Literal["mean", "sum", "min", "max", "median", "count"] = "mean",
    where: str | pl.Expr | None = None,
) -> AdamNamespace:
    """
    Compute a summary statistic per group and append the results as new records.

    *set_values_to*: column → value mapping applied to every new record
    (e.g. ``{"PARAMCD": "AVGBP", "DTYPE": "AVERAGE"}``).

    *stat*: ``"mean"`` (default), ``"sum"``, ``"min"``, ``"max"``, ``"median"``,
    ``"count"``. A group with only null values gives null for every stat
    except ``"count"``, which gives 0, as SAS ``SUM()`` and PROC MEANS.

    *where*: filter on the source records of the summary. The rows of the
    dataset are all kept. A second call in one chain reads the rows that
    the first call added: give ``where=pl.col("DTYPE").is_null()`` to
    summarise only collected records. When *where* is None and the source
    holds a non-null DTYPE, the verb warns.

    Materialises the current pipeline before concatenation.

    Examples:
        Compute mean AVAL per subject and parameter::

            advs = (
                vs_raw.adam
                .derive_summary_records(
                    by=["USUBJID", "PARAMCD"],
                    analysis_var="AVAL",
                    set_values_to={"DTYPE": "AVERAGE"},
                    stat="mean",
                )
                .to_frame()
            )
    """
    stat_lower = stat.lower()
    agg_map = {
        "mean": pl.col(analysis_var).mean(),
        "sum": pl.when(pl.col(analysis_var).count() > 0).then(pl.col(analysis_var).sum()),
        "min": pl.col(analysis_var).min(),
        "max": pl.col(analysis_var).max(),
        "median": pl.col(analysis_var).median(),
        "count": pl.col(analysis_var).count().cast(pl.Float64),
    }
    if stat_lower not in agg_map:
        raise DerivationError(f"Unknown stat '{stat}'. Supported: {', '.join(agg_map)}.")

    df = self.to_frame()
    source = df
    if where is not None:
        from fleet.sdtm.utils import parse_expression

        source = df.filter(where if isinstance(where, pl.Expr) else parse_expression(where))
    elif "DTYPE" in df.columns and df.get_column("DTYPE").is_not_null().any():
        warnings.warn(
            "derive_summary_records(): the source holds records with a non-null DTYPE, "
            "and they enter the summary. Give where=pl.col('DTYPE').is_null() to "
            "summarise only collected records.",
            UserWarning,
            stacklevel=2,
        )
    summary = source.group_by(by, maintain_order=True).agg(
        agg_map[stat_lower].alias(analysis_var)
    )

    # Apply constant values to the summary rows
    for col_name, col_val in set_values_to.items():
        summary = summary.with_columns(pl.lit(col_val).alias(col_name))

    # Align schemas before concat: add missing columns as null in both directions
    for c in df.columns:
        if c not in summary.columns:
            summary = summary.with_columns(pl.lit(None).cast(df.schema[c]).alias(c))
    for c in summary.columns:
        if c not in df.columns:
            df = df.with_columns(pl.lit(None).cast(summary.schema[c]).alias(c))

    col_order = df.columns
    summary = summary.select(col_order)

    combined = pl.concat([df, summary], how="vertical_relaxed")
    from fleet.core.lineage import record_row_step

    return record_row_step(self._materialise_then(combined), "derive_summary_records", {})

derive_locf_records

derive_locf_records(
    *,
    dataset_ref,
    by,
    order_by,
    analysis_var="AVAL",
    imputation="add",
    keep_vars=None
)

Add LOCF records for missed visits and for a null analysis_var.

For each by group, every row of dataset_ref (the expected visits) that has no record with a non-null analysis_var gets a value carried forward from the previous record, sorted by by and order_by. Each imputed record has DTYPE "LOCF"; an existing DTYPE on the other records is kept. A group with no earlier value keeps a null value.

Parameters:

Name Type Description Default
dataset_ref DataFrame

Expected observations, for example AVISIT and AVISITN, or PARAMCD, AVISIT and AVISITN. Add USUBJID for a per-subject list. Each of its columns must be in the dataset.

required
by list[str]

Group columns, for example ["STUDYID", "USUBJID", "PARAMCD"].

required
order_by str | list[str]

Sort column(s) within a group. The first one must be in dataset_ref, so that a new record has a sort value.

required
analysis_var str

Column to carry forward (default "AVAL").

'AVAL'
imputation Literal['add', 'update', 'update_add']

"add" (default, as admiral) keeps each record with a null value and adds an imputed record. "update" puts the value on that record. "update_add" does both.

'add'
keep_vars list[str] | None

Other columns to carry forward, for example PARAMN. A new record has values only in by, dataset_ref, analysis_var, keep_vars and DTYPE; other columns are null.

None

Returns:

Name Type Description
AdamNamespace AdamNamespace

The namespace with the LOCF records; call .to_frame() to materialise.

Raises:

Type Description
DerivationError

On an unknown imputation, a missing column, a first order_by column that is not in dataset_ref, or a null order_by value on a record to sort.

Examples:

Add WEEK 24 by LOCF for each subject and parameter::

visits = pl.DataFrame(
    {"AVISIT": ["BASELINE", "WEEK 8", "WEEK 16", "WEEK 24"],
     "AVISITN": [0, 8, 16, 24]}
)
adqs = (
    qs_raw.adam
    .derive_locf_records(
        dataset_ref=visits,
        by=["STUDYID", "USUBJID", "PARAMCD"],
        order_by=["AVISITN"],
        keep_vars=["PARAM"],
    )
    .to_frame()
)
References

ADaMIG v1.3 section 4.4 (BDS): DTYPE must be populated on a record whose AVAL is imputed; "LOCF" is in CDISC CT codelist DTYPE (C81224). admiral derive_locf_records (pharmaverse) defines the three imputation modes. ADR-0029.

Source code in src/fleet/adam/namespace.py
def derive_locf_records(
    self,
    *,
    dataset_ref: pl.DataFrame,
    by: list[str],
    order_by: str | list[str],
    analysis_var: str = "AVAL",
    imputation: Literal["add", "update", "update_add"] = "add",
    keep_vars: list[str] | None = None,
) -> AdamNamespace:
    """Add LOCF records for missed visits and for a null *analysis_var*.

    For each *by* group, every row of *dataset_ref* (the expected visits)
    that has no record with a non-null *analysis_var* gets a value carried
    forward from the previous record, sorted by *by* and *order_by*. Each
    imputed record has DTYPE ``"LOCF"``; an existing DTYPE on the other
    records is kept. A group with no earlier value keeps a null value.

    Args:
        dataset_ref: Expected observations, for example AVISIT and AVISITN,
            or PARAMCD, AVISIT and AVISITN. Add USUBJID for a per-subject
            list. Each of its columns must be in the dataset.
        by: Group columns, for example ``["STUDYID", "USUBJID", "PARAMCD"]``.
        order_by: Sort column(s) within a group. The first one must be in
            *dataset_ref*, so that a new record has a sort value.
        analysis_var: Column to carry forward (default ``"AVAL"``).
        imputation: ``"add"`` (default, as admiral) keeps each record with a
            null value and adds an imputed record. ``"update"`` puts the
            value on that record. ``"update_add"`` does both.
        keep_vars: Other columns to carry forward, for example PARAMN.
            A new record has values only in *by*, *dataset_ref*,
            *analysis_var*, *keep_vars* and DTYPE; other columns are null.

    Returns:
        AdamNamespace: The namespace with the LOCF records; call
            ``.to_frame()`` to materialise.

    Raises:
        DerivationError: On an unknown *imputation*, a missing column, a
            first *order_by* column that is not in *dataset_ref*, or a null
            *order_by* value on a record to sort.

    Examples:
        Add WEEK 24 by LOCF for each subject and parameter::

            visits = pl.DataFrame(
                {"AVISIT": ["BASELINE", "WEEK 8", "WEEK 16", "WEEK 24"],
                 "AVISITN": [0, 8, 16, 24]}
            )
            adqs = (
                qs_raw.adam
                .derive_locf_records(
                    dataset_ref=visits,
                    by=["STUDYID", "USUBJID", "PARAMCD"],
                    order_by=["AVISITN"],
                    keep_vars=["PARAM"],
                )
                .to_frame()
            )

    References:
        ADaMIG v1.3 section 4.4 (BDS): DTYPE must be populated on a record
        whose AVAL is imputed; "LOCF" is in CDISC CT codelist DTYPE (C81224).
        admiral ``derive_locf_records`` (pharmaverse) defines the three
        imputation modes. ADR-0029.
    """
    order = [order_by] if isinstance(order_by, str) else list(order_by)
    keep = list(keep_vars or [])
    if imputation not in ("add", "update", "update_add"):
        raise DerivationError(
            f"derive_locf_records(): imputation={imputation!r} is not supported. "
            "Choose 'add', 'update' or 'update_add'."
        )
    if not order:
        raise DerivationError("derive_locf_records(): order_by needs at least one column.")
    ref_cols = dataset_ref.columns
    if order[0] not in ref_cols:
        raise DerivationError(
            f"derive_locf_records(): the first order_by column {order[0]!r} is not in "
            f"dataset_ref (columns {ref_cols}). A new record would have no sort value. "
            "Sort by a visit column of dataset_ref, for example order_by=['AVISITN']."
        )
    df = self.to_frame()
    needed = dict.fromkeys([*by, analysis_var, *order, *keep, *ref_cols])
    missing = [c for c in needed if c not in df.columns]
    if missing:
        raise DerivationError(f"derive_locf_records(): column(s) {missing} not in the dataset.")

    ref = dataset_ref.cast({c: df.schema[c] for c in ref_cols})
    ids = df.select([c for c in by if c not in ref_cols]).unique(maintain_order=True)
    expected = ids.join(ref, how="cross") if ids.width else ref
    exp_by = list(dict.fromkeys([*by, *ref_cols]))

    is_null = pl.col(analysis_var).is_null()
    fill_base = df.filter(~is_null) if imputation == "add" else df
    to_add = expected.join(fill_base.select(exp_by), on=exp_by, how="anti", nulls_equal=True)
    stacked = pl.concat([fill_base, to_add], how="diagonal_relaxed")
    dtype = pl.when(is_null).then(pl.lit("LOCF"))
    if "DTYPE" in df.columns:
        dtype = dtype.otherwise(pl.col("DTYPE"))
    stacked = stacked.with_columns(dtype.alias("DTYPE"))

    n_null = stacked.select(pl.any_horizontal(pl.col(order).is_null()).sum()).item()
    if n_null:
        raise DerivationError(
            f"derive_locf_records(): {n_null} record(s) have a null value in order_by "
            f"{order}, so their place in the visit order is unknown."
        )
    filled = stacked.sort([*by, *order], maintain_order=True).with_columns(
        pl.col([analysis_var, *keep]).forward_fill().over(by)
    )
    if imputation != "update":
        filled = pl.concat([filled, df.filter(is_null)], how="diagonal_relaxed")
    from fleet.core.lineage import record_row_step

    new = self._materialise_then(filled.select(list(dict.fromkeys([*df.columns, "DTYPE"]))))
    return record_row_step(new, "derive_locf_records", {})

derive_param

derive_param(
    *,
    by=None,
    set_values_to,
    parameter_filter,
    analysis_value,
    from_dataset=None,
    where=None
)

Derive a new parameter (e.g. BMI) from existing records and append the computed rows to the dataset.

parameter_filter: {alias: PARAMCD} pairs identifying the source records to pivot on (e.g. {"WEIGHT": "WEIGHT", "HEIGHT": "HEIGHT"}). Each key is a local alias; the value is the PARAMCD it matches. Every source parameter must be unique per by group — duplicates raise instead of silently multiplying the derived rows.

analysis_value: a Polars expression (or YAML-friendly string) referencing the aliases to compute the new AVAL (e.g. pl.col("WEIGHT") / (pl.col("HEIGHT")/100)**2).

set_values_to: constant columns on the new rows — including the parameter-level identifiers PARAM, PARAMN, PARCATy / PARCATyN, and DTYPE (e.g. {"PARAMCD": "BMI", "PARAM": "Body Mass Index", "PARAMN": 3, "PARCAT1": "ANTHRO"}). Columns that don't exist yet are added to the dataset. The new PARAMCD must not already exist in the dataset: appending under an existing code would break the PARAMCD ↔ PARAM/PARAMN one-to-one mapping that ADaM conformance checks enforce.

from_dataset: optional BDS-shaped frame (PARAMCD + AVAL) to pivot the source parameters from — derive into this dataset from another one (e.g. compute a param in ADVS from ADLB rows). Defaults to the current pipeline frame.

where: optional filter applied to the source records before the pivot (e.g. restrict to ANL01FL == "Y" or baseline rows) — the current dataset's rows are never dropped.

A new AVAL that is infinite or NaN (for example a division by zero) becomes null, with a warning that gives the count, as SAS gives a missing value.

Materialises the pipeline before appending.

Examples:

Derive BMI as a new PARAMCD from WEIGHT and HEIGHT::

advs = (
    vs_raw.adam
    .derive_param(
        by=["USUBJID", "ADT"],
        set_values_to={"PARAMCD": "BMI",
                       "PARAM": "Body Mass Index"},
        parameter_filter={"WEIGHT": "WEIGHT",
                          "HEIGHT": "HEIGHT"},
        analysis_value=(
            pl.col("WEIGHT") / (pl.col("HEIGHT") / 100) ** 2
        ),
    )
    .to_frame()
)

Add a parameter computed from ANOTHER dataset's records::

advs = (
    advs.adam
    .derive_param(
        by=["USUBJID", "AVISIT"],
        set_values_to={"PARAMCD": "BSCRCL",
                       "PARAM": "Creatinine Clearance"},
        parameter_filter={"CREAT": "CREAT"},
        analysis_value='pl.col("CREAT") * 1.1',
        from_dataset=adlb,
        where='pl.col("ANL01FL") == "Y"',
    )
    .to_frame()
)
Source code in src/fleet/adam/namespace.py
def derive_param(
    self,
    *,
    by: list[str] | None = None,
    set_values_to: dict[str, Any],
    parameter_filter: dict[str, str],
    analysis_value: pl.Expr | str,
    from_dataset: pl.DataFrame | None = None,
    where: str | pl.Expr | None = None,
) -> AdamNamespace:
    """
    Derive a new parameter (e.g. BMI) from existing records and append
    the computed rows to the dataset.

    *parameter_filter*: ``{alias: PARAMCD}`` pairs identifying the source
    records to pivot on (e.g. ``{"WEIGHT": "WEIGHT", "HEIGHT": "HEIGHT"}``).
    Each key is a local alias; the value is the ``PARAMCD`` it matches.
    Every source parameter must be unique per *by* group — duplicates
    raise instead of silently multiplying the derived rows.

    *analysis_value*: a Polars expression (or YAML-friendly string)
    referencing the aliases to compute the new AVAL
    (e.g. ``pl.col("WEIGHT") / (pl.col("HEIGHT")/100)**2``).

    *set_values_to*: constant columns on the new rows — including the
    parameter-level identifiers ``PARAM``, ``PARAMN``, ``PARCATy`` /
    ``PARCATyN``, and ``DTYPE`` (e.g. ``{"PARAMCD": "BMI",
    "PARAM": "Body Mass Index", "PARAMN": 3, "PARCAT1": "ANTHRO"}``).
    Columns that don't exist yet are added to the dataset.  The new
    ``PARAMCD`` must not already exist in the dataset: appending under
    an existing code would break the PARAMCD ↔ PARAM/PARAMN one-to-one
    mapping that ADaM conformance checks enforce.

    *from_dataset*: optional BDS-shaped frame (``PARAMCD`` + ``AVAL``)
    to pivot the source parameters from — derive into this dataset
    **from another one** (e.g. compute a param in ADVS from ADLB rows).
    Defaults to the current pipeline frame.

    *where*: optional filter applied to the source records before the
    pivot (e.g. restrict to ``ANL01FL == "Y"`` or baseline rows) —
    the current dataset's rows are never dropped.

    A new AVAL that is infinite or NaN (for example a division by zero)
    becomes null, with a warning that gives the count, as SAS gives a
    missing value.

    Materialises the pipeline before appending.

    Examples:
        Derive BMI as a new PARAMCD from WEIGHT and HEIGHT::

            advs = (
                vs_raw.adam
                .derive_param(
                    by=["USUBJID", "ADT"],
                    set_values_to={"PARAMCD": "BMI",
                                   "PARAM": "Body Mass Index"},
                    parameter_filter={"WEIGHT": "WEIGHT",
                                      "HEIGHT": "HEIGHT"},
                    analysis_value=(
                        pl.col("WEIGHT") / (pl.col("HEIGHT") / 100) ** 2
                    ),
                )
                .to_frame()
            )

        Add a parameter computed from ANOTHER dataset's records::

            advs = (
                advs.adam
                .derive_param(
                    by=["USUBJID", "AVISIT"],
                    set_values_to={"PARAMCD": "BSCRCL",
                                   "PARAM": "Creatinine Clearance"},
                    parameter_filter={"CREAT": "CREAT"},
                    analysis_value='pl.col("CREAT") * 1.1',
                    from_dataset=adlb,
                    where='pl.col("ANL01FL") == "Y"',
                )
                .to_frame()
            )
    """
    from fleet.sdtm.utils import parse_expression

    if not parameter_filter:
        raise DerivationError("derive_param() requires at least one parameter_filter entry.")

    grps = by or ["USUBJID"]
    df = self.to_frame()

    # Guard the BDS one-to-one parameter mapping: appending rows under an
    # already-used PARAMCD would mix parameter-level metadata (PARAM,
    # PARAMN, PARCATy) for one code — a guaranteed conformance finding.
    new_paramcd = set_values_to.get("PARAMCD")
    if (
        isinstance(new_paramcd, str)
        and "PARAMCD" in df.columns
        and (df.get_column("PARAMCD") == new_paramcd).any()
    ):
        raise DerivationError(
            f"derive_param(): PARAMCD '{new_paramcd}' already exists in the dataset — "
            "appending would break the PARAMCD ↔ PARAM/PARAMN one-to-one mapping. "
            "Choose a new PARAMCD, or remove the existing rows first."
        )

    source = from_dataset if from_dataset is not None else df
    missing = [c for c in ("PARAMCD", "AVAL") if c not in source.columns]
    if missing:
        origin = "from_dataset" if from_dataset is not None else "the current frame"
        raise DerivationError(
            f"derive_param(): {origin} is missing required column(s) {missing} — "
            "the source must be BDS-shaped (PARAMCD + AVAL)."
        )
    if where is not None:
        where_expr = where if isinstance(where, pl.Expr) else parse_expression(str(where))
        source = source.filter(where_expr)

    # Pivot: for each alias in parameter_filter, get AVAL as that alias
    pivoted_parts = []
    for alias, paramcd_val in parameter_filter.items():
        part = source.filter(pl.col("PARAMCD") == paramcd_val).select(
            grps + [pl.col("AVAL").alias(alias)]
        )
        dup = part.group_by(grps).len().filter(pl.col("len") > 1)
        if dup.height:
            raise DerivationError(
                f"derive_param(): PARAMCD '{paramcd_val}' has multiple records for "
                f"{dup.height} {grps} group(s) (e.g. {dup.select(grps).row(0)}). "
                "The derived rows would multiply — deduplicate the source, extend "
                "by=, or narrow the records with where=."
            )
        pivoted_parts.append(part)

    # Join all pivoted parts on the by keys
    joined = pivoted_parts[0]
    for part in pivoted_parts[1:]:
        joined = joined.join(part, on=grps, how="inner", nulls_equal=True)

    # Compute the new AVAL
    aval_expr = (
        analysis_value
        if isinstance(analysis_value, pl.Expr)
        else parse_expression(str(analysis_value))
    )
    new_rows = joined.with_columns(aval_expr.alias("AVAL")).select(grps + ["AVAL"])
    if new_rows.schema["AVAL"].is_float():
        non_finite = new_rows.select((~pl.col("AVAL").is_finite()).sum()).item()
        if non_finite:
            import warnings

            warnings.warn(
                f"derive_param(): {non_finite} new AVAL value(s) are infinite or NaN "
                "(for example a division by zero) and are set to null.",
                stacklevel=2,
            )
            new_rows = new_rows.with_columns(
                pl.when(pl.col("AVAL").is_finite()).then(pl.col("AVAL")).alias("AVAL")
            )

    # Apply set_values_to constants
    for col_name, col_val in set_values_to.items():
        new_rows = new_rows.with_columns(pl.lit(col_val).alias(col_name))

    # Align schemas both ways: new set_values_to columns (e.g. DTYPE)
    # are added to the base frame instead of being silently dropped.
    for c in df.columns:
        if c not in new_rows.columns:
            new_rows = new_rows.with_columns(pl.lit(None).cast(df.schema[c]).alias(c))
    for c in new_rows.columns:
        if c not in df.columns:
            df = df.with_columns(pl.lit(None).cast(new_rows.schema[c]).alias(c))
    new_rows = new_rows.select(df.columns)

    combined = pl.concat([df, new_rows], how="vertical_relaxed")
    from fleet.core.lineage import record_row_step

    return record_row_step(self._materialise_then(combined), "derive_param", {})

atoxgr

atoxgr(
    target,
    *,
    system="ctcae_v5",
    direction,
    term_var,
    unit_var,
    signif_dig=15,
    indicators=None
)

Derive a toxicity grade, as admiral derive_var_atoxgr_dir.

Materialises the pipeline and grades every row whose term has criteria in direction. The bundled criteria are generated from the admiral metadata (scripts/regen_grading_criteria.R), so each term follows the admiral case_when: for example, a null BNRIND counts as not abnormal and the ULN criteria apply, and CTCAE v5 INR takes the worse of the absolute and the baseline cut-offs (admiral COMMENT: worst case, assume on anticoagulation). The term and the unit match without case. A row with another unit, a null unit, no criteria or a population no criteria cover gets a null grade. Every row stays, in its order.

The ctcae_*, daids systems hold SI cut-offs (hemoglobin in g/L); the *_uscv systems hold US conventional units (g/dL). A row whose unit is not a unit of the criteria gets null, with a warning that gives the count.

Parameters:

Name Type Description Default
target str

Name of the output grade column (e.g. "ATOXGRL").

required
system str

Grading system name (e.g. "ctcae_v5", "daids") or path to a custom JSON criteria file (schema version 2).

'ctcae_v5'
direction Literal['L', 'H']

"L" (low) or "H" (high).

required
term_var str

Column holding the lab-test / term name.

required
unit_var str

Column holding the unit of measure (e.g. "AVALU"). Required, as admiral: each row is graded with the cut-offs of its own unit.

required
signif_dig int

Significant digits for comparison (default 15, as admiral signif_digits).

15
indicators dict[str, list[str]] | None

Values of the indicator params of the criteria (default {"high_indicator": ["HIGH", "H"], "low_indicator": ["LOW", "L"]}).

None

Returns:

Name Type Description
AdamNamespace AdamNamespace

A fresh namespace wrapping the graded frame.

Raises:

Type Description
DerivationError

When direction is not "L" or "H", or a needed column is missing.

References

admiral derive_var_atoxgr_dir and the metadata tables atoxgr_criteria_ctcv4/5/6 and atoxgr_criteria_daids (SI and USCV), admiral 1.4.1, where get_unit_expr is required; NCI CTCAE v4.03, v5.0, v6.0; DAIDS grading table v2.1. ADR-0028.

Examples:

Grade low-direction anemia using CTCAE v5::

adlb = (
    lb_raw.adam
    .atoxgr("ATOXGRL", system="ctcae_v5",
            direction="L", term_var="PARAMCD",
            unit_var="AVALU")
    .to_frame()
)
Source code in src/fleet/adam/namespace.py
def atoxgr(
    self,
    target: str,
    *,
    system: str = "ctcae_v5",
    direction: Literal["L", "H"],
    term_var: str,
    unit_var: str,
    signif_dig: int = 15,
    indicators: dict[str, list[str]] | None = None,
) -> AdamNamespace:
    """Derive a toxicity grade, as admiral ``derive_var_atoxgr_dir``.

    Materialises the pipeline and grades every row whose term has
    criteria in *direction*.  The bundled criteria are generated from the
    admiral metadata (``scripts/regen_grading_criteria.R``), so each term
    follows the admiral ``case_when``: for example, a null ``BNRIND``
    counts as not abnormal and the ULN criteria apply, and CTCAE v5 INR
    takes the worse of the absolute and the baseline cut-offs (admiral
    COMMENT: worst case, assume on anticoagulation).  The term and the
    unit match without case.  A row with another unit, a null unit, no
    criteria or a population no criteria cover gets a null grade.  Every
    row stays, in its order.

    The ``ctcae_*``, ``daids`` systems hold SI cut-offs (hemoglobin in
    g/L); the ``*_uscv`` systems hold US conventional units (g/dL).  A
    row whose unit is not a unit of the criteria gets null, with a
    warning that gives the count.

    Args:
        target: Name of the output grade column (e.g. ``"ATOXGRL"``).
        system: Grading system name (e.g. ``"ctcae_v5"``, ``"daids"``)
            or path to a custom JSON criteria file (schema version 2).
        direction: ``"L"`` (low) or ``"H"`` (high).
        term_var: Column holding the lab-test / term name.
        unit_var: Column holding the unit of measure (e.g. ``"AVALU"``).
            Required, as admiral: each row is graded with the cut-offs
            of its own unit.
        signif_dig: Significant digits for comparison (default 15, as
            admiral ``signif_digits``).
        indicators: Values of the indicator params of the criteria
            (default ``{"high_indicator": ["HIGH", "H"],
            "low_indicator": ["LOW", "L"]}``).

    Returns:
        AdamNamespace: A fresh namespace wrapping the graded frame.

    Raises:
        DerivationError: When *direction* is not ``"L"`` or ``"H"``, or a
            needed column is missing.

    References:
        admiral ``derive_var_atoxgr_dir`` and the metadata tables
        ``atoxgr_criteria_ctcv4/5/6`` and ``atoxgr_criteria_daids``
        (SI and USCV), admiral 1.4.1, where ``get_unit_expr`` is required;
        NCI CTCAE v4.03, v5.0, v6.0; DAIDS grading table v2.1. ADR-0028.

    Examples:
        Grade low-direction anemia using CTCAE v5::

            adlb = (
                lb_raw.adam
                .atoxgr("ATOXGRL", system="ctcae_v5",
                        direction="L", term_var="PARAMCD",
                        unit_var="AVALU")
                .to_frame()
            )
    """
    from .grading._compiler import grade_dataset
    from .grading._registry import load_criteria

    criteria = load_criteria(system)
    df = self.to_frame()
    # Provide standard BNRIND defaults when no indicators are given.
    if indicators is None:
        indicators = {
            "high_indicator": ["HIGH", "H"],
            "low_indicator": ["LOW", "L"],
        }
    graded = grade_dataset(
        df,
        criteria,
        target=target,
        direction=direction,
        term_var=term_var,
        unit_var=unit_var,
        signif_dig=signif_dig,
        indicators=indicators,
    )
    return self._materialise_then(graded)

combine_grades

combine_grades(
    target="ATOXGR",
    *,
    low_var="ATOXGRL",
    high_var="ATOXGRH",
    low_desc_var="ATOXDSCL",
    high_desc_var="ATOXDSCH"
)

Combine low and high toxicity grades into a signed grade, as admiral.

Low grades are prefixed with "-"; high grades are kept as-is. Both null → null. "0" only when each side is "0" or its description is null (no criteria in that direction). Low "0" with a null high grade and a present high description gives null: the high grade is unknown (for example ANRHI is missing).

Parameters:

Name Type Description Default
target str

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

'ATOXGR'
low_var str

Low-direction grade column (default "ATOXGRL").

'ATOXGRL'
high_var str

High-direction grade column (default "ATOXGRH").

'ATOXGRH'
low_desc_var str

Low-grade term description column (default "ATOXDSCL"). Required in the data; for a one-direction study, add it as a null column.

'ATOXDSCL'
high_desc_var str

High-grade term description column (default "ATOXDSCH"). Required in the data, as low_desc_var.

'ATOXDSCH'

Returns:

Name Type Description
AdamNamespace AdamNamespace

The namespace with target appended.

Raises:

Type Description
DerivationError

When a grade or description column is missing.

References

admiral derive_var_atoxgr (admiral 1.4.1): lowgrade == "0" | is.na(lowdesc) and the same for high give "0". ADR-0028.

Examples:

Combine low/high grades into ATOXGR::

adlb = (
    lb_raw.adam
    .atoxgr("ATOXGRL", system="ctcae_v5", direction="L",
            term_var="ATOXDSCL", unit_var="AVALU")
    .atoxgr("ATOXGRH", system="ctcae_v5", direction="H",
            term_var="ATOXDSCH", unit_var="AVALU")
    .combine_grades("ATOXGR")
    .to_frame()
)
Source code in src/fleet/adam/namespace.py
def combine_grades(
    self,
    target: str = "ATOXGR",
    *,
    low_var: str = "ATOXGRL",
    high_var: str = "ATOXGRH",
    low_desc_var: str = "ATOXDSCL",
    high_desc_var: str = "ATOXDSCH",
) -> AdamNamespace:
    """Combine low and high toxicity grades into a signed grade, as admiral.

    Low grades are prefixed with ``"-"``; high grades are kept as-is.
    Both null → null.  ``"0"`` only when each side is ``"0"`` or its
    description is null (no criteria in that direction).  Low ``"0"``
    with a null high grade and a present high description gives null:
    the high grade is unknown (for example ANRHI is missing).

    Args:
        target: Name of the output column (default ``"ATOXGR"``).
        low_var: Low-direction grade column (default ``"ATOXGRL"``).
        high_var: High-direction grade column (default ``"ATOXGRH"``).
        low_desc_var: Low-grade term description column (default
            ``"ATOXDSCL"``).  Required in the data; for a
            one-direction study, add it as a null column.
        high_desc_var: High-grade term description column (default
            ``"ATOXDSCH"``).  Required in the data, as *low_desc_var*.

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

    Raises:
        DerivationError: When a grade or description column is missing.

    References:
        admiral ``derive_var_atoxgr`` (admiral 1.4.1): ``lowgrade == "0" |
        is.na(lowdesc)`` and the same for high give "0". ADR-0028.

    Examples:
        Combine low/high grades into ATOXGR::

            adlb = (
                lb_raw.adam
                .atoxgr("ATOXGRL", system="ctcae_v5", direction="L",
                        term_var="ATOXDSCL", unit_var="AVALU")
                .atoxgr("ATOXGRH", system="ctcae_v5", direction="H",
                        term_var="ATOXDSCH", unit_var="AVALU")
                .combine_grades("ATOXGR")
                .to_frame()
            )
    """
    from .grading._compiler import combine_grades_expr

    names = self._lazy.collect_schema().names()
    missing = [c for c in (low_var, high_var, low_desc_var, high_desc_var) if c not in names]
    if missing:
        raise DerivationError(
            f"combine_grades('{target}'): column(s) {missing} are missing. The "
            "descriptions tell a direction with no criteria from an unknown grade; "
            "for a one-direction study add the other description as a null column."
        )
    return self._chain(
        combine_grades_expr(
            low_var,
            high_var,
            low_desc_var=low_desc_var,
            high_desc_var=high_desc_var,
        ).alias(target),
        verb="combine_grades",
    )

transform

transform(fn, *, label=None)

Apply an arbitrary (pl.DataFrame) -> pl.DataFrame function.

The pending expression pipeline is materialised before the function is called, so the function always receives a fully committed frame.

Parameters:

Name Type Description Default
fn str | Callable[[DataFrame], DataFrame]

Either a callable directly, or the registered name of a transform (see :func:fleet.adam.transforms.register_transform).

required
label str | None

Optional cosmetic label for documentation/lineage; has no effect on the output.

None

Raises:

Type Description
KeyError

If fn is a string that has not been registered.

TypeError

If fn is neither a callable nor a string, or if the function does not return a pl.DataFrame.

Returns:

Name Type Description
AdamNamespace AdamNamespace

A fresh namespace wrapping the transformed frame.

Examples:

Register and apply a custom age-group transform::

from fleet.adam.transforms import register_transform

@register_transform("add_agegr1")
def add_agegr1(df):
    return df.with_columns(
        pl.when(pl.col("AGE") < 65).then(pl.lit("<65"))
          .otherwise(pl.lit(">=65")).alias("AGEGR1")
    )

adsl = (
    dm_raw.adam
    .assign("STUDYID", value="S01")
    .transform("add_agegr1")
    .to_frame()
)
Source code in src/fleet/adam/namespace.py
def transform(
    self,
    fn: str | Callable[[pl.DataFrame], pl.DataFrame],
    *,
    label: str | None = None,  # noqa: ARG002  — cosmetic, intentionally unused
) -> AdamNamespace:
    """
    Apply an arbitrary ``(pl.DataFrame) -> pl.DataFrame`` function.

    The pending expression pipeline is materialised before the function
    is called, so the function always receives a fully committed frame.

    Args:
        fn: Either a callable directly, or the registered name of a
            transform (see :func:`fleet.adam.transforms.register_transform`).
        label: Optional cosmetic label for documentation/lineage; has no
            effect on the output.

    Raises:
        KeyError: If *fn* is a string that has not been registered.
        TypeError: If *fn* is neither a callable nor a string, or if the
            function does not return a ``pl.DataFrame``.

    Returns:
        AdamNamespace: A fresh namespace wrapping the transformed frame.

    Examples:
        Register and apply a custom age-group transform::

            from fleet.adam.transforms import register_transform

            @register_transform("add_agegr1")
            def add_agegr1(df):
                return df.with_columns(
                    pl.when(pl.col("AGE") < 65).then(pl.lit("<65"))
                      .otherwise(pl.lit(">=65")).alias("AGEGR1")
                )

            adsl = (
                dm_raw.adam
                .assign("STUDYID", value="S01")
                .transform("add_agegr1")
                .to_frame()
            )
    """
    from .transforms import get_transform

    if isinstance(fn, str):
        fn = get_transform(fn)  # raises KeyError if not found
    elif not callable(fn):
        raise VerbUsageError(
            f"transform() expects a callable or a registered name string, "
            f"got {type(fn).__name__!r}."
        )

    # Materialise pending expressions so the function sees a full frame.
    committed = self.to_frame()
    result = fn(committed)

    if not isinstance(result, pl.DataFrame):
        raise VerbUsageError(
            f"Transform function must return a polars DataFrame, got {type(result).__name__!r}."
        )

    return self._materialise_then(result)

options: show_root_heading: true heading_level: 2 members_order: source inherited_members: true filters: ["!^_"]

Shared verbs (all ADaM namespaces)

These verbs are available on every ADaM namespace (df.adam, df.adam.adsl, df.adam.occds, …).

fleet.adam.SharedADaMVerbsMixin

Bases: SharedVerbsMixin, PinMixin, FlagCriterionMixin

Base mixin providing the shared verbs and chaining infrastructure.

Inherits algorithmic and infrastructure verbs from SharedVerbsMixin (derivation, duration, study_day, seq, validate, select, inspect, explain, to_frame, to_dataset_json, write_parquet, _chain, _materialise_then).

Concrete namespace classes inherit from this mixin. The _chain and _materialise_then helpers use copy.copy(self) so the returned instance stays the correct sub-type for continued chaining.

Required instance attribute ~~~~~~~~~~~~~~~~~~~~~~~~~~~ _lazy: pl.LazyFrame — set by __init__.

Source code in src/fleet/adam/_mixins.py
 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
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
class SharedADaMVerbsMixin(SharedVerbsMixin, PinMixin, FlagCriterionMixin):
    """Base mixin providing the shared verbs and chaining infrastructure.

    Inherits algorithmic and infrastructure verbs from ``SharedVerbsMixin``
    (derivation, duration, study_day, seq, validate, select, inspect,
    explain, to_frame, to_dataset_json, write_parquet, _chain,
    _materialise_then).

    Concrete namespace classes inherit from this mixin.  The ``_chain``
    and ``_materialise_then`` helpers use ``copy.copy(self)`` so the
    returned instance stays the correct sub-type for continued chaining.

    Required instance attribute
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    ``_lazy: pl.LazyFrame``  — set by ``__init__``.
    """

    _lazy: pl.LazyFrame

    _FK_RULES: dict[str, dict[str, str]] = {
        "USUBJID": {"pin": "ADSL", "ref_col": "USUBJID"},
    }

    # -- SharedVerbsMixin configuration for ADaM --
    _STUDY_DAY_REF_COL: str = "TRTSDT"
    _STUDY_DAY_REF_PIN: str = "ADSL"
    _SEQ_DEFAULT_GROUPS: list[str] = ["USUBJID"]
    _VALIDATE_STANDARD = "adam"

    # ------------------------------------------------------------------ #
    # Lifecycle                                                            #
    # ------------------------------------------------------------------ #

    def __init__(self, df: pl.DataFrame | pl.LazyFrame) -> None:
        self._lazy = df.lazy()
        self._root_lazy = self._lazy  # the start of the chain, for to_spec_yaml()
        self._domain: str | None = None
        self._pinned: dict[str, tuple[pl.DataFrame, list[str]]] = {}
        self._pin_lineage: list = []
        self._pending_fk_checks: list[tuple[str, str, str, str]] = []

    def __call__(self, domain: str) -> Self:
        """Return a copy of this namespace with *domain* set for CDISC lineage.

        Args:
            domain: CDISC domain code (e.g. ``"ADAE"``, ``"ADVS"``).

        Returns:
            Self: A shallow copy whose lineage records will carry *domain*.

        Examples:
            Tag an OCCDS pipeline as ADAE::

                adae = (
                    ae_with_trt.adam.occds("ADAE")
                    .source("USUBJID")
                    .treatment_emergent("TRTEMFL", start_date="ASTDT",
                                        end_date="AENDT", trtsdt="TRTSDT")
                    .to_frame()
                )
        """
        new = copy.copy(self)
        new._domain = domain
        return new

    # ------------------------------------------------------------------ #
    # Cross-domain: pin-powered verbs                                      #
    # ------------------------------------------------------------------ #

    def join_adsl(self, *cols: str) -> Self:
        """Pull columns from pinned ADSL into this pipeline.

        Performs a left join on the pinned join key, keeps only the
        requested columns, and records ``carry_forward`` lineage for
        each column.

        Args:
            *cols: Column names to carry forward from ADSL
                (e.g. ``"TRTSDT"``, ``"TRTEDT"``, ``"SAFFL"``).

        Returns:
            Self: The namespace with ADSL columns attached; call
                ``.to_frame()`` to materialise.

        Raises:
            LookupError: If ADSL is not pinned.
            DerivationError: If a column is not in ADSL (with a
                did-you-mean suggestion), is already in the pipeline, or
                ADSL has two different rows for one subject.

        References:
            ADR-0032 (docs/adr/0032-merge-reads-as-sas-merge-and-stops-on-a-clash.md).
            ADaMIG 1.3: ADSL holds one record per subject.

        Examples:
            Carry TRTSDT and SAFFL from ADSL into an ADAE pipeline::

                adae = (
                    ae_df.adam.occds("ADAE")
                    .pin("ADSL", adsl_df)
                    .source("USUBJID")
                    .join_adsl("TRTSDT", "TRTEDT", "SAFFL")
                    .to_frame()
                )
        """
        from fleet.core.lineage import record_pin_lineage

        adsl = self._require_pin("ADSL", "join_adsl")
        join_key = self._pin_join_key("ADSL")
        require_columns("join_adsl()", cols, adsl.columns, where="the pinned ADSL")
        refuse_shared_columns(
            "join_adsl()",
            self._lazy.collect_schema().names(),
            cols,
            join_key,
            hint="Drop the column from the pipeline first, or leave it out of join_adsl().",
        )
        ref_slim = refuse_repeated_keys(
            "join_adsl()",
            adsl.select(list(dict.fromkeys(join_key + list(cols)))),
            join_key,
            source="ADSL",
        )

        df = self._lazy.collect().join(ref_slim, on=join_key, how="left", nulls_equal=True)
        new = self._materialise_then(df)

        for col in cols:
            record_pin_lineage(
                new,
                target_col=col,
                verb="join_adsl",
                source_domain="ADSL",
                source_cols=[col],
                join_key=join_key,
                relationship="carry_forward",
            )
        return new

    # study_day is inherited from SharedVerbsMixin (one shared
    # implementation; `adsl=` / `dm=` are documented ref_df aliases).

    # ------------------------------------------------------------------ #
    # Shared verbs                                                         #
    # ------------------------------------------------------------------ #

    def source(self, *targets: str, from_col: str | None = None) -> Self:
        """Carry one or more source columns into the ADaM dataset.

        With a single name and ``from_col=``, copies *from_col* to the
        target (legacy 1:1 form — prefer ``assign(target, source=...)``).
        With multiple names, each column is carried through as-is::

            .source("STUDYID", "USUBJID", "AETERM")

        Args:
            *targets: Output ADaM variable name(s).  Without *from_col*
                each is an identity copy of the same-named input column.
            from_col: Name of the input column to copy from (single
                target only).  Defaults to the target name.

        Returns:
            Self: The namespace with the target(s) appended; call
                ``.to_frame()`` to materialise.

        Raises:
            DerivationError: When no target is given, or *from_col* is
                combined with more than one target.

        Examples:
            Carry the key variables through in one call::

                adae = (
                    ae_df.adam
                    .source("STUDYID", "USUBJID", "AEDECOD")
                    .to_frame()
                )
        """
        if not targets:
            raise DerivationError("source() requires at least one column name.")
        if from_col is not None:
            if len(targets) > 1:
                raise DerivationError(
                    "source(): from_col= applies to a single target — got "
                    f"{len(targets)} targets. Use assign(target, source=...) "
                    "for renames, or list the columns without from_col."
                )
            return self._chain(pl.col(from_col).alias(targets[0]), verb="source")
        exprs = [pl.col(t).alias(t) for t in targets]
        return self._chain(*exprs, verb="source")

    def recode(
        self,
        target: str,
        *,
        source: str,
        recode_map: dict[Any, Any],
        default: Any = None,
    ) -> Self:
        """Map values in *source* to recoded values in *target*.

        Unmapped values fall back to *default*.  The output type follows
        the map values and a literal *default*, ignoring ``None``: integers
        give an integer column, integers with floats a float column (ADaM
        ``*N`` variables such as ASEVN and AVISITN are Num), and text gives
        text.  A map that mixes kinds raises, so a typing slip cannot give a
        text ``*N`` variable.

        Args:
            target: Name of the output ADaM variable.
            source: Name of the input column containing coded values.
            recode_map: ``{old_value: new_value}`` mapping.
            default: Value for entries not present in *recode_map*.

        Returns:
            Self: The namespace with *target* appended; call ``.to_frame()``
                to materialise.

        Raises:
            DerivationError: When the map values and *default* mix kinds.

        Examples:
            Recode numeric sex to character::

                adsl = (
                    dm_df.adam.adsl
                    .recode("SEX", source="SEXN",
                            recode_map={1: "M", 2: "F"})
                    .to_frame()
                )

            Code severity to a number::

                adae = (
                    ae_df.adam.occds
                    .recode("ASEVN", source="ASEV",
                            recode_map={"MILD": 1, "MODERATE": 2, "SEVERE": 3})
                    .to_frame()
                )
        """
        default_expr = default if isinstance(default, pl.Expr) else pl.lit(default)
        if not recode_map:
            return self._chain(default_expr.alias(target), verb="recode")
        values = [*recode_map.values(), *([] if isinstance(default, pl.Expr) else [default])]
        kinds = {_value_kind(v) for v in values if v is not None}
        return_dtype: pl.DataType | None = None
        if kinds == {"int", "float"}:
            recode_map = {k: None if v is None else float(v) for k, v in recode_map.items()}
        elif len(kinds) > 1:
            raise DerivationError(
                f"recode('{target}'): the map values and default mix {sorted(kinds)}. "
                f"Give one kind, so {target} is numeric or text."
            )
        elif kinds != {"int"} and kinds != {"float"}:
            return_dtype = pl.String()
        expr = (
            pl.col(source)
            .replace_strict(recode_map, default=default_expr, return_dtype=return_dtype)
            .alias(target)
        )
        return self._chain(expr, verb="recode")

    # ------------------------------------------------------------------ #
    # pick — priority-ordered event selection across sources               #
    # ------------------------------------------------------------------ #

    def pick(
        self,
        targets: str | list[str],
        *,
        events: list[dict[str, Any]],
        by: list[str] | None = None,
        order: str | list[str] | None = None,
        mode: str = "first",
    ) -> Self:
        """Derive targets from one event per group, chosen across the events.

        Each event in the list defines a candidate source, a filter
        condition, and values to set when that event is selected.  Within
        each event's matching records, the event's *order* and *mode* (or
        the top-level ones) select one record.  Then one event wins:

        - with a top-level *order*, every event's record competes on that
          order and *mode*, as admiral ``derive_vars_extreme_event`` does:
          ``order=["LSTALVDT"], mode="last"`` gives the latest date over all
          sources.  A tie goes to the first listed event.
        - with no top-level *order*, the first listed event with a matching
          record wins (a priority cascade, as the admiral DTHCAUS template).

        This is Fleet's answer to multi-source derivations such as
        last-date-known-alive (LSTALVDT) or death cause (DTHCAUS).

        Event dict keys:

        - ``"when"`` (required): Boolean expression (``str | pl.Expr``)
          filtering which records qualify.
        - ``"set"`` (required): ``dict[str, str | pl.Expr | Any]`` mapping
          each target name to a column reference, expression, or literal.
          Column references use bare names (``"DTHDT"``); literals must be
          wrapped in ``pl.lit()``.
        - ``"source"`` (optional): External ``pl.DataFrame`` to scan for
          this event.  When omitted, the current pipeline frame is used.
        - ``"mode"`` (optional): Override the top-level *mode* for this
          event only (``"first"`` | ``"last"``).
        - ``"order"`` (optional): Override the top-level *order* for this
          event only.
        - ``"label"`` (optional): Documentation-only description.

        Args:
            targets: Target column name(s) to derive.
            events: List of event dicts.  List position breaks ties and,
                with no top-level *order*, decides the winner.
            by: Grouping columns (default ``["USUBJID"]``).
            order: Sort column(s).  Within an event they select the record;
                at top level they also select the event (see above).  An
                event with more than one matching record in a group needs
                an order (its own or the top-level one).  A missing order
                value loses in both modes.  Records that tie on the order
                keep their input order, so ``"last"`` takes the last tied
                record, as SAS ``LAST.``; a warning names a tie whose
                records set different values.
            mode: ``"first"`` or ``"last"`` — which record to select
                after sorting by *order* (default ``"first"``).

        Returns:
            Self: A fresh namespace with *targets* added; call
                ``.to_frame()`` to materialise.

        Raises:
            DerivationError: If *events* is empty, a required key is
                missing, an event contains an unknown key (with a
                did-you-mean suggestion), or an event with no order has
                more than one matching record in a group.  Also catchable
                as ``ValueError``.

        References:
            admiral ``derive_vars_extreme_event`` (``order`` is required)
            and SAS ``FIRST.``/``LAST.`` after PROC SORT EQUALS; ADR-0024.

        Examples:
            Derive last date known alive from death, AE, and treatment::

                adsl = (
                    dm.adam.adsl
                    .source("USUBJID")
                    .pick(
                        ["LSTALVDT", "DTHFL"],
                        events=[
                            {"when": pl.col("DTHDT").is_not_null(),
                             "set": {"LSTALVDT": "DTHDT", "DTHFL": pl.lit("Y")},
                             "source": adsl_df, "label": "Death date"},
                            {"when": pl.col("AEENDTC").is_not_null(),
                             "set": {"LSTALVDT": "AEENDTC", "DTHFL": pl.lit("N")},
                             "source": ae, "mode": "last", "order": ["AEENDTC"]},
                            {"when": pl.col("TRTEDT").is_not_null(),
                             "set": {"LSTALVDT": "TRTEDT", "DTHFL": pl.lit("N")},
                             "source": adsl_df},
                        ],
                        by=["USUBJID"],
                        order=["LSTALVDT"],
                        mode="last",
                    )
                    .to_frame()
                )

            Simple single-target with string conditions (YAML-friendly)::

                adsl = (
                    dm.adam.adsl
                    .pick(
                        "DTHCAUS",
                        events=[
                            {"when": 'pl.col("AEOUT") == "FATAL"',
                             "set": {"DTHCAUS": "AEDECOD"},
                             "source": ae, "order": ["AESTDTC", "AESEQ"]},
                            {"when": 'pl.col("DSDECOD") == "DEATH"',
                             "set": {"DTHCAUS": "DSTERM"},
                             "source": ds, "order": ["DSSTDTC", "DSSEQ"]},
                        ],
                        by=["USUBJID"],
                    )
                    .to_frame()
                )
        """
        from fleet.sdtm.utils import parse_expression

        if not events:
            raise DerivationError("pick() requires at least one event.")
        if mode not in ("first", "last"):
            raise DerivationError(
                f"pick() mode={mode!r} is not supported. Choose 'first' or 'last'."
            )

        target_list = [targets] if isinstance(targets, str) else list(targets)
        by_vars = by or ["USUBJID"]
        global_order: list[str] | None = (
            [order] if isinstance(order, str) else list(order) if order else None
        )

        df = self.to_frame()

        # Collect one candidate row per event per group.
        candidate_frames: list[pl.DataFrame] = []

        valid_event_keys = {"when", "set", "source", "mode", "order", "label"}
        for event_nr, event in enumerate(events):
            unknown = sorted(set(event) - valid_event_keys)
            if unknown:
                hints = []
                for key in unknown:
                    close = difflib.get_close_matches(str(key), sorted(valid_event_keys), n=1)
                    hints.append(f"'{key}'" + (f" (did you mean '{close[0]}'?)" if close else ""))
                raise DerivationError(
                    f"pick() event #{event_nr} contains unknown key(s): {', '.join(hints)}. "
                    f"Valid keys: {sorted(valid_event_keys)}."
                )
            if "when" not in event or "set" not in event:
                raise DerivationError(
                    f"Event #{event_nr} must contain 'when' and 'set' keys. "
                    f"Got keys: {list(event.keys())}"
                )

            # Resolve source frame
            source_df: pl.DataFrame = event.get("source", df)

            # Resolve condition
            when_raw = event["when"]
            when_expr: pl.Expr = (
                when_raw if isinstance(when_raw, pl.Expr) else parse_expression(str(when_raw))
            )

            # Filter candidates
            candidates = source_df.filter(when_expr)
            if candidates.is_empty():
                continue

            # Build set-values expressions
            set_exprs: list[pl.Expr] = []
            set_spec: dict[str, Any] = event["set"]
            for tgt in target_list:
                if tgt not in set_spec:
                    # Target not produced by this event → null placeholder
                    set_exprs.append(pl.lit(None).alias(tgt))
                    continue
                val = set_spec[tgt]
                if isinstance(val, pl.Expr):
                    set_exprs.append(val.alias(tgt))
                elif isinstance(val, str):
                    # String → parse as expression or column reference.
                    # parse_expression handles both: bare names ("AEENDTC")
                    # become pl.col("AEENDTC"); expression strings like
                    # 'pl.lit("Y")' are evaluated via sandboxed AST.
                    set_exprs.append(parse_expression(val).alias(tgt))
                else:
                    # Literal value
                    set_exprs.append(pl.lit(val).alias(tgt))

            # Apply set expressions + add event priority marker
            candidates = candidates.with_columns(
                *set_exprs,
                pl.lit(event_nr).cast(pl.UInt32).alias("__pick_event_nr__"),
            )

            # Resolve per-event mode/order
            evt_mode = event.get("mode", mode)
            if evt_mode not in ("first", "last"):
                raise DerivationError(
                    f"pick() event #{event_nr} mode={evt_mode!r} is not supported. "
                    "Choose 'first' or 'last'."
                )
            evt_order_raw = event.get("order", global_order)
            evt_order: list[str] | None = (
                [evt_order_raw] if isinstance(evt_order_raw, str) else evt_order_raw
            )

            # Within-event selection: pick one record per group
            if evt_order:
                # A missing order value loses in both modes; a tie keeps input order,
                # so "last" takes the last tied record (SAS LAST., admiral filter_extreme).
                candidates = candidates.sort(
                    evt_order, nulls_last=evt_mode == "first", maintain_order=True
                )
                self._warn_pick_ties(
                    candidates, event_nr, by_vars, evt_order, evt_mode, target_list
                )
                grouped = candidates.group_by(by_vars, maintain_order=True)
                candidates = grouped.first() if evt_mode == "first" else grouped.last()
            else:
                multi = (
                    candidates.group_by(by_vars, maintain_order=True)
                    .len()
                    .filter(pl.col("len") > 1)
                )
                if not multi.is_empty():
                    first = multi.row(0, named=True)
                    key = ", ".join(f"{c}={first[c]!r}" for c in by_vars)
                    raise DerivationError(
                        f"pick() event #{event_nr} has no order and {multi.height} group(s) "
                        f"with more than one matching record (first: {key}, "
                        f"{first['len']} records). Give 'order' in the event or at top "
                        "level, so the record does not depend on row order."
                    )
                candidates = candidates.group_by(by_vars, maintain_order=True).first()

            # Keep only by_vars + targets + the cross-event order + event_nr
            keep = by_vars + target_list + (global_order or []) + ["__pick_event_nr__"]
            available = [c for c in dict.fromkeys(keep) if c in candidates.columns]
            candidates = candidates.select(available)

            candidate_frames.append(candidates)

        # No events matched at all — set all targets to null
        if not candidate_frames:
            null_exprs = [pl.lit(None).alias(t) for t in target_list]
            return self._materialise_then(df.with_columns(null_exprs))

        # Each event gave at most one row per group.  A top-level order makes
        # them compete (admiral derive_vars_extreme_event); a tie goes to the
        # first listed event.  With no top-level order, list position decides.
        all_candidates = pl.concat(candidate_frames, how="diagonal_relaxed")
        if global_order:
            all_candidates = all_candidates.sort(
                [*global_order, "__pick_event_nr__"],
                descending=[mode == "last"] * len(global_order) + [False],
                nulls_last=True,
                maintain_order=True,
            )
        else:
            all_candidates = all_candidates.sort("__pick_event_nr__", maintain_order=True)
        winners = all_candidates.group_by(by_vars, maintain_order=True).first()
        winners = winners.select(by_vars + target_list)

        # Drop pre-existing target columns from base frame before join
        drop_existing = [t for t in target_list if t in df.columns]
        if drop_existing:
            df = df.drop(drop_existing)

        result = df.join(winners, on=by_vars, how="left", nulls_equal=True)
        return self._materialise_then(result)

    @staticmethod
    def _warn_pick_ties(
        candidates: pl.DataFrame,
        event_nr: int,
        by_vars: list[str],
        order: list[str],
        mode: str,
        targets: list[str],
    ) -> None:
        """Warn when records tie with the selected one on *order* but set other values."""
        pick_one = (lambda e: e.first()) if mode == "first" else (lambda e: e.last())
        tied = candidates.filter(
            pl.all_horizontal(
                pl.col(c).eq_missing(pick_one(pl.col(c)).over(by_vars)) for c in order
            )
        )
        differ = (
            tied.group_by(by_vars, maintain_order=True)
            .agg(pl.struct(targets).n_unique().alias("__n__"))
            .filter(pl.col("__n__") > 1)
        )
        if differ.is_empty():
            return
        first = differ.row(0, named=True)
        key = ", ".join(f"{c}={first[c]!r}" for c in by_vars)
        warnings.warn(
            f"pick() event #{event_nr}: {differ.height} group(s) have records that tie on "
            f"{order} and set different values (first: {key}). mode={mode!r} takes the "
            f"{mode} input record of the tie. Add a key to 'order' to break the tie.",
            stacklevel=3,
        )

    def whereclauses(self, *, where: str | pl.Expr) -> Self:
        """Filter records by a *where* expression.

        Materialises the pipeline before applying the filter.

        Args:
            where: A Polars expression (or string) that evaluates to a
                boolean mask.

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

        Examples:
            Subset to on-treatment records only::

                advs = (
                    vs_df.adam
                    .whereclauses(where='pl.col("ONTRTFL") == "Y"')
                    .to_frame()
                )
        """
        from fleet.sdtm.utils import parse_expression

        df = self.to_frame()
        filter_expr = where if isinstance(where, pl.Expr) else parse_expression(str(where))
        from fleet.core.lineage import record_row_step

        return record_row_step(
            self._materialise_then(df.filter(filter_expr)), "whereclauses", {"where": where}
        )

    def merge_adsl(
        self,
        adsl: pl.DataFrame,
        *,
        by: list[str] | None = None,
        keep: list[str] | None = None,
    ) -> Self:
        """Left-join ADSL columns onto the current dataset.

        Materialises the pipeline, left-joins *adsl* (optionally restricted to
        *keep* plus the *by* key columns), and returns a fresh namespace.
        Each *by* key must name one ADSL row, and a non-key column may be
        on one side only: give *keep*, or add a shared column such as
        STUDYID to *by*, as admiral ``derive_vars_merged`` asks.

        Args:
            adsl: The ADSL ``pl.DataFrame`` to merge in.
            by: Key column(s) for the join (default ``["USUBJID"]``).
            keep: Subset of ADSL columns to bring in (excluding *by*
                keys, which are always included).  When ``None``, all ADSL
                columns are merged.

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

        Raises:
            DerivationError: When a *keep* column is not in *adsl*, a
                non-key column is on both sides, or *adsl* has two
                different rows for one key.

        References:
            ADR-0032 (docs/adr/0032-merge-reads-as-sas-merge-and-stops-on-a-clash.md).
            ADaMIG 1.3: ADSL holds one record per subject.

        Examples:
            Merge treatment date columns from ADSL::

                advs = (
                    vs_df.adam
                    .merge_adsl(adsl_df, keep=["TRTSDT", "TRTEDT", "TRT01P"])
                    .to_frame()
                )
        """
        join_keys = by if by is not None else ["USUBJID"]
        if keep is not None:
            require_columns("merge_adsl(keep=...)", keep, adsl.columns, where="ADSL")
            adsl = adsl.select(list(dict.fromkeys(keep + join_keys)))
        df = self.to_frame()
        refuse_shared_columns(
            "merge_adsl()",
            df.columns,
            adsl.columns,
            join_keys,
            hint="Pass keep= to choose the ADSL columns, or add the shared column to by=.",
        )
        adsl = refuse_repeated_keys("merge_adsl()", adsl, join_keys, source="ADSL")
        joined = df.join(adsl, on=join_keys, how="left", nulls_equal=True)
        return self._materialise_then(joined)

    # ------------------------------------------------------------------ #
    # Subject-level event aggregations (first_date / last_date / count)    #
    # ------------------------------------------------------------------ #

    def first_date(
        self,
        target: str,
        *,
        from_dataset: pl.DataFrame,
        date_col: str,
        where: str | pl.Expr | None = None,
        by: list[str] | None = None,
        impute: str | None = None,
    ) -> Self:
        """Derive *target* as the earliest date in *date_col* from *from_dataset*.

        Materialises the current pipeline, aggregates *from_dataset* to
        subject level, then left-joins.  Useful for ASTDTM, TRTSDT, etc.
        ``--DTC`` text is compared as dates: ``*DT`` gives a date, ``*DTM``
        a date-time, ``*DTC`` the text of the earliest record.  A partial
        or unreadable value is left out with a warning, unless *impute*
        states the SAP rule (admiral ``derive_vars_dt``).

        Args:
            target: Name of the output date column.
            from_dataset: Source ``pl.DataFrame`` to aggregate.
            date_col: Date column to take the minimum of.
            where: Optional filter applied to *from_dataset* before aggregation.
            by: Join key columns (default ``["USUBJID"]``).
            impute: Impute a partial ``--DTC`` value (``"first"``, ``"mid"``,
                ``"last"``) for a ``*DT`` target, write the ``*DTF`` flag of the
                earliest record, and warn with the count.

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

        Examples:
            Derive earliest serious AE start date::

                adsl = (
                    dm_raw.adam.adsl
                    .first_date("AESTDTM", from_dataset=ae_sdtm,
                                date_col="AESTDTC",
                                where='pl.col("AESER") == "Y"')
                    .to_frame()
                )
        """
        from fleet.core.lineage import append_verb_node

        ns = self._date_agg(
            target,
            from_dataset=from_dataset,
            date_col=date_col,
            where=where,
            by=by,
            agg_fn="min",
            impute=impute,
        )
        params = {"target": target, "from_dataset": from_dataset, "date_col": date_col}
        params.update(where=where, by=by, impute=impute)
        return append_verb_node(ns, target, "first_date", [date_col], params)

    def last_date(
        self,
        target: str,
        *,
        from_dataset: pl.DataFrame,
        date_col: str,
        where: str | pl.Expr | None = None,
        by: list[str] | None = None,
        impute: str | None = None,
    ) -> Self:
        """Derive *target* as the latest date in *date_col* from *from_dataset*.

        Useful for AENDTM, TRTEDT, DTHDT, etc.  Reads ``--DTC`` text as
        :meth:`first_date` does.

        Args:
            target: Name of the output date column.
            from_dataset: Source ``pl.DataFrame`` to aggregate.
            date_col: Date column to take the maximum of.
            where: Optional filter applied to *from_dataset* before aggregation.
            by: Join key columns (default ``["USUBJID"]``).
            impute: Impute a partial ``--DTC`` value for a ``*DT`` target,
                write the ``*DTF`` flag of the latest record, and warn.

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

        Examples:
            Derive latest treatment end date::

                adsl = (
                    dm_raw.adam.adsl
                    .last_date("TRTEDT", from_dataset=ex_sdtm,
                               date_col="EXENDTC")
                    .to_frame()
                )
        """
        from fleet.core.lineage import append_verb_node

        ns = self._date_agg(
            target,
            from_dataset=from_dataset,
            date_col=date_col,
            where=where,
            by=by,
            agg_fn="max",
            impute=impute,
        )
        params = {"target": target, "from_dataset": from_dataset, "date_col": date_col}
        params.update(where=where, by=by, impute=impute)
        return append_verb_node(ns, target, "last_date", [date_col], params)

    def _date_agg(
        self,
        target: str,
        *,
        from_dataset: pl.DataFrame,
        date_col: str,
        where: str | pl.Expr | None,
        by: list[str] | None,
        agg_fn: str,
        impute: str | None = None,
    ) -> Self:
        """Shared implementation for first_date/last_date.

        ``--DTC`` text is read by the shared reader and compared as dates, so
        the extreme is a date, never a text minimum.  The output type
        follows the target: ``*DT`` a date, ``*DTM`` a date-time (values with
        hours and minutes), ``*DTC`` the text of the winning record.  With no
        *impute*, a partial value is left out with a warning; with one, a
        partial value is imputed and the ``*DTF`` flag comes from the
        winning record.
        """
        from fleet.adam.utils import (
            _extract_prefix,
            _infer_output_type,
            dtf_expr,
            impute_dtc_to_date,
        )
        from fleet.core.dtc import date_part, datetime_part
        from fleet.sdtm.utils import parse_expression

        verb = "first_date" if agg_fn == "min" else "last_date"
        grps = by or ["USUBJID"]
        src = from_dataset
        if where is not None:
            where_expr = where if isinstance(where, pl.Expr) else parse_expression(str(where))
            src = src.filter(where_expr)
        output = _infer_output_type(target) or "dt"
        if src.schema[date_col] != pl.String:
            if impute is not None:
                raise DerivationError(f"{verb}('{target}'): impute= reads --DTC text only.")
            col = pl.col(date_col)
            if output == "dt" and isinstance(src.schema[date_col], pl.Datetime):
                col = col.cast(pl.Date)
            agg_df = src.group_by(grps).agg(
                (col.min() if agg_fn == "min" else col.max()).alias(target)
            )
            df = self.to_frame()
            refuse_shared_columns(f"{verb}()", df.columns, agg_df.columns, grps, hint=_CLASH_HINT)
            df = df.join(agg_df, on=grps, how="left", nulls_equal=True)
            return self._materialise_then(df)

        raw = pl.col(date_col)
        flag = None
        if impute is not None:
            if output != "dt":
                raise DerivationError(
                    f"{verb}('{target}', impute=): imputation writes a *DT target and its *DTF "
                    "flag. Impute the source with .adam.date() first for other targets."
                )
            key = impute_dtc_to_date(
                date_col, "__key__", day_imputation=impute, month_imputation=impute
            )
            flag = f"{_extract_prefix(target)}DTF"
        elif output == "dtm":
            key = datetime_part(raw)
        else:
            key = date_part(raw)

        given = raw.str.strip_chars().fill_null("") != ""
        rows = src.with_columns(key.alias("__key__"))
        left_out = rows.filter(given & pl.col("__key__").is_null())
        if left_out.height:
            values = left_out[date_col].unique(maintain_order=True).head(5).to_list()
            warnings.warn(
                f"{verb}('{target}'): {date_col} has {left_out.height} partial or unreadable "
                f"value(s), left out of the {verb}. Pass impute= to impute partial dates. "
                f"Values: {values}",
                stacklevel=3,
            )

        picks = [pl.col("__key__").alias(target) if output != "dtc" else raw.alias(target)]
        if flag is not None:
            rows = rows.with_columns(dtf_expr(date_col, "__flag__"))
            picks.append(pl.col("__flag__").alias(flag))
        winners = (
            rows.filter(pl.col("__key__").is_not_null())
            .sort(
                [*grps, "__key__", *(["__flag__"] if flag else [])],
                descending=[False] * len(grps) + [agg_fn == "max"] + ([False] if flag else []),
                nulls_last=False,
            )
            .group_by(grps, maintain_order=True)
            .first()
            .select(*grps, *picks)
        )
        if flag is not None:
            imputed = winners.filter(pl.col(flag).is_not_null()).height
            if imputed:
                warnings.warn(
                    f"{verb}('{target}'): imputed {imputed} date(s) from partial {date_col} "
                    f"values (impute='{impute}'); {flag} records it.",
                    stacklevel=3,
                )
        df = self.to_frame()
        refuse_shared_columns(f"{verb}()", df.columns, winners.columns, grps, hint=_CLASH_HINT)
        df = df.join(winners, on=grps, how="left", nulls_equal=True)
        return self._materialise_then(df)

    def count_events(
        self,
        target: str,
        *,
        from_dataset: pl.DataFrame,
        where: str | pl.Expr | None = None,
        by: list[str] | None = None,
    ) -> Self:
        """Derive *target* as the count of matching records in *from_dataset*.

        Returns 0 for subjects with no matching records (never null).  The
        count is Int64, so a later subtraction can go below zero.

        Args:
            target: Name of the output count column.
            from_dataset: Source ``pl.DataFrame`` to count.
            where: Optional filter applied before counting.
            by: Join key columns (default ``["USUBJID"]``).

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

        Examples:
            Count total AE records per subject::

                adsl = (
                    dm_raw.adam.adsl
                    .count_events("NUMAE", from_dataset=ae_sdtm)
                    .to_frame()
                )
        """
        from fleet.sdtm.utils import parse_expression

        grps = by or ["USUBJID"]
        src = from_dataset
        if where is not None:
            where_expr = where if isinstance(where, pl.Expr) else parse_expression(str(where))
            src = src.filter(where_expr)
        agg_df = src.group_by(grps).agg(pl.len().cast(pl.Int64).alias(target))
        df = self.to_frame()
        refuse_shared_columns("count_events()", df.columns, agg_df.columns, grps, hint=_CLASH_HINT)
        df = df.join(agg_df, on=grps, how="left", nulls_equal=True)
        df = df.with_columns(pl.col(target).fill_null(0))
        from fleet.core.lineage import append_verb_node

        params = {"target": target, "from_dataset": from_dataset, "where": where, "by": by}
        return append_verb_node(self._materialise_then(df), target, "count_events", grps, params)

    # ------------------------------------------------------------------ #
    # Date derivation verbs                                                #
    # ------------------------------------------------------------------ #

    # ------------------------------------------------------------------ #
    # Unified date / duration verbs                                        #
    # ------------------------------------------------------------------ #

    def date(
        self,
        target: str,
        *,
        source: str | None = None,
        value: str | None = None,
        output: str | None = None,
        time: str | None = None,
        impute: str = "first",
        impute_time: str | None = None,
        highest: str | None = None,
        flag: bool | str = True,
        min_date: str | None = None,
        max_date: str | None = None,
    ) -> Self:
        """Parse, convert, impute, and flag a date or datetime column.

        Dispatches behavior based on the CDISC suffix of *target* (DT, DTM)
        or an explicit *output* override.  Supports both column references
        (``source=``) and literal values (``value=``).

        Args:
            target: Name of the output column.
            source: Column name to read values from.  Mutually exclusive
                with *value*.
            value: Literal date value to broadcast.  Mutually exclusive
                with *source*.
            output: Explicit output type override: ``"dt"`` or ``"dtm"``.
                When omitted, inferred from the *target* suffix.
            time: Time column name or ``"HH:MM:SS"`` literal to combine
                with the date from *source* (DTM targets only).
            impute: Imputation strategy for missing date components:
                ``"first"`` (default), ``"mid"``, ``"last"``, ``"none"``.
            impute_time: Override for time-part imputation, separate from
                *impute*.  Only relevant for DTM targets.
            highest: Maximum imputation ceiling (``"D"``, ``"M"``, ``"Y"``,
                ``"h"``, ``"m"``, ``"s"``).  Rows that exceed the ceiling
                are set to null.
            flag: ``True`` to auto-generate DTF/TMF flag columns,
                ``False`` to suppress, or a string to name the DTF flag
                explicitly.
            min_date: Lower bound for an imputed date (column name or date
                literal).  Applies only when the bound is inside the possible
                range of the partial value; a complete date never changes.
                Date (*DT) targets only.
            max_date: Upper bound for an imputed date, with the same rule.

        Returns:
            Self: The namespace with *target* (and optionally flag columns)
                appended; call ``.to_frame()`` to materialise.

        Examples:
            Derive ADT from a DTC source with default imputation::

                advs = (
                    vs_df.adam
                    .date("ADT", source="VSDTC")
                    .to_frame()
                )

            Non-standard target with explicit output and flag::

                df = (
                    raw.adam
                    .date("XYZ", source="raw_date", output="dt",
                          flag="XYZDTF")
                    .to_frame()
                )

            Broadcast a literal date::

                adsl = (
                    dm.adam.adsl
                    .date("RFSTDT", value="2024-01-15", output="dt",
                          flag=False)
                    .to_frame()
                )
        """
        from datetime import date as _date
        from datetime import datetime as _datetime

        from fleet.adam.utils import (
            _resolve_output_type,
            impute_and_flag,
        )

        # ── validate source / value mutual exclusivity ──
        if source is not None and value is not None:
            raise DerivationError("Cannot specify both source= and value=. Choose one.")
        if source is None and value is None:
            raise DerivationError("Must specify either source= or value=.")

        output_type = _resolve_output_type(target, output)

        # DTC targets belong in SDTM, not ADaM
        if output_type == "dtc":
            raise DerivationError(
                f"DTC output type is not supported on ADaM namespaces. "
                f"Use the SDTM .date() verb for target '{target}'."
            )

        # time= only valid for DTM
        if time is not None and output_type != "dtm":
            raise DerivationError(
                f"time= parameter is only valid for DTM targets, "
                f"but target '{target}' resolves to output='{output_type}'."
            )

        # value= path: broadcast literal, skip imputation
        if value is not None:
            # Default flags to False for value= (no imputation)
            if flag is True:
                flag = False
            # Parse string values to appropriate Python types
            val: str | _date | _datetime = value
            if isinstance(value, str):
                val = value
            exprs = impute_and_flag(
                None,
                target,
                value=val,
                output_type=output_type,
                flag=flag,
            )
            return self._chain(*exprs, verb="date")

        # source= path: one engine for both namespaces; time= first, then imputation
        assert source is not None
        from fleet.adam.utils import dtm_source_text, source_text

        schema = self._lazy.collect_schema()
        if time is not None:
            src = dtm_source_text(schema, source=source, target=target, time=time)
        else:
            src = source_text(source, schema.get(source), verb=f"date('{target}')")
        exprs = impute_and_flag(
            src,
            target,
            output_type=output_type,
            impute=impute,
            impute_time=impute_time,
            highest=highest,
            min_date=min_date,
            max_date=max_date,
            flag=flag,
        )
        return self._chain(*exprs, verb="date")

join_adsl

join_adsl(*cols)

Pull columns from pinned ADSL into this pipeline.

Performs a left join on the pinned join key, keeps only the requested columns, and records carry_forward lineage for each column.

Parameters:

Name Type Description Default
*cols str

Column names to carry forward from ADSL (e.g. "TRTSDT", "TRTEDT", "SAFFL").

()

Returns:

Name Type Description
Self Self

The namespace with ADSL columns attached; call .to_frame() to materialise.

Raises:

Type Description
LookupError

If ADSL is not pinned.

DerivationError

If a column is not in ADSL (with a did-you-mean suggestion), is already in the pipeline, or ADSL has two different rows for one subject.

References

ADR-0032 (docs/adr/0032-merge-reads-as-sas-merge-and-stops-on-a-clash.md). ADaMIG 1.3: ADSL holds one record per subject.

Examples:

Carry TRTSDT and SAFFL from ADSL into an ADAE pipeline::

adae = (
    ae_df.adam.occds("ADAE")
    .pin("ADSL", adsl_df)
    .source("USUBJID")
    .join_adsl("TRTSDT", "TRTEDT", "SAFFL")
    .to_frame()
)
Source code in src/fleet/adam/_mixins.py
def join_adsl(self, *cols: str) -> Self:
    """Pull columns from pinned ADSL into this pipeline.

    Performs a left join on the pinned join key, keeps only the
    requested columns, and records ``carry_forward`` lineage for
    each column.

    Args:
        *cols: Column names to carry forward from ADSL
            (e.g. ``"TRTSDT"``, ``"TRTEDT"``, ``"SAFFL"``).

    Returns:
        Self: The namespace with ADSL columns attached; call
            ``.to_frame()`` to materialise.

    Raises:
        LookupError: If ADSL is not pinned.
        DerivationError: If a column is not in ADSL (with a
            did-you-mean suggestion), is already in the pipeline, or
            ADSL has two different rows for one subject.

    References:
        ADR-0032 (docs/adr/0032-merge-reads-as-sas-merge-and-stops-on-a-clash.md).
        ADaMIG 1.3: ADSL holds one record per subject.

    Examples:
        Carry TRTSDT and SAFFL from ADSL into an ADAE pipeline::

            adae = (
                ae_df.adam.occds("ADAE")
                .pin("ADSL", adsl_df)
                .source("USUBJID")
                .join_adsl("TRTSDT", "TRTEDT", "SAFFL")
                .to_frame()
            )
    """
    from fleet.core.lineage import record_pin_lineage

    adsl = self._require_pin("ADSL", "join_adsl")
    join_key = self._pin_join_key("ADSL")
    require_columns("join_adsl()", cols, adsl.columns, where="the pinned ADSL")
    refuse_shared_columns(
        "join_adsl()",
        self._lazy.collect_schema().names(),
        cols,
        join_key,
        hint="Drop the column from the pipeline first, or leave it out of join_adsl().",
    )
    ref_slim = refuse_repeated_keys(
        "join_adsl()",
        adsl.select(list(dict.fromkeys(join_key + list(cols)))),
        join_key,
        source="ADSL",
    )

    df = self._lazy.collect().join(ref_slim, on=join_key, how="left", nulls_equal=True)
    new = self._materialise_then(df)

    for col in cols:
        record_pin_lineage(
            new,
            target_col=col,
            verb="join_adsl",
            source_domain="ADSL",
            source_cols=[col],
            join_key=join_key,
            relationship="carry_forward",
        )
    return new

source

source(*targets, from_col=None)

Carry one or more source columns into the ADaM dataset.

With a single name and from_col=, copies from_col to the target (legacy 1:1 form — prefer assign(target, source=...)). With multiple names, each column is carried through as-is::

.source("STUDYID", "USUBJID", "AETERM")

Parameters:

Name Type Description Default
*targets str

Output ADaM variable name(s). Without from_col each is an identity copy of the same-named input column.

()
from_col str | None

Name of the input column to copy from (single target only). Defaults to the target name.

None

Returns:

Name Type Description
Self Self

The namespace with the target(s) appended; call .to_frame() to materialise.

Raises:

Type Description
DerivationError

When no target is given, or from_col is combined with more than one target.

Examples:

Carry the key variables through in one call::

adae = (
    ae_df.adam
    .source("STUDYID", "USUBJID", "AEDECOD")
    .to_frame()
)
Source code in src/fleet/adam/_mixins.py
def source(self, *targets: str, from_col: str | None = None) -> Self:
    """Carry one or more source columns into the ADaM dataset.

    With a single name and ``from_col=``, copies *from_col* to the
    target (legacy 1:1 form — prefer ``assign(target, source=...)``).
    With multiple names, each column is carried through as-is::

        .source("STUDYID", "USUBJID", "AETERM")

    Args:
        *targets: Output ADaM variable name(s).  Without *from_col*
            each is an identity copy of the same-named input column.
        from_col: Name of the input column to copy from (single
            target only).  Defaults to the target name.

    Returns:
        Self: The namespace with the target(s) appended; call
            ``.to_frame()`` to materialise.

    Raises:
        DerivationError: When no target is given, or *from_col* is
            combined with more than one target.

    Examples:
        Carry the key variables through in one call::

            adae = (
                ae_df.adam
                .source("STUDYID", "USUBJID", "AEDECOD")
                .to_frame()
            )
    """
    if not targets:
        raise DerivationError("source() requires at least one column name.")
    if from_col is not None:
        if len(targets) > 1:
            raise DerivationError(
                "source(): from_col= applies to a single target — got "
                f"{len(targets)} targets. Use assign(target, source=...) "
                "for renames, or list the columns without from_col."
            )
        return self._chain(pl.col(from_col).alias(targets[0]), verb="source")
    exprs = [pl.col(t).alias(t) for t in targets]
    return self._chain(*exprs, verb="source")

recode

recode(target, *, source, recode_map, default=None)

Map values in source to recoded values in target.

Unmapped values fall back to default. The output type follows the map values and a literal default, ignoring None: integers give an integer column, integers with floats a float column (ADaM *N variables such as ASEVN and AVISITN are Num), and text gives text. A map that mixes kinds raises, so a typing slip cannot give a text *N variable.

Parameters:

Name Type Description Default
target str

Name of the output ADaM variable.

required
source str

Name of the input column containing coded values.

required
recode_map dict[Any, Any]

{old_value: new_value} mapping.

required
default Any

Value for entries not present in recode_map.

None

Returns:

Name Type Description
Self Self

The namespace with target appended; call .to_frame() to materialise.

Raises:

Type Description
DerivationError

When the map values and default mix kinds.

Examples:

Recode numeric sex to character::

adsl = (
    dm_df.adam.adsl
    .recode("SEX", source="SEXN",
            recode_map={1: "M", 2: "F"})
    .to_frame()
)

Code severity to a number::

adae = (
    ae_df.adam.occds
    .recode("ASEVN", source="ASEV",
            recode_map={"MILD": 1, "MODERATE": 2, "SEVERE": 3})
    .to_frame()
)
Source code in src/fleet/adam/_mixins.py
def recode(
    self,
    target: str,
    *,
    source: str,
    recode_map: dict[Any, Any],
    default: Any = None,
) -> Self:
    """Map values in *source* to recoded values in *target*.

    Unmapped values fall back to *default*.  The output type follows
    the map values and a literal *default*, ignoring ``None``: integers
    give an integer column, integers with floats a float column (ADaM
    ``*N`` variables such as ASEVN and AVISITN are Num), and text gives
    text.  A map that mixes kinds raises, so a typing slip cannot give a
    text ``*N`` variable.

    Args:
        target: Name of the output ADaM variable.
        source: Name of the input column containing coded values.
        recode_map: ``{old_value: new_value}`` mapping.
        default: Value for entries not present in *recode_map*.

    Returns:
        Self: The namespace with *target* appended; call ``.to_frame()``
            to materialise.

    Raises:
        DerivationError: When the map values and *default* mix kinds.

    Examples:
        Recode numeric sex to character::

            adsl = (
                dm_df.adam.adsl
                .recode("SEX", source="SEXN",
                        recode_map={1: "M", 2: "F"})
                .to_frame()
            )

        Code severity to a number::

            adae = (
                ae_df.adam.occds
                .recode("ASEVN", source="ASEV",
                        recode_map={"MILD": 1, "MODERATE": 2, "SEVERE": 3})
                .to_frame()
            )
    """
    default_expr = default if isinstance(default, pl.Expr) else pl.lit(default)
    if not recode_map:
        return self._chain(default_expr.alias(target), verb="recode")
    values = [*recode_map.values(), *([] if isinstance(default, pl.Expr) else [default])]
    kinds = {_value_kind(v) for v in values if v is not None}
    return_dtype: pl.DataType | None = None
    if kinds == {"int", "float"}:
        recode_map = {k: None if v is None else float(v) for k, v in recode_map.items()}
    elif len(kinds) > 1:
        raise DerivationError(
            f"recode('{target}'): the map values and default mix {sorted(kinds)}. "
            f"Give one kind, so {target} is numeric or text."
        )
    elif kinds != {"int"} and kinds != {"float"}:
        return_dtype = pl.String()
    expr = (
        pl.col(source)
        .replace_strict(recode_map, default=default_expr, return_dtype=return_dtype)
        .alias(target)
    )
    return self._chain(expr, verb="recode")

pick

pick(targets, *, events, by=None, order=None, mode='first')

Derive targets from one event per group, chosen across the events.

Each event in the list defines a candidate source, a filter condition, and values to set when that event is selected. Within each event's matching records, the event's order and mode (or the top-level ones) select one record. Then one event wins:

  • with a top-level order, every event's record competes on that order and mode, as admiral derive_vars_extreme_event does: order=["LSTALVDT"], mode="last" gives the latest date over all sources. A tie goes to the first listed event.
  • with no top-level order, the first listed event with a matching record wins (a priority cascade, as the admiral DTHCAUS template).

This is Fleet's answer to multi-source derivations such as last-date-known-alive (LSTALVDT) or death cause (DTHCAUS).

Event dict keys:

  • "when" (required): Boolean expression (str | pl.Expr) filtering which records qualify.
  • "set" (required): dict[str, str | pl.Expr | Any] mapping each target name to a column reference, expression, or literal. Column references use bare names ("DTHDT"); literals must be wrapped in pl.lit().
  • "source" (optional): External pl.DataFrame to scan for this event. When omitted, the current pipeline frame is used.
  • "mode" (optional): Override the top-level mode for this event only ("first" | "last").
  • "order" (optional): Override the top-level order for this event only.
  • "label" (optional): Documentation-only description.

Parameters:

Name Type Description Default
targets str | list[str]

Target column name(s) to derive.

required
events list[dict[str, Any]]

List of event dicts. List position breaks ties and, with no top-level order, decides the winner.

required
by list[str] | None

Grouping columns (default ["USUBJID"]).

None
order str | list[str] | None

Sort column(s). Within an event they select the record; at top level they also select the event (see above). An event with more than one matching record in a group needs an order (its own or the top-level one). A missing order value loses in both modes. Records that tie on the order keep their input order, so "last" takes the last tied record, as SAS LAST.; a warning names a tie whose records set different values.

None
mode str

"first" or "last" — which record to select after sorting by order (default "first").

'first'

Returns:

Name Type Description
Self Self

A fresh namespace with targets added; call .to_frame() to materialise.

Raises:

Type Description
DerivationError

If events is empty, a required key is missing, an event contains an unknown key (with a did-you-mean suggestion), or an event with no order has more than one matching record in a group. Also catchable as ValueError.

References

admiral derive_vars_extreme_event (order is required) and SAS FIRST./LAST. after PROC SORT EQUALS; ADR-0024.

Examples:

Derive last date known alive from death, AE, and treatment::

adsl = (
    dm.adam.adsl
    .source("USUBJID")
    .pick(
        ["LSTALVDT", "DTHFL"],
        events=[
            {"when": pl.col("DTHDT").is_not_null(),
             "set": {"LSTALVDT": "DTHDT", "DTHFL": pl.lit("Y")},
             "source": adsl_df, "label": "Death date"},
            {"when": pl.col("AEENDTC").is_not_null(),
             "set": {"LSTALVDT": "AEENDTC", "DTHFL": pl.lit("N")},
             "source": ae, "mode": "last", "order": ["AEENDTC"]},
            {"when": pl.col("TRTEDT").is_not_null(),
             "set": {"LSTALVDT": "TRTEDT", "DTHFL": pl.lit("N")},
             "source": adsl_df},
        ],
        by=["USUBJID"],
        order=["LSTALVDT"],
        mode="last",
    )
    .to_frame()
)

Simple single-target with string conditions (YAML-friendly)::

adsl = (
    dm.adam.adsl
    .pick(
        "DTHCAUS",
        events=[
            {"when": 'pl.col("AEOUT") == "FATAL"',
             "set": {"DTHCAUS": "AEDECOD"},
             "source": ae, "order": ["AESTDTC", "AESEQ"]},
            {"when": 'pl.col("DSDECOD") == "DEATH"',
             "set": {"DTHCAUS": "DSTERM"},
             "source": ds, "order": ["DSSTDTC", "DSSEQ"]},
        ],
        by=["USUBJID"],
    )
    .to_frame()
)
Source code in src/fleet/adam/_mixins.py
def pick(
    self,
    targets: str | list[str],
    *,
    events: list[dict[str, Any]],
    by: list[str] | None = None,
    order: str | list[str] | None = None,
    mode: str = "first",
) -> Self:
    """Derive targets from one event per group, chosen across the events.

    Each event in the list defines a candidate source, a filter
    condition, and values to set when that event is selected.  Within
    each event's matching records, the event's *order* and *mode* (or
    the top-level ones) select one record.  Then one event wins:

    - with a top-level *order*, every event's record competes on that
      order and *mode*, as admiral ``derive_vars_extreme_event`` does:
      ``order=["LSTALVDT"], mode="last"`` gives the latest date over all
      sources.  A tie goes to the first listed event.
    - with no top-level *order*, the first listed event with a matching
      record wins (a priority cascade, as the admiral DTHCAUS template).

    This is Fleet's answer to multi-source derivations such as
    last-date-known-alive (LSTALVDT) or death cause (DTHCAUS).

    Event dict keys:

    - ``"when"`` (required): Boolean expression (``str | pl.Expr``)
      filtering which records qualify.
    - ``"set"`` (required): ``dict[str, str | pl.Expr | Any]`` mapping
      each target name to a column reference, expression, or literal.
      Column references use bare names (``"DTHDT"``); literals must be
      wrapped in ``pl.lit()``.
    - ``"source"`` (optional): External ``pl.DataFrame`` to scan for
      this event.  When omitted, the current pipeline frame is used.
    - ``"mode"`` (optional): Override the top-level *mode* for this
      event only (``"first"`` | ``"last"``).
    - ``"order"`` (optional): Override the top-level *order* for this
      event only.
    - ``"label"`` (optional): Documentation-only description.

    Args:
        targets: Target column name(s) to derive.
        events: List of event dicts.  List position breaks ties and,
            with no top-level *order*, decides the winner.
        by: Grouping columns (default ``["USUBJID"]``).
        order: Sort column(s).  Within an event they select the record;
            at top level they also select the event (see above).  An
            event with more than one matching record in a group needs
            an order (its own or the top-level one).  A missing order
            value loses in both modes.  Records that tie on the order
            keep their input order, so ``"last"`` takes the last tied
            record, as SAS ``LAST.``; a warning names a tie whose
            records set different values.
        mode: ``"first"`` or ``"last"`` — which record to select
            after sorting by *order* (default ``"first"``).

    Returns:
        Self: A fresh namespace with *targets* added; call
            ``.to_frame()`` to materialise.

    Raises:
        DerivationError: If *events* is empty, a required key is
            missing, an event contains an unknown key (with a
            did-you-mean suggestion), or an event with no order has
            more than one matching record in a group.  Also catchable
            as ``ValueError``.

    References:
        admiral ``derive_vars_extreme_event`` (``order`` is required)
        and SAS ``FIRST.``/``LAST.`` after PROC SORT EQUALS; ADR-0024.

    Examples:
        Derive last date known alive from death, AE, and treatment::

            adsl = (
                dm.adam.adsl
                .source("USUBJID")
                .pick(
                    ["LSTALVDT", "DTHFL"],
                    events=[
                        {"when": pl.col("DTHDT").is_not_null(),
                         "set": {"LSTALVDT": "DTHDT", "DTHFL": pl.lit("Y")},
                         "source": adsl_df, "label": "Death date"},
                        {"when": pl.col("AEENDTC").is_not_null(),
                         "set": {"LSTALVDT": "AEENDTC", "DTHFL": pl.lit("N")},
                         "source": ae, "mode": "last", "order": ["AEENDTC"]},
                        {"when": pl.col("TRTEDT").is_not_null(),
                         "set": {"LSTALVDT": "TRTEDT", "DTHFL": pl.lit("N")},
                         "source": adsl_df},
                    ],
                    by=["USUBJID"],
                    order=["LSTALVDT"],
                    mode="last",
                )
                .to_frame()
            )

        Simple single-target with string conditions (YAML-friendly)::

            adsl = (
                dm.adam.adsl
                .pick(
                    "DTHCAUS",
                    events=[
                        {"when": 'pl.col("AEOUT") == "FATAL"',
                         "set": {"DTHCAUS": "AEDECOD"},
                         "source": ae, "order": ["AESTDTC", "AESEQ"]},
                        {"when": 'pl.col("DSDECOD") == "DEATH"',
                         "set": {"DTHCAUS": "DSTERM"},
                         "source": ds, "order": ["DSSTDTC", "DSSEQ"]},
                    ],
                    by=["USUBJID"],
                )
                .to_frame()
            )
    """
    from fleet.sdtm.utils import parse_expression

    if not events:
        raise DerivationError("pick() requires at least one event.")
    if mode not in ("first", "last"):
        raise DerivationError(
            f"pick() mode={mode!r} is not supported. Choose 'first' or 'last'."
        )

    target_list = [targets] if isinstance(targets, str) else list(targets)
    by_vars = by or ["USUBJID"]
    global_order: list[str] | None = (
        [order] if isinstance(order, str) else list(order) if order else None
    )

    df = self.to_frame()

    # Collect one candidate row per event per group.
    candidate_frames: list[pl.DataFrame] = []

    valid_event_keys = {"when", "set", "source", "mode", "order", "label"}
    for event_nr, event in enumerate(events):
        unknown = sorted(set(event) - valid_event_keys)
        if unknown:
            hints = []
            for key in unknown:
                close = difflib.get_close_matches(str(key), sorted(valid_event_keys), n=1)
                hints.append(f"'{key}'" + (f" (did you mean '{close[0]}'?)" if close else ""))
            raise DerivationError(
                f"pick() event #{event_nr} contains unknown key(s): {', '.join(hints)}. "
                f"Valid keys: {sorted(valid_event_keys)}."
            )
        if "when" not in event or "set" not in event:
            raise DerivationError(
                f"Event #{event_nr} must contain 'when' and 'set' keys. "
                f"Got keys: {list(event.keys())}"
            )

        # Resolve source frame
        source_df: pl.DataFrame = event.get("source", df)

        # Resolve condition
        when_raw = event["when"]
        when_expr: pl.Expr = (
            when_raw if isinstance(when_raw, pl.Expr) else parse_expression(str(when_raw))
        )

        # Filter candidates
        candidates = source_df.filter(when_expr)
        if candidates.is_empty():
            continue

        # Build set-values expressions
        set_exprs: list[pl.Expr] = []
        set_spec: dict[str, Any] = event["set"]
        for tgt in target_list:
            if tgt not in set_spec:
                # Target not produced by this event → null placeholder
                set_exprs.append(pl.lit(None).alias(tgt))
                continue
            val = set_spec[tgt]
            if isinstance(val, pl.Expr):
                set_exprs.append(val.alias(tgt))
            elif isinstance(val, str):
                # String → parse as expression or column reference.
                # parse_expression handles both: bare names ("AEENDTC")
                # become pl.col("AEENDTC"); expression strings like
                # 'pl.lit("Y")' are evaluated via sandboxed AST.
                set_exprs.append(parse_expression(val).alias(tgt))
            else:
                # Literal value
                set_exprs.append(pl.lit(val).alias(tgt))

        # Apply set expressions + add event priority marker
        candidates = candidates.with_columns(
            *set_exprs,
            pl.lit(event_nr).cast(pl.UInt32).alias("__pick_event_nr__"),
        )

        # Resolve per-event mode/order
        evt_mode = event.get("mode", mode)
        if evt_mode not in ("first", "last"):
            raise DerivationError(
                f"pick() event #{event_nr} mode={evt_mode!r} is not supported. "
                "Choose 'first' or 'last'."
            )
        evt_order_raw = event.get("order", global_order)
        evt_order: list[str] | None = (
            [evt_order_raw] if isinstance(evt_order_raw, str) else evt_order_raw
        )

        # Within-event selection: pick one record per group
        if evt_order:
            # A missing order value loses in both modes; a tie keeps input order,
            # so "last" takes the last tied record (SAS LAST., admiral filter_extreme).
            candidates = candidates.sort(
                evt_order, nulls_last=evt_mode == "first", maintain_order=True
            )
            self._warn_pick_ties(
                candidates, event_nr, by_vars, evt_order, evt_mode, target_list
            )
            grouped = candidates.group_by(by_vars, maintain_order=True)
            candidates = grouped.first() if evt_mode == "first" else grouped.last()
        else:
            multi = (
                candidates.group_by(by_vars, maintain_order=True)
                .len()
                .filter(pl.col("len") > 1)
            )
            if not multi.is_empty():
                first = multi.row(0, named=True)
                key = ", ".join(f"{c}={first[c]!r}" for c in by_vars)
                raise DerivationError(
                    f"pick() event #{event_nr} has no order and {multi.height} group(s) "
                    f"with more than one matching record (first: {key}, "
                    f"{first['len']} records). Give 'order' in the event or at top "
                    "level, so the record does not depend on row order."
                )
            candidates = candidates.group_by(by_vars, maintain_order=True).first()

        # Keep only by_vars + targets + the cross-event order + event_nr
        keep = by_vars + target_list + (global_order or []) + ["__pick_event_nr__"]
        available = [c for c in dict.fromkeys(keep) if c in candidates.columns]
        candidates = candidates.select(available)

        candidate_frames.append(candidates)

    # No events matched at all — set all targets to null
    if not candidate_frames:
        null_exprs = [pl.lit(None).alias(t) for t in target_list]
        return self._materialise_then(df.with_columns(null_exprs))

    # Each event gave at most one row per group.  A top-level order makes
    # them compete (admiral derive_vars_extreme_event); a tie goes to the
    # first listed event.  With no top-level order, list position decides.
    all_candidates = pl.concat(candidate_frames, how="diagonal_relaxed")
    if global_order:
        all_candidates = all_candidates.sort(
            [*global_order, "__pick_event_nr__"],
            descending=[mode == "last"] * len(global_order) + [False],
            nulls_last=True,
            maintain_order=True,
        )
    else:
        all_candidates = all_candidates.sort("__pick_event_nr__", maintain_order=True)
    winners = all_candidates.group_by(by_vars, maintain_order=True).first()
    winners = winners.select(by_vars + target_list)

    # Drop pre-existing target columns from base frame before join
    drop_existing = [t for t in target_list if t in df.columns]
    if drop_existing:
        df = df.drop(drop_existing)

    result = df.join(winners, on=by_vars, how="left", nulls_equal=True)
    return self._materialise_then(result)

whereclauses

whereclauses(*, where)

Filter records by a where expression.

Materialises the pipeline before applying the filter.

Parameters:

Name Type Description Default
where str | Expr

A Polars expression (or string) that evaluates to a boolean mask.

required

Returns:

Name Type Description
Self Self

A fresh namespace wrapping the filtered frame.

Examples:

Subset to on-treatment records only::

advs = (
    vs_df.adam
    .whereclauses(where='pl.col("ONTRTFL") == "Y"')
    .to_frame()
)
Source code in src/fleet/adam/_mixins.py
def whereclauses(self, *, where: str | pl.Expr) -> Self:
    """Filter records by a *where* expression.

    Materialises the pipeline before applying the filter.

    Args:
        where: A Polars expression (or string) that evaluates to a
            boolean mask.

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

    Examples:
        Subset to on-treatment records only::

            advs = (
                vs_df.adam
                .whereclauses(where='pl.col("ONTRTFL") == "Y"')
                .to_frame()
            )
    """
    from fleet.sdtm.utils import parse_expression

    df = self.to_frame()
    filter_expr = where if isinstance(where, pl.Expr) else parse_expression(str(where))
    from fleet.core.lineage import record_row_step

    return record_row_step(
        self._materialise_then(df.filter(filter_expr)), "whereclauses", {"where": where}
    )

merge_adsl

merge_adsl(adsl, *, by=None, keep=None)

Left-join ADSL columns onto the current dataset.

Materialises the pipeline, left-joins adsl (optionally restricted to keep plus the by key columns), and returns a fresh namespace. Each by key must name one ADSL row, and a non-key column may be on one side only: give keep, or add a shared column such as STUDYID to by, as admiral derive_vars_merged asks.

Parameters:

Name Type Description Default
adsl DataFrame

The ADSL pl.DataFrame to merge in.

required
by list[str] | None

Key column(s) for the join (default ["USUBJID"]).

None
keep list[str] | None

Subset of ADSL columns to bring in (excluding by keys, which are always included). When None, all ADSL columns are merged.

None

Returns:

Name Type Description
Self Self

A fresh namespace wrapping the joined frame.

Raises:

Type Description
DerivationError

When a keep column is not in adsl, a non-key column is on both sides, or adsl has two different rows for one key.

References

ADR-0032 (docs/adr/0032-merge-reads-as-sas-merge-and-stops-on-a-clash.md). ADaMIG 1.3: ADSL holds one record per subject.

Examples:

Merge treatment date columns from ADSL::

advs = (
    vs_df.adam
    .merge_adsl(adsl_df, keep=["TRTSDT", "TRTEDT", "TRT01P"])
    .to_frame()
)
Source code in src/fleet/adam/_mixins.py
def merge_adsl(
    self,
    adsl: pl.DataFrame,
    *,
    by: list[str] | None = None,
    keep: list[str] | None = None,
) -> Self:
    """Left-join ADSL columns onto the current dataset.

    Materialises the pipeline, left-joins *adsl* (optionally restricted to
    *keep* plus the *by* key columns), and returns a fresh namespace.
    Each *by* key must name one ADSL row, and a non-key column may be
    on one side only: give *keep*, or add a shared column such as
    STUDYID to *by*, as admiral ``derive_vars_merged`` asks.

    Args:
        adsl: The ADSL ``pl.DataFrame`` to merge in.
        by: Key column(s) for the join (default ``["USUBJID"]``).
        keep: Subset of ADSL columns to bring in (excluding *by*
            keys, which are always included).  When ``None``, all ADSL
            columns are merged.

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

    Raises:
        DerivationError: When a *keep* column is not in *adsl*, a
            non-key column is on both sides, or *adsl* has two
            different rows for one key.

    References:
        ADR-0032 (docs/adr/0032-merge-reads-as-sas-merge-and-stops-on-a-clash.md).
        ADaMIG 1.3: ADSL holds one record per subject.

    Examples:
        Merge treatment date columns from ADSL::

            advs = (
                vs_df.adam
                .merge_adsl(adsl_df, keep=["TRTSDT", "TRTEDT", "TRT01P"])
                .to_frame()
            )
    """
    join_keys = by if by is not None else ["USUBJID"]
    if keep is not None:
        require_columns("merge_adsl(keep=...)", keep, adsl.columns, where="ADSL")
        adsl = adsl.select(list(dict.fromkeys(keep + join_keys)))
    df = self.to_frame()
    refuse_shared_columns(
        "merge_adsl()",
        df.columns,
        adsl.columns,
        join_keys,
        hint="Pass keep= to choose the ADSL columns, or add the shared column to by=.",
    )
    adsl = refuse_repeated_keys("merge_adsl()", adsl, join_keys, source="ADSL")
    joined = df.join(adsl, on=join_keys, how="left", nulls_equal=True)
    return self._materialise_then(joined)

first_date

first_date(
    target,
    *,
    from_dataset,
    date_col,
    where=None,
    by=None,
    impute=None
)

Derive target as the earliest date in date_col from from_dataset.

Materialises the current pipeline, aggregates from_dataset to subject level, then left-joins. Useful for ASTDTM, TRTSDT, etc. --DTC text is compared as dates: *DT gives a date, *DTM a date-time, *DTC the text of the earliest record. A partial or unreadable value is left out with a warning, unless impute states the SAP rule (admiral derive_vars_dt).

Parameters:

Name Type Description Default
target str

Name of the output date column.

required
from_dataset DataFrame

Source pl.DataFrame to aggregate.

required
date_col str

Date column to take the minimum of.

required
where str | Expr | None

Optional filter applied to from_dataset before aggregation.

None
by list[str] | None

Join key columns (default ["USUBJID"]).

None
impute str | None

Impute a partial --DTC value ("first", "mid", "last") for a *DT target, write the *DTF flag of the earliest record, and warn with the count.

None

Returns:

Name Type Description
Self Self

The namespace with target appended.

Examples:

Derive earliest serious AE start date::

adsl = (
    dm_raw.adam.adsl
    .first_date("AESTDTM", from_dataset=ae_sdtm,
                date_col="AESTDTC",
                where='pl.col("AESER") == "Y"')
    .to_frame()
)
Source code in src/fleet/adam/_mixins.py
def first_date(
    self,
    target: str,
    *,
    from_dataset: pl.DataFrame,
    date_col: str,
    where: str | pl.Expr | None = None,
    by: list[str] | None = None,
    impute: str | None = None,
) -> Self:
    """Derive *target* as the earliest date in *date_col* from *from_dataset*.

    Materialises the current pipeline, aggregates *from_dataset* to
    subject level, then left-joins.  Useful for ASTDTM, TRTSDT, etc.
    ``--DTC`` text is compared as dates: ``*DT`` gives a date, ``*DTM``
    a date-time, ``*DTC`` the text of the earliest record.  A partial
    or unreadable value is left out with a warning, unless *impute*
    states the SAP rule (admiral ``derive_vars_dt``).

    Args:
        target: Name of the output date column.
        from_dataset: Source ``pl.DataFrame`` to aggregate.
        date_col: Date column to take the minimum of.
        where: Optional filter applied to *from_dataset* before aggregation.
        by: Join key columns (default ``["USUBJID"]``).
        impute: Impute a partial ``--DTC`` value (``"first"``, ``"mid"``,
            ``"last"``) for a ``*DT`` target, write the ``*DTF`` flag of the
            earliest record, and warn with the count.

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

    Examples:
        Derive earliest serious AE start date::

            adsl = (
                dm_raw.adam.adsl
                .first_date("AESTDTM", from_dataset=ae_sdtm,
                            date_col="AESTDTC",
                            where='pl.col("AESER") == "Y"')
                .to_frame()
            )
    """
    from fleet.core.lineage import append_verb_node

    ns = self._date_agg(
        target,
        from_dataset=from_dataset,
        date_col=date_col,
        where=where,
        by=by,
        agg_fn="min",
        impute=impute,
    )
    params = {"target": target, "from_dataset": from_dataset, "date_col": date_col}
    params.update(where=where, by=by, impute=impute)
    return append_verb_node(ns, target, "first_date", [date_col], params)

last_date

last_date(
    target,
    *,
    from_dataset,
    date_col,
    where=None,
    by=None,
    impute=None
)

Derive target as the latest date in date_col from from_dataset.

Useful for AENDTM, TRTEDT, DTHDT, etc. Reads --DTC text as :meth:first_date does.

Parameters:

Name Type Description Default
target str

Name of the output date column.

required
from_dataset DataFrame

Source pl.DataFrame to aggregate.

required
date_col str

Date column to take the maximum of.

required
where str | Expr | None

Optional filter applied to from_dataset before aggregation.

None
by list[str] | None

Join key columns (default ["USUBJID"]).

None
impute str | None

Impute a partial --DTC value for a *DT target, write the *DTF flag of the latest record, and warn.

None

Returns:

Name Type Description
Self Self

The namespace with target appended.

Examples:

Derive latest treatment end date::

adsl = (
    dm_raw.adam.adsl
    .last_date("TRTEDT", from_dataset=ex_sdtm,
               date_col="EXENDTC")
    .to_frame()
)
Source code in src/fleet/adam/_mixins.py
def last_date(
    self,
    target: str,
    *,
    from_dataset: pl.DataFrame,
    date_col: str,
    where: str | pl.Expr | None = None,
    by: list[str] | None = None,
    impute: str | None = None,
) -> Self:
    """Derive *target* as the latest date in *date_col* from *from_dataset*.

    Useful for AENDTM, TRTEDT, DTHDT, etc.  Reads ``--DTC`` text as
    :meth:`first_date` does.

    Args:
        target: Name of the output date column.
        from_dataset: Source ``pl.DataFrame`` to aggregate.
        date_col: Date column to take the maximum of.
        where: Optional filter applied to *from_dataset* before aggregation.
        by: Join key columns (default ``["USUBJID"]``).
        impute: Impute a partial ``--DTC`` value for a ``*DT`` target,
            write the ``*DTF`` flag of the latest record, and warn.

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

    Examples:
        Derive latest treatment end date::

            adsl = (
                dm_raw.adam.adsl
                .last_date("TRTEDT", from_dataset=ex_sdtm,
                           date_col="EXENDTC")
                .to_frame()
            )
    """
    from fleet.core.lineage import append_verb_node

    ns = self._date_agg(
        target,
        from_dataset=from_dataset,
        date_col=date_col,
        where=where,
        by=by,
        agg_fn="max",
        impute=impute,
    )
    params = {"target": target, "from_dataset": from_dataset, "date_col": date_col}
    params.update(where=where, by=by, impute=impute)
    return append_verb_node(ns, target, "last_date", [date_col], params)

count_events

count_events(target, *, from_dataset, where=None, by=None)

Derive target as the count of matching records in from_dataset.

Returns 0 for subjects with no matching records (never null). The count is Int64, so a later subtraction can go below zero.

Parameters:

Name Type Description Default
target str

Name of the output count column.

required
from_dataset DataFrame

Source pl.DataFrame to count.

required
where str | Expr | None

Optional filter applied before counting.

None
by list[str] | None

Join key columns (default ["USUBJID"]).

None

Returns:

Name Type Description
Self Self

The namespace with target appended.

Examples:

Count total AE records per subject::

adsl = (
    dm_raw.adam.adsl
    .count_events("NUMAE", from_dataset=ae_sdtm)
    .to_frame()
)
Source code in src/fleet/adam/_mixins.py
def count_events(
    self,
    target: str,
    *,
    from_dataset: pl.DataFrame,
    where: str | pl.Expr | None = None,
    by: list[str] | None = None,
) -> Self:
    """Derive *target* as the count of matching records in *from_dataset*.

    Returns 0 for subjects with no matching records (never null).  The
    count is Int64, so a later subtraction can go below zero.

    Args:
        target: Name of the output count column.
        from_dataset: Source ``pl.DataFrame`` to count.
        where: Optional filter applied before counting.
        by: Join key columns (default ``["USUBJID"]``).

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

    Examples:
        Count total AE records per subject::

            adsl = (
                dm_raw.adam.adsl
                .count_events("NUMAE", from_dataset=ae_sdtm)
                .to_frame()
            )
    """
    from fleet.sdtm.utils import parse_expression

    grps = by or ["USUBJID"]
    src = from_dataset
    if where is not None:
        where_expr = where if isinstance(where, pl.Expr) else parse_expression(str(where))
        src = src.filter(where_expr)
    agg_df = src.group_by(grps).agg(pl.len().cast(pl.Int64).alias(target))
    df = self.to_frame()
    refuse_shared_columns("count_events()", df.columns, agg_df.columns, grps, hint=_CLASH_HINT)
    df = df.join(agg_df, on=grps, how="left", nulls_equal=True)
    df = df.with_columns(pl.col(target).fill_null(0))
    from fleet.core.lineage import append_verb_node

    params = {"target": target, "from_dataset": from_dataset, "where": where, "by": by}
    return append_verb_node(self._materialise_then(df), target, "count_events", grps, params)

date

date(
    target,
    *,
    source=None,
    value=None,
    output=None,
    time=None,
    impute="first",
    impute_time=None,
    highest=None,
    flag=True,
    min_date=None,
    max_date=None
)

Parse, convert, impute, and flag a date or datetime column.

Dispatches behavior based on the CDISC suffix of target (DT, DTM) or an explicit output override. Supports both column references (source=) and literal values (value=).

Parameters:

Name Type Description Default
target str

Name of the output column.

required
source str | None

Column name to read values from. Mutually exclusive with value.

None
value str | None

Literal date value to broadcast. Mutually exclusive with source.

None
output str | None

Explicit output type override: "dt" or "dtm". When omitted, inferred from the target suffix.

None
time str | None

Time column name or "HH:MM:SS" literal to combine with the date from source (DTM targets only).

None
impute str

Imputation strategy for missing date components: "first" (default), "mid", "last", "none".

'first'
impute_time str | None

Override for time-part imputation, separate from impute. Only relevant for DTM targets.

None
highest str | None

Maximum imputation ceiling ("D", "M", "Y", "h", "m", "s"). Rows that exceed the ceiling are set to null.

None
flag bool | str

True to auto-generate DTF/TMF flag columns, False to suppress, or a string to name the DTF flag explicitly.

True
min_date str | None

Lower bound for an imputed date (column name or date literal). Applies only when the bound is inside the possible range of the partial value; a complete date never changes. Date (*DT) targets only.

None
max_date str | None

Upper bound for an imputed date, with the same rule.

None

Returns:

Name Type Description
Self Self

The namespace with target (and optionally flag columns) appended; call .to_frame() to materialise.

Examples:

Derive ADT from a DTC source with default imputation::

advs = (
    vs_df.adam
    .date("ADT", source="VSDTC")
    .to_frame()
)

Non-standard target with explicit output and flag::

df = (
    raw.adam
    .date("XYZ", source="raw_date", output="dt",
          flag="XYZDTF")
    .to_frame()
)

Broadcast a literal date::

adsl = (
    dm.adam.adsl
    .date("RFSTDT", value="2024-01-15", output="dt",
          flag=False)
    .to_frame()
)
Source code in src/fleet/adam/_mixins.py
def date(
    self,
    target: str,
    *,
    source: str | None = None,
    value: str | None = None,
    output: str | None = None,
    time: str | None = None,
    impute: str = "first",
    impute_time: str | None = None,
    highest: str | None = None,
    flag: bool | str = True,
    min_date: str | None = None,
    max_date: str | None = None,
) -> Self:
    """Parse, convert, impute, and flag a date or datetime column.

    Dispatches behavior based on the CDISC suffix of *target* (DT, DTM)
    or an explicit *output* override.  Supports both column references
    (``source=``) and literal values (``value=``).

    Args:
        target: Name of the output column.
        source: Column name to read values from.  Mutually exclusive
            with *value*.
        value: Literal date value to broadcast.  Mutually exclusive
            with *source*.
        output: Explicit output type override: ``"dt"`` or ``"dtm"``.
            When omitted, inferred from the *target* suffix.
        time: Time column name or ``"HH:MM:SS"`` literal to combine
            with the date from *source* (DTM targets only).
        impute: Imputation strategy for missing date components:
            ``"first"`` (default), ``"mid"``, ``"last"``, ``"none"``.
        impute_time: Override for time-part imputation, separate from
            *impute*.  Only relevant for DTM targets.
        highest: Maximum imputation ceiling (``"D"``, ``"M"``, ``"Y"``,
            ``"h"``, ``"m"``, ``"s"``).  Rows that exceed the ceiling
            are set to null.
        flag: ``True`` to auto-generate DTF/TMF flag columns,
            ``False`` to suppress, or a string to name the DTF flag
            explicitly.
        min_date: Lower bound for an imputed date (column name or date
            literal).  Applies only when the bound is inside the possible
            range of the partial value; a complete date never changes.
            Date (*DT) targets only.
        max_date: Upper bound for an imputed date, with the same rule.

    Returns:
        Self: The namespace with *target* (and optionally flag columns)
            appended; call ``.to_frame()`` to materialise.

    Examples:
        Derive ADT from a DTC source with default imputation::

            advs = (
                vs_df.adam
                .date("ADT", source="VSDTC")
                .to_frame()
            )

        Non-standard target with explicit output and flag::

            df = (
                raw.adam
                .date("XYZ", source="raw_date", output="dt",
                      flag="XYZDTF")
                .to_frame()
            )

        Broadcast a literal date::

            adsl = (
                dm.adam.adsl
                .date("RFSTDT", value="2024-01-15", output="dt",
                      flag=False)
                .to_frame()
            )
    """
    from datetime import date as _date
    from datetime import datetime as _datetime

    from fleet.adam.utils import (
        _resolve_output_type,
        impute_and_flag,
    )

    # ── validate source / value mutual exclusivity ──
    if source is not None and value is not None:
        raise DerivationError("Cannot specify both source= and value=. Choose one.")
    if source is None and value is None:
        raise DerivationError("Must specify either source= or value=.")

    output_type = _resolve_output_type(target, output)

    # DTC targets belong in SDTM, not ADaM
    if output_type == "dtc":
        raise DerivationError(
            f"DTC output type is not supported on ADaM namespaces. "
            f"Use the SDTM .date() verb for target '{target}'."
        )

    # time= only valid for DTM
    if time is not None and output_type != "dtm":
        raise DerivationError(
            f"time= parameter is only valid for DTM targets, "
            f"but target '{target}' resolves to output='{output_type}'."
        )

    # value= path: broadcast literal, skip imputation
    if value is not None:
        # Default flags to False for value= (no imputation)
        if flag is True:
            flag = False
        # Parse string values to appropriate Python types
        val: str | _date | _datetime = value
        if isinstance(value, str):
            val = value
        exprs = impute_and_flag(
            None,
            target,
            value=val,
            output_type=output_type,
            flag=flag,
        )
        return self._chain(*exprs, verb="date")

    # source= path: one engine for both namespaces; time= first, then imputation
    assert source is not None
    from fleet.adam.utils import dtm_source_text, source_text

    schema = self._lazy.collect_schema()
    if time is not None:
        src = dtm_source_text(schema, source=source, target=target, time=time)
    else:
        src = source_text(source, schema.get(source), verb=f"date('{target}')")
    exprs = impute_and_flag(
        src,
        target,
        output_type=output_type,
        impute=impute,
        impute_time=impute_time,
        highest=highest,
        min_date=min_date,
        max_date=max_date,
        flag=flag,
    )
    return self._chain(*exprs, verb="date")

options: show_root_heading: false heading_level: 3 members_order: source filters: ["!^_"]

Flag Criterion Mixin

fleet.adam.FlagCriterionMixin

Mixin providing flag(), its wrappers, and criterion().

Both SDTM (df.sdtm) and all ADaM namespaces inherit from this mixin. The methods rely on _chain(), _with_lazy() and _materialise_then() which every concrete namespace class must provide.

Source code in src/fleet/core/_flag_mixin.py
 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
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
class FlagCriterionMixin:
    """Mixin providing ``flag()``, its wrappers, and ``criterion()``.

    Both SDTM (``df.sdtm``) and all ADaM namespaces inherit from this
    mixin.  The methods rely on ``_chain()``, ``_with_lazy()`` and
    ``_materialise_then()`` which every concrete namespace class must
    provide.
    """

    _lazy: pl.LazyFrame

    # Subclasses must provide these — declared here for type-checker only.
    def _chain(self, *exprs: pl.Expr, verb: str | None = None) -> Self: ...  # noqa: E704
    def _materialise_then(self, df: pl.DataFrame) -> Self: ...  # noqa: E704
    def _with_lazy(self, lf: pl.LazyFrame) -> Self: ...  # noqa: E704

    # ------------------------------------------------------------------ #
    # Flag — generalised "Y" / null flagging                               #
    # ------------------------------------------------------------------ #

    def flag(
        self,
        target: str,
        *,
        criteria: str | pl.Expr,
        by: list[str] | None = None,
        order_by: str | list[str] | None = None,
        value_col: str | None = None,
        where: str | pl.Expr | None = None,
        from_dataset: pl.DataFrame | list[pl.DataFrame] | None = None,
        on: list[str] | None = None,
        source_filter: pl.Expr | None = None,
        condition: pl.Expr | None = None,
        inclusive: bool = True,
        flag_no_ref_groups: bool = True,
        flag_all: bool = False,
        flag_value: str = "Y",
        false_value: str | None = None,
    ) -> Self:
        """Set *target* to *flag_value* for records matching *criteria*.

        Supports row-level boolean expressions and built-in shortcuts:

        - ``"first"`` / ``"last"`` — rank-based edge detection within groups.
        - ``"max"`` / ``"min"`` — value-based extreme within groups.
        - ``"exists"`` — set-membership from external dataset(s).
        - ``"before"`` / ``"after"`` — relative to a landmark condition.
        - ``"exists_after"`` / ``"exists_before"`` — temporal/self-join flag.

        Parameters that are irrelevant to the selected criteria mode
        raise :class:`~fleet.core.exceptions.VerbUsageError` instead of
        being silently ignored.  The ``flag_first`` / ``flag_last`` /
        ``flag_extreme`` / ``flag_exists`` / ``flag_relative`` wrappers
        expose each mode with only its own parameters.

        Args:
            target: Name of the output flag column.
            criteria: A Polars expression, or one of ``"first"``,
                ``"last"``, ``"max"``, ``"min"``, ``"exists"``,
                ``"before"``, ``"after"``, ``"exists_after"``,
                ``"exists_before"``.
            by: Partition columns (default ``["USUBJID"]``).
            order_by: Sort column(s) required for ``"first"``/``"last"``
                and ``"before"``/``"after"``.  On a tie among candidates,
                ``"last"`` takes the last input record and ``"first"`` the
                first (SAS ``LAST.``/``FIRST.``); add a sequence variable
                to remove the dependence on input order.  For
                ``"first"``/``"last"`` a missing value sorts last in each
                key, as admiral (ADR-0020): ``"last"`` takes a record with a
                missing key, and ``"first"`` takes one only when every
                candidate misses it.  SAS sorts a missing value first, so a
                QC program with PROC SORT differs on such a group.
                ``"exists_after"``/``"exists_before"`` take one column
                only; build one ordered key (ADTM) for date and time.
            value_col: Value column required for ``"max"``/``"min"``.
            where: Optional pre-filter — only matching rows are candidates;
                rows that fail it take no part, even on a tie.
            from_dataset: External dataset(s) for ``"exists"`` and
                ``"exists_after"``/``"exists_before"`` criteria.
            on: Join key columns for ``"exists"`` criteria.
            source_filter: Filter applied to *from_dataset* before key
                extraction or join.
            condition: Boolean expression identifying landmark rows for
                ``"before"``/``"after"`` or the current-row condition for
                ``"exists_after"``/``"exists_before"``.
            inclusive: Whether the landmark row itself is included in the
                flag (for ``"before"``/``"after"``). Default ``True``.
            flag_no_ref_groups: If ``False``, groups without a landmark
                condition match get ``None`` instead of being flagged
                (for ``"before"``/``"after"``). Default ``True``.
            flag_all: If ``True``, all tied extreme values receive the
                flag (for ``"first"``/``"last"``). Default ``False``.
            flag_value: Value to assign when condition is met (default
                ``"Y"``).
            false_value: Value to assign when condition is not met.
                Default ``None`` (null).

        Returns:
            Self: The namespace with *target* appended; call
                ``.to_frame()`` to materialise.

        Raises:
            VerbUsageError: When a parameter irrelevant to the selected
                criteria mode is passed.
            DerivationError: When a mode-required parameter is missing,
                or a bare-identifier *criteria* matches neither a
                keyword nor a column.

        References:
            admiral ``derive_var_extreme_flag`` (pharmaverse): the order of
            ``"first"``/``"last"``, a missing value last in each key (ADR-0020).

        Examples:
            First observation per group::

                advs = (
                    vs_raw.adam
                    .flag("ABLFL", criteria="first", order_by="AVISITN",
                          by=["USUBJID", "PARAMCD"])
                    .to_frame()
                )

            Existence flag from external dataset::

                adsl = (
                    dm.adam.adsl
                    .flag("VSEVALFL", criteria="exists",
                          from_dataset=advs, on=["USUBJID"],
                          source_filter=pl.col("AVISIT") == "BASELINE")
                    .to_frame()
                )

            Relative flag — before first PD::

                result = (
                    response.adam
                    .flag("ANL02FL", criteria="before",
                          condition=pl.col("AVALC") == "PD",
                          order_by="AVISITN", by=["USUBJID"],
                          inclusive=True)
                    .to_frame()
                )

            Population flag from the treatment start date (a population
            flag is never blank, so non-members get ``"N"``)::

                adsl = (
                    adsl.adam.adsl
                    .flag("SAFFL", criteria=pl.col("TRTSDT").is_not_null(),
                          false_value="N")
                    .to_frame()
                )
        """
        from fleet.sdtm.utils import parse_expression

        grps = by or ["USUBJID"]
        order_cols: list[str] | None = None
        if order_by is not None:
            order_cols = [order_by] if isinstance(order_by, str) else list(order_by)

        criteria_lower = criteria.lower() if isinstance(criteria, str) else None
        mode = criteria_lower if criteria_lower in _FLAG_CRITERIA_KEYWORDS else "expression"
        if mode == "expression":
            # Keyword typos ("frist") must surface as a did-you-mean error
            # before any parameter validation blames the wrong thing.
            self._check_flag_criteria_typo(target, criteria)
        self._validate_flag_params(
            target,
            criteria,
            mode,
            {
                "order_by": order_by,
                "value_col": value_col,
                "where": where,
                "from_dataset": from_dataset,
                "on": on,
                "source_filter": source_filter,
                "condition": condition,
                "inclusive": inclusive,
                "flag_no_ref_groups": flag_no_ref_groups,
                "flag_all": flag_all,
                "false_value": false_value,
            },
        )

        where_expr: pl.Expr | None = None
        if where is not None:
            where_expr = where if isinstance(where, pl.Expr) else parse_expression(str(where))

        false_lit = pl.lit(false_value) if false_value is not None else pl.lit(None)

        if mode in ("first", "last"):
            return self._flag_ranked(
                target,
                criteria_lower=mode,
                grps=grps,
                order_cols=order_cols,
                where_expr=where_expr,
                flag_all=flag_all,
                flag_value=flag_value,
                false_lit=false_lit,
            )
        elif mode in ("max", "min"):
            return self._flag_extreme(
                target,
                criteria_lower=mode,
                grps=grps,
                value_col=value_col,
                where_expr=where_expr,
                flag_value=flag_value,
                false_lit=false_lit,
            )
        elif mode == "exists":
            return self._flag_exists(
                target,
                grps=grps,
                from_dataset=from_dataset,
                on=on,
                source_filter=source_filter,
                flag_value=flag_value,
                false_lit=false_lit,
            )
        elif mode in ("before", "after"):
            return self._flag_relative(
                target,
                criteria_lower=mode,
                grps=grps,
                order_cols=order_cols,
                condition=condition,
                inclusive=inclusive,
                flag_no_ref_groups=flag_no_ref_groups,
                flag_value=flag_value,
                false_value=false_value,
            )
        elif mode in ("exists_after", "exists_before"):
            return self._flag_temporal_exists(
                target,
                criteria_lower=mode,
                from_dataset=from_dataset,
                on=on,
                order_cols=order_cols,
                condition=condition,
                source_filter=source_filter,
                flag_value=flag_value,
            )
        else:
            return self._flag_expression(
                target,
                criteria=criteria,
                where_expr=where_expr,
                flag_value=flag_value,
                false_lit=false_lit,
            )

    # ------------------------------------------------------------------ #
    # Discoverable per-mode wrappers                                       #
    # ------------------------------------------------------------------ #

    def flag_first(
        self,
        target: str,
        *,
        order_by: str | list[str],
        by: list[str] | None = None,
        where: str | pl.Expr | None = None,
        flag_all: bool = False,
        flag_value: str = "Y",
        false_value: str | None = None,
    ) -> Self:
        """Flag the first record per group (``flag(criteria="first")``).

        Args:
            target: Name of the output flag column.
            order_by: Sort column(s) defining "first" within each group.
                A tie goes to the first input record.  A missing value sorts
                last, as admiral: it is first only when every candidate
                misses it.
            by: Partition columns (default ``["USUBJID"]``).
            where: Optional pre-filter — only matching rows are candidates.
            flag_all: Flag every tied extreme record instead of one.
            flag_value: Value assigned to flagged records (default ``"Y"``).
            false_value: Value assigned otherwise (default null).

        Returns:
            Self: The namespace with *target* appended; call
                ``.to_frame()`` to materialise.

        Examples:
            Baseline flag on the first visit per subject/parameter::

                advs = (
                    vs_raw.adam
                    .flag_first("ABLFL", order_by="AVISITN",
                                by=["USUBJID", "PARAMCD"])
                    .to_frame()
                )
        """
        return self.flag(
            target,
            criteria="first",
            order_by=order_by,
            by=by,
            where=where,
            flag_all=flag_all,
            flag_value=flag_value,
            false_value=false_value,
        )

    def flag_last(
        self,
        target: str,
        *,
        order_by: str | list[str],
        by: list[str] | None = None,
        where: str | pl.Expr | None = None,
        flag_all: bool = False,
        flag_value: str = "Y",
        false_value: str | None = None,
    ) -> Self:
        """Flag the last record per group (``flag(criteria="last")``).

        Args:
            target: Name of the output flag column.
            order_by: Sort column(s) defining "last" within each group.
                A tie goes to the last input record.  A missing value sorts
                last, as admiral, so a record with a missing key is last.
            by: Partition columns (default ``["USUBJID"]``).
            where: Optional pre-filter — only matching rows are candidates.
            flag_all: Flag every tied extreme record instead of one.
            flag_value: Value assigned to flagged records (default ``"Y"``).
            false_value: Value assigned otherwise (default null).

        Returns:
            Self: The namespace with *target* appended; call
                ``.to_frame()`` to materialise.

        Examples:
            Last analysis-eligible record per subject/parameter::

                advs = (
                    vs_raw.adam
                    .flag_last("ANL01FL", order_by="ADT",
                               by=["USUBJID", "PARAMCD"])
                    .to_frame()
                )
        """
        return self.flag(
            target,
            criteria="last",
            order_by=order_by,
            by=by,
            where=where,
            flag_all=flag_all,
            flag_value=flag_value,
            false_value=false_value,
        )

    def flag_extreme(
        self,
        target: str,
        *,
        value_col: str,
        mode: Literal["max", "min"] = "max",
        by: list[str] | None = None,
        where: str | pl.Expr | None = None,
        flag_value: str = "Y",
        false_value: str | None = None,
    ) -> Self:
        """Flag the extreme-valued record(s) per group (``criteria="max"/"min"``).

        Args:
            target: Name of the output flag column.
            value_col: Column whose extreme value is flagged.
            mode: ``"max"`` (default) or ``"min"``.
            by: Partition columns (default ``["USUBJID"]``).
            where: Optional pre-filter — only matching rows are candidates.
            flag_value: Value assigned to flagged records (default ``"Y"``).
            false_value: Value assigned otherwise (default null).

        Returns:
            Self: The namespace with *target* appended; call
                ``.to_frame()`` to materialise.

        Examples:
            Worst-severity record per subject and term::

                adae = (
                    ae_df.adam.occds
                    .flag_extreme("ANL01FL", value_col="AESEVN",
                                  by=["USUBJID", "AETERM"])
                    .to_frame()
                )
        """
        return self.flag(
            target,
            criteria=mode,
            value_col=value_col,
            by=by,
            where=where,
            flag_value=flag_value,
            false_value=false_value,
        )

    def flag_exists(
        self,
        target: str,
        *,
        from_dataset: pl.DataFrame | list[pl.DataFrame],
        on: list[str],
        source_filter: pl.Expr | None = None,
        flag_value: str = "Y",
        false_value: str | None = None,
    ) -> Self:
        """Flag records with a match in external dataset(s) (``criteria="exists"``).

        Args:
            target: Name of the output flag column.
            from_dataset: External dataset(s) to look up keys in.
            on: Join key columns.
            source_filter: Filter applied to *from_dataset* before key
                extraction.
            flag_value: Value assigned when a match exists (default ``"Y"``).
            false_value: Value assigned otherwise (default null).

        Returns:
            Self: The namespace with *target* appended; call
                ``.to_frame()`` to materialise.

        Examples:
            Subjects with a baseline vital-signs record::

                adsl = (
                    dm.adam.adsl
                    .flag_exists("VSEVALFL", from_dataset=advs,
                                 on=["USUBJID"],
                                 source_filter=pl.col("AVISIT") == "BASELINE")
                    .to_frame()
                )
        """
        return self.flag(
            target,
            criteria="exists",
            from_dataset=from_dataset,
            on=on,
            source_filter=source_filter,
            flag_value=flag_value,
            false_value=false_value,
        )

    def flag_relative(
        self,
        target: str,
        *,
        when: Literal["before", "after"],
        condition: pl.Expr,
        order_by: str | list[str],
        by: list[str] | None = None,
        inclusive: bool = True,
        flag_no_ref_groups: bool = True,
        flag_value: str = "Y",
        false_value: str | None = None,
    ) -> Self:
        """Flag records before/after a landmark (``criteria="before"/"after"``).

        Args:
            target: Name of the output flag column.
            when: ``"before"`` or ``"after"`` the first landmark record.
            condition: Boolean expression identifying landmark rows.
            order_by: Sort column(s) defining record order within groups.
            by: Partition columns (default ``["USUBJID"]``).
            inclusive: Whether the landmark row itself is flagged.
            flag_no_ref_groups: If ``True`` (default), every record of a
                group with no landmark gets *flag_value*, in both
                directions, as admiral ``derive_var_relative_flag``.  Pass
                ``False`` for a post-event flag, so that such a group gets
                *false_value*.
            flag_value: Value assigned to flagged records (default ``"Y"``).
            false_value: Value assigned otherwise (default null).

        Returns:
            Self: The namespace with *target* appended; call
                ``.to_frame()`` to materialise.

        Examples:
            Analysis flag for records up to first disease progression::

                adrs = (
                    rs_df.adam
                    .flag_relative("ANL02FL", when="before",
                                   condition=pl.col("AVALC") == "PD",
                                   order_by="AVISITN", by=["USUBJID"])
                    .to_frame()
                )
        """
        return self.flag(
            target,
            criteria=when,
            condition=condition,
            order_by=order_by,
            by=by,
            inclusive=inclusive,
            flag_no_ref_groups=flag_no_ref_groups,
            flag_value=flag_value,
            false_value=false_value,
        )

    # ------------------------------------------------------------------ #
    # Internal validation / dispatch helpers                               #
    # ------------------------------------------------------------------ #

    def _validate_flag_params(
        self,
        target: str,
        criteria: str | pl.Expr,
        mode: str,
        passed: dict[str, object],
    ) -> None:
        """Reject parameters that the selected criteria mode does not use."""
        irrelevant = [
            name
            for name, value in passed.items()
            if value is not _FLAG_PARAM_DEFAULTS[name] and mode not in _FLAG_MODE_PARAMS[name]
        ]
        if not irrelevant:
            return
        crit_repr = repr(criteria) if isinstance(criteria, str) else "<expression>"
        raise VerbUsageError(
            f"flag('{target}', criteria={crit_repr}): parameter(s) "
            f"{', '.join(sorted(irrelevant))} are not used by criteria mode "
            f"'{mode}' and would be silently ignored. Remove them, or pick the "
            "matching mode (see flag_first/flag_last/flag_extreme/flag_exists/"
            "flag_relative for per-mode signatures)."
        )

    def _check_flag_criteria_typo(self, target: str, criteria: str | pl.Expr) -> None:
        """Reject bare-identifier criteria that match neither keyword nor column.

        A string like ``"frist"`` would otherwise fall through to
        expression parsing and blame a nonexistent *column* when the user
        typo'd a *keyword*.  Reports both interpretations.
        """
        if not isinstance(criteria, str):
            return
        bare = criteria.strip()
        if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", bare):
            return
        schema_names = self._lazy.collect_schema().names()
        if bare in schema_names:
            return
        parts = [
            f"flag('{target}', criteria={criteria!r}): {bare!r} is neither a "
            "criteria keyword nor a column in the frame."
        ]
        kw_hit = difflib.get_close_matches(bare.lower(), sorted(_FLAG_CRITERIA_KEYWORDS), n=1)
        if kw_hit:
            parts.append(f"Did you mean criteria='{kw_hit[0]}'?")
        col_hit = difflib.get_close_matches(bare, schema_names, n=1)
        if col_hit:
            parts.append(f"Or the column '{col_hit[0]}'?")
        parts.append(f"Valid keywords: {sorted(_FLAG_CRITERIA_KEYWORDS)}.")
        raise DerivationError(" ".join(parts))

    def _flag_ranked(
        self,
        target,
        *,
        criteria_lower,
        grps,
        order_cols,
        where_expr,
        flag_all,
        flag_value,
        false_lit,
    ) -> Self:
        """Handle first/last rank-based flag criteria (pure window exprs).

        The order is admiral's (``dplyr::arrange``): ascending on each key,
        a missing value last, then input order.  ``"first"`` takes the first
        record of that order and ``"last"`` the last one, so a record with a
        missing key is the last record, and it is first only when every
        candidate of the group misses that key.
        """
        if not order_cols:
            raise DerivationError(f"flag criteria='{criteria_lower}' requires order_by.")
        # "last" reads admiral's order backwards: descending, so missing values come first.
        descending = criteria_lower == "last"
        eligible = pl.lit(True) if where_expr is None else where_expr.fill_null(False)

        def ordered(expr: pl.Expr) -> pl.Expr:
            # is_null() before each key puts a missing value last: Polars 1.x ignores
            # nulls_last when a window order_by has more than one key.
            keys = [
                k
                for i, c in enumerate(order_cols)
                for k in (pl.col(c).is_null().alias(f"__null_{i}"), pl.col(c))
            ]
            return expr.over(
                grps,
                order_by=[*keys, pl.int_range(pl.len()).alias("__tie")],
                descending=descending,
            )

        if flag_all:
            # Every candidate whose keys equal the winner's, a missing value equal to a missing one.
            row_cond = eligible & pl.all_horizontal(
                pl.col(c).eq_missing(ordered(pl.col(c).filter(eligible).first()))
                for c in order_cols
            )
        else:
            # Records that fail `where` take no part; a tie goes to the last (first) input row.
            position = pl.int_range(pl.len())
            winner = pl.when(eligible).then(position).otherwise(None).min()
            row_cond = ordered((position == winner) & eligible)
        expr = pl.when(row_cond).then(pl.lit(flag_value)).otherwise(false_lit).alias(target)
        return self._chain(expr, verb="flag")

    def _flag_extreme(
        self,
        target,
        *,
        criteria_lower,
        grps,
        value_col,
        where_expr,
        flag_value,
        false_lit,
    ) -> Self:
        """Handle max/min value-based extreme flag criteria."""
        if not value_col:
            raise DerivationError(f"flag criteria='{criteria_lower}' requires value_col.")
        if where_expr is not None:
            masked_val = pl.when(where_expr).then(pl.col(value_col)).otherwise(pl.lit(None))
            agg_val = (
                masked_val.max().over(grps)
                if criteria_lower == "max"
                else masked_val.min().over(grps)
            )
            row_cond = where_expr & (pl.col(value_col) == agg_val)
        else:
            agg_val = (
                pl.col(value_col).max().over(grps)
                if criteria_lower == "max"
                else pl.col(value_col).min().over(grps)
            )
            row_cond = pl.col(value_col) == agg_val
        expr = pl.when(row_cond).then(pl.lit(flag_value)).otherwise(false_lit).alias(target)
        return self._chain(expr, verb="flag")

    def _flag_exists(
        self,
        target,
        *,
        grps,
        from_dataset,
        on,
        source_filter,
        flag_value,
        false_lit,
    ) -> Self:
        """Handle exists set-membership flag criteria."""
        if from_dataset is None or on is None:
            raise DerivationError("flag criteria='exists' requires from_dataset and on.")
        datasets = from_dataset if isinstance(from_dataset, list) else [from_dataset]
        key_frames: list[pl.DataFrame] = []
        for ds in datasets:
            filtered = ds
            if source_filter is not None:
                filtered = ds.filter(source_filter)
            key_frames.append(filtered.select(on).unique())
        all_keys = pl.concat(key_frames).unique()

        if len(on) == 1:
            is_member = pl.col(on[0]).is_in(all_keys[on[0]].implode(), nulls_equal=True)
        else:
            is_member = pl.struct(on).is_in(
                all_keys.select(pl.struct(on)).to_series().implode(), nulls_equal=True
            )
        expr = pl.when(is_member).then(pl.lit(flag_value)).otherwise(false_lit).alias(target)
        return self._chain(expr, verb="flag")

    def _flag_relative(
        self,
        target,
        *,
        criteria_lower,
        grps,
        order_cols,
        condition,
        inclusive,
        flag_no_ref_groups,
        flag_value,
        false_value,
    ) -> Self:
        """Handle before/after relative-to-landmark flag criteria (window exprs)."""
        if condition is None:
            raise DerivationError(f"flag criteria='{criteria_lower}' requires condition.")
        if not order_cols:
            raise DerivationError(f"flag criteria='{criteria_lower}' requires order_by.")

        pos = pl.int_range(pl.len()).over(grps, order_by=[pl.col(c) for c in order_cols])
        cond_bool = condition.cast(pl.Boolean)
        landmark = pl.when(cond_bool).then(pos).otherwise(None).min().over(grps)

        norm_false = pl.lit(false_value) if false_value else pl.lit(None)
        no_ref = pl.lit(flag_value) if flag_no_ref_groups else norm_false
        if criteria_lower == "before":
            flagged = (pos <= landmark) if inclusive else (pos < landmark)
        else:
            flagged = (pos >= landmark) if inclusive else (pos > landmark)

        expr = (
            pl.when(landmark.is_null())
            .then(no_ref)
            .when(flagged)
            .then(pl.lit(flag_value))
            .otherwise(norm_false)
            .alias(target)
        )
        return self._chain(expr, verb="flag")

    def _flag_temporal_exists(
        self,
        target,
        *,
        criteria_lower,
        from_dataset,
        on,
        order_cols,
        condition,
        source_filter,
        flag_value,
    ) -> Self:
        """Handle exists_after/exists_before via one aggregate join.

        "Any source record strictly after t" is equivalent to
        "max(source times) > t" (and symmetrically with min for
        exists_before), so a per-key aggregate left join replaces the
        former per-row scan.
        """
        if from_dataset is None or condition is None:
            raise DerivationError(
                f"flag criteria='{criteria_lower}' requires from_dataset and condition."
            )
        if on is None:
            raise DerivationError(f"flag criteria='{criteria_lower}' requires on.")

        src = from_dataset if isinstance(from_dataset, pl.DataFrame) else pl.concat(from_dataset)
        if source_filter is not None:
            src = src.filter(source_filter)

        if len(order_cols) > 1:
            raise VerbUsageError(
                f"flag criteria='{criteria_lower}' takes one order_by column, got "
                f"{order_cols}. Build one ordered key column first, for example "
                "pl.concat_str([pl.col('ADT').cast(pl.String), pl.col('ATM')]) or ADTM, "
                "and pass it as order_by."
            )
        if order_cols:
            time_col = order_cols[0]
        else:
            schema_names = self._lazy.collect_schema().names()
            common_time = [
                c
                for c in ["AVISITN", "ADY", "ADT", "ADTM"]
                if c in schema_names and c in src.columns
            ]
            if not common_time:
                raise DerivationError(
                    f"flag criteria='{criteria_lower}' requires order_by or a "
                    "common temporal column (AVISITN, ADY, ADT, ADTM)."
                )
            time_col = common_time[0]

        tmp = "__flag_src_time__"
        if criteria_lower == "exists_after":
            src_agg = src.group_by(on).agg(pl.col(time_col).max().alias(tmp))
            cmp = pl.col(tmp) > pl.col(time_col)
        else:
            src_agg = src.group_by(on).agg(pl.col(time_col).min().alias(tmp))
            cmp = pl.col(tmp) < pl.col(time_col)

        flag_expr = (
            pl.when(condition & cmp).then(pl.lit(flag_value)).otherwise(pl.lit(None)).alias(target)
        )
        lf = (
            self._lazy.join(
                src_agg.lazy(), on=on, how="left", maintain_order="left", nulls_equal=True
            )
            .with_columns(flag_expr)
            .drop(tmp)
        )
        return self._with_lazy(lf)

    def _flag_expression(
        self,
        target,
        *,
        criteria,
        where_expr,
        flag_value,
        false_lit,
    ) -> Self:
        """Handle direct expression-based flag criteria."""
        from fleet.sdtm.utils import parse_expression

        if isinstance(criteria, pl.Expr):
            row_cond = criteria
        else:
            row_cond = parse_expression(str(criteria), self._lazy.collect_schema())
        final_cond = (where_expr & row_cond) if where_expr is not None else row_cond
        expr = pl.when(final_cond).then(pl.lit(flag_value)).otherwise(false_lit).alias(target)
        return self._chain(expr, verb="flag")

    # ------------------------------------------------------------------ #
    # Criterion — CRITy / CRITyFL / CRITyFN triple-output                 #
    # ------------------------------------------------------------------ #

    def criterion(
        self,
        number: int,
        *,
        condition: pl.Expr,
        description: str | None = None,
        prefix: str = "CRIT",
    ) -> Self:
        """Derive criterion flag triple: CRITy, CRITyFL, CRITyFN.

        Produces three columns following CDISC ADaM conventions:

        - ``{prefix}{number}`` — the criterion description (constant string).
        - ``{prefix}{number}FL`` — ``"Y"`` if condition is met, ``"N"`` if not.
        - ``{prefix}{number}FN`` — ``1`` if met, ``0`` if not.

        When the condition is null (for example AVAL is missing), FL and FN are
        null, as admiral ``derive_vars_crit_flag()``. For a SAP rule "missing is
        not met", pass ``condition=(...).fill_null(False)``.

        References:
            admiral ``derive_vars_crit_flag(values_yn = TRUE,
            create_numeric_flag = TRUE)``; ADR-0033.

        Args:
            number: Criterion number (e.g. 1 → CRIT1, CRIT1FL, CRIT1FN).
            condition: Boolean Polars expression defining the criterion.
            description: Human-readable description stored in CRITy column.
                If ``None``, the column is still created with null values.
            prefix: Column name prefix (default ``"CRIT"``).

        Returns:
            Self: The namespace with three new columns appended; call
                ``.to_frame()`` to materialise.

        Examples:
            Flag records where AVAL >= 10::

                adlb = (
                    lb_df.adam
                    .criterion(1, condition=pl.col("AVAL") >= 10,
                               description="AVAL >= 10")
                    .to_frame()
                )
        """
        col_crit = f"{prefix}{number}"
        col_fl = f"{prefix}{number}FL"
        col_fn = f"{prefix}{number}FN"

        desc_expr = (
            pl.lit(description).alias(col_crit)
            if description is not None
            else pl.lit(None).cast(pl.String).alias(col_crit)
        )
        fl_expr = (
            pl.when(condition).then(pl.lit("Y")).when(~condition).then(pl.lit("N")).alias(col_fl)
        )
        fn_expr = pl.when(condition).then(pl.lit(1)).when(~condition).then(pl.lit(0)).alias(col_fn)

        return self._chain(desc_expr, fl_expr, fn_expr, verb="criterion")

flag

flag(
    target,
    *,
    criteria,
    by=None,
    order_by=None,
    value_col=None,
    where=None,
    from_dataset=None,
    on=None,
    source_filter=None,
    condition=None,
    inclusive=True,
    flag_no_ref_groups=True,
    flag_all=False,
    flag_value="Y",
    false_value=None
)

Set target to flag_value for records matching criteria.

Supports row-level boolean expressions and built-in shortcuts:

  • "first" / "last" — rank-based edge detection within groups.
  • "max" / "min" — value-based extreme within groups.
  • "exists" — set-membership from external dataset(s).
  • "before" / "after" — relative to a landmark condition.
  • "exists_after" / "exists_before" — temporal/self-join flag.

Parameters that are irrelevant to the selected criteria mode raise :class:~fleet.core.exceptions.VerbUsageError instead of being silently ignored. The flag_first / flag_last / flag_extreme / flag_exists / flag_relative wrappers expose each mode with only its own parameters.

Parameters:

Name Type Description Default
target str

Name of the output flag column.

required
criteria str | Expr

A Polars expression, or one of "first", "last", "max", "min", "exists", "before", "after", "exists_after", "exists_before".

required
by list[str] | None

Partition columns (default ["USUBJID"]).

None
order_by str | list[str] | None

Sort column(s) required for "first"/"last" and "before"/"after". On a tie among candidates, "last" takes the last input record and "first" the first (SAS LAST./FIRST.); add a sequence variable to remove the dependence on input order. For "first"/"last" a missing value sorts last in each key, as admiral (ADR-0020): "last" takes a record with a missing key, and "first" takes one only when every candidate misses it. SAS sorts a missing value first, so a QC program with PROC SORT differs on such a group. "exists_after"/"exists_before" take one column only; build one ordered key (ADTM) for date and time.

None
value_col str | None

Value column required for "max"/"min".

None
where str | Expr | None

Optional pre-filter — only matching rows are candidates; rows that fail it take no part, even on a tie.

None
from_dataset DataFrame | list[DataFrame] | None

External dataset(s) for "exists" and "exists_after"/"exists_before" criteria.

None
on list[str] | None

Join key columns for "exists" criteria.

None
source_filter Expr | None

Filter applied to from_dataset before key extraction or join.

None
condition Expr | None

Boolean expression identifying landmark rows for "before"/"after" or the current-row condition for "exists_after"/"exists_before".

None
inclusive bool

Whether the landmark row itself is included in the flag (for "before"/"after"). Default True.

True
flag_no_ref_groups bool

If False, groups without a landmark condition match get None instead of being flagged (for "before"/"after"). Default True.

True
flag_all bool

If True, all tied extreme values receive the flag (for "first"/"last"). Default False.

False
flag_value str

Value to assign when condition is met (default "Y").

'Y'
false_value str | None

Value to assign when condition is not met. Default None (null).

None

Returns:

Name Type Description
Self Self

The namespace with target appended; call .to_frame() to materialise.

Raises:

Type Description
VerbUsageError

When a parameter irrelevant to the selected criteria mode is passed.

DerivationError

When a mode-required parameter is missing, or a bare-identifier criteria matches neither a keyword nor a column.

References

admiral derive_var_extreme_flag (pharmaverse): the order of "first"/"last", a missing value last in each key (ADR-0020).

Examples:

First observation per group::

advs = (
    vs_raw.adam
    .flag("ABLFL", criteria="first", order_by="AVISITN",
          by=["USUBJID", "PARAMCD"])
    .to_frame()
)

Existence flag from external dataset::

adsl = (
    dm.adam.adsl
    .flag("VSEVALFL", criteria="exists",
          from_dataset=advs, on=["USUBJID"],
          source_filter=pl.col("AVISIT") == "BASELINE")
    .to_frame()
)

Relative flag — before first PD::

result = (
    response.adam
    .flag("ANL02FL", criteria="before",
          condition=pl.col("AVALC") == "PD",
          order_by="AVISITN", by=["USUBJID"],
          inclusive=True)
    .to_frame()
)

Population flag from the treatment start date (a population flag is never blank, so non-members get "N")::

adsl = (
    adsl.adam.adsl
    .flag("SAFFL", criteria=pl.col("TRTSDT").is_not_null(),
          false_value="N")
    .to_frame()
)
Source code in src/fleet/core/_flag_mixin.py
def flag(
    self,
    target: str,
    *,
    criteria: str | pl.Expr,
    by: list[str] | None = None,
    order_by: str | list[str] | None = None,
    value_col: str | None = None,
    where: str | pl.Expr | None = None,
    from_dataset: pl.DataFrame | list[pl.DataFrame] | None = None,
    on: list[str] | None = None,
    source_filter: pl.Expr | None = None,
    condition: pl.Expr | None = None,
    inclusive: bool = True,
    flag_no_ref_groups: bool = True,
    flag_all: bool = False,
    flag_value: str = "Y",
    false_value: str | None = None,
) -> Self:
    """Set *target* to *flag_value* for records matching *criteria*.

    Supports row-level boolean expressions and built-in shortcuts:

    - ``"first"`` / ``"last"`` — rank-based edge detection within groups.
    - ``"max"`` / ``"min"`` — value-based extreme within groups.
    - ``"exists"`` — set-membership from external dataset(s).
    - ``"before"`` / ``"after"`` — relative to a landmark condition.
    - ``"exists_after"`` / ``"exists_before"`` — temporal/self-join flag.

    Parameters that are irrelevant to the selected criteria mode
    raise :class:`~fleet.core.exceptions.VerbUsageError` instead of
    being silently ignored.  The ``flag_first`` / ``flag_last`` /
    ``flag_extreme`` / ``flag_exists`` / ``flag_relative`` wrappers
    expose each mode with only its own parameters.

    Args:
        target: Name of the output flag column.
        criteria: A Polars expression, or one of ``"first"``,
            ``"last"``, ``"max"``, ``"min"``, ``"exists"``,
            ``"before"``, ``"after"``, ``"exists_after"``,
            ``"exists_before"``.
        by: Partition columns (default ``["USUBJID"]``).
        order_by: Sort column(s) required for ``"first"``/``"last"``
            and ``"before"``/``"after"``.  On a tie among candidates,
            ``"last"`` takes the last input record and ``"first"`` the
            first (SAS ``LAST.``/``FIRST.``); add a sequence variable
            to remove the dependence on input order.  For
            ``"first"``/``"last"`` a missing value sorts last in each
            key, as admiral (ADR-0020): ``"last"`` takes a record with a
            missing key, and ``"first"`` takes one only when every
            candidate misses it.  SAS sorts a missing value first, so a
            QC program with PROC SORT differs on such a group.
            ``"exists_after"``/``"exists_before"`` take one column
            only; build one ordered key (ADTM) for date and time.
        value_col: Value column required for ``"max"``/``"min"``.
        where: Optional pre-filter — only matching rows are candidates;
            rows that fail it take no part, even on a tie.
        from_dataset: External dataset(s) for ``"exists"`` and
            ``"exists_after"``/``"exists_before"`` criteria.
        on: Join key columns for ``"exists"`` criteria.
        source_filter: Filter applied to *from_dataset* before key
            extraction or join.
        condition: Boolean expression identifying landmark rows for
            ``"before"``/``"after"`` or the current-row condition for
            ``"exists_after"``/``"exists_before"``.
        inclusive: Whether the landmark row itself is included in the
            flag (for ``"before"``/``"after"``). Default ``True``.
        flag_no_ref_groups: If ``False``, groups without a landmark
            condition match get ``None`` instead of being flagged
            (for ``"before"``/``"after"``). Default ``True``.
        flag_all: If ``True``, all tied extreme values receive the
            flag (for ``"first"``/``"last"``). Default ``False``.
        flag_value: Value to assign when condition is met (default
            ``"Y"``).
        false_value: Value to assign when condition is not met.
            Default ``None`` (null).

    Returns:
        Self: The namespace with *target* appended; call
            ``.to_frame()`` to materialise.

    Raises:
        VerbUsageError: When a parameter irrelevant to the selected
            criteria mode is passed.
        DerivationError: When a mode-required parameter is missing,
            or a bare-identifier *criteria* matches neither a
            keyword nor a column.

    References:
        admiral ``derive_var_extreme_flag`` (pharmaverse): the order of
        ``"first"``/``"last"``, a missing value last in each key (ADR-0020).

    Examples:
        First observation per group::

            advs = (
                vs_raw.adam
                .flag("ABLFL", criteria="first", order_by="AVISITN",
                      by=["USUBJID", "PARAMCD"])
                .to_frame()
            )

        Existence flag from external dataset::

            adsl = (
                dm.adam.adsl
                .flag("VSEVALFL", criteria="exists",
                      from_dataset=advs, on=["USUBJID"],
                      source_filter=pl.col("AVISIT") == "BASELINE")
                .to_frame()
            )

        Relative flag — before first PD::

            result = (
                response.adam
                .flag("ANL02FL", criteria="before",
                      condition=pl.col("AVALC") == "PD",
                      order_by="AVISITN", by=["USUBJID"],
                      inclusive=True)
                .to_frame()
            )

        Population flag from the treatment start date (a population
        flag is never blank, so non-members get ``"N"``)::

            adsl = (
                adsl.adam.adsl
                .flag("SAFFL", criteria=pl.col("TRTSDT").is_not_null(),
                      false_value="N")
                .to_frame()
            )
    """
    from fleet.sdtm.utils import parse_expression

    grps = by or ["USUBJID"]
    order_cols: list[str] | None = None
    if order_by is not None:
        order_cols = [order_by] if isinstance(order_by, str) else list(order_by)

    criteria_lower = criteria.lower() if isinstance(criteria, str) else None
    mode = criteria_lower if criteria_lower in _FLAG_CRITERIA_KEYWORDS else "expression"
    if mode == "expression":
        # Keyword typos ("frist") must surface as a did-you-mean error
        # before any parameter validation blames the wrong thing.
        self._check_flag_criteria_typo(target, criteria)
    self._validate_flag_params(
        target,
        criteria,
        mode,
        {
            "order_by": order_by,
            "value_col": value_col,
            "where": where,
            "from_dataset": from_dataset,
            "on": on,
            "source_filter": source_filter,
            "condition": condition,
            "inclusive": inclusive,
            "flag_no_ref_groups": flag_no_ref_groups,
            "flag_all": flag_all,
            "false_value": false_value,
        },
    )

    where_expr: pl.Expr | None = None
    if where is not None:
        where_expr = where if isinstance(where, pl.Expr) else parse_expression(str(where))

    false_lit = pl.lit(false_value) if false_value is not None else pl.lit(None)

    if mode in ("first", "last"):
        return self._flag_ranked(
            target,
            criteria_lower=mode,
            grps=grps,
            order_cols=order_cols,
            where_expr=where_expr,
            flag_all=flag_all,
            flag_value=flag_value,
            false_lit=false_lit,
        )
    elif mode in ("max", "min"):
        return self._flag_extreme(
            target,
            criteria_lower=mode,
            grps=grps,
            value_col=value_col,
            where_expr=where_expr,
            flag_value=flag_value,
            false_lit=false_lit,
        )
    elif mode == "exists":
        return self._flag_exists(
            target,
            grps=grps,
            from_dataset=from_dataset,
            on=on,
            source_filter=source_filter,
            flag_value=flag_value,
            false_lit=false_lit,
        )
    elif mode in ("before", "after"):
        return self._flag_relative(
            target,
            criteria_lower=mode,
            grps=grps,
            order_cols=order_cols,
            condition=condition,
            inclusive=inclusive,
            flag_no_ref_groups=flag_no_ref_groups,
            flag_value=flag_value,
            false_value=false_value,
        )
    elif mode in ("exists_after", "exists_before"):
        return self._flag_temporal_exists(
            target,
            criteria_lower=mode,
            from_dataset=from_dataset,
            on=on,
            order_cols=order_cols,
            condition=condition,
            source_filter=source_filter,
            flag_value=flag_value,
        )
    else:
        return self._flag_expression(
            target,
            criteria=criteria,
            where_expr=where_expr,
            flag_value=flag_value,
            false_lit=false_lit,
        )

flag_first

flag_first(
    target,
    *,
    order_by,
    by=None,
    where=None,
    flag_all=False,
    flag_value="Y",
    false_value=None
)

Flag the first record per group (flag(criteria="first")).

Parameters:

Name Type Description Default
target str

Name of the output flag column.

required
order_by str | list[str]

Sort column(s) defining "first" within each group. A tie goes to the first input record. A missing value sorts last, as admiral: it is first only when every candidate misses it.

required
by list[str] | None

Partition columns (default ["USUBJID"]).

None
where str | Expr | None

Optional pre-filter — only matching rows are candidates.

None
flag_all bool

Flag every tied extreme record instead of one.

False
flag_value str

Value assigned to flagged records (default "Y").

'Y'
false_value str | None

Value assigned otherwise (default null).

None

Returns:

Name Type Description
Self Self

The namespace with target appended; call .to_frame() to materialise.

Examples:

Baseline flag on the first visit per subject/parameter::

advs = (
    vs_raw.adam
    .flag_first("ABLFL", order_by="AVISITN",
                by=["USUBJID", "PARAMCD"])
    .to_frame()
)
Source code in src/fleet/core/_flag_mixin.py
def flag_first(
    self,
    target: str,
    *,
    order_by: str | list[str],
    by: list[str] | None = None,
    where: str | pl.Expr | None = None,
    flag_all: bool = False,
    flag_value: str = "Y",
    false_value: str | None = None,
) -> Self:
    """Flag the first record per group (``flag(criteria="first")``).

    Args:
        target: Name of the output flag column.
        order_by: Sort column(s) defining "first" within each group.
            A tie goes to the first input record.  A missing value sorts
            last, as admiral: it is first only when every candidate
            misses it.
        by: Partition columns (default ``["USUBJID"]``).
        where: Optional pre-filter — only matching rows are candidates.
        flag_all: Flag every tied extreme record instead of one.
        flag_value: Value assigned to flagged records (default ``"Y"``).
        false_value: Value assigned otherwise (default null).

    Returns:
        Self: The namespace with *target* appended; call
            ``.to_frame()`` to materialise.

    Examples:
        Baseline flag on the first visit per subject/parameter::

            advs = (
                vs_raw.adam
                .flag_first("ABLFL", order_by="AVISITN",
                            by=["USUBJID", "PARAMCD"])
                .to_frame()
            )
    """
    return self.flag(
        target,
        criteria="first",
        order_by=order_by,
        by=by,
        where=where,
        flag_all=flag_all,
        flag_value=flag_value,
        false_value=false_value,
    )

flag_last

flag_last(
    target,
    *,
    order_by,
    by=None,
    where=None,
    flag_all=False,
    flag_value="Y",
    false_value=None
)

Flag the last record per group (flag(criteria="last")).

Parameters:

Name Type Description Default
target str

Name of the output flag column.

required
order_by str | list[str]

Sort column(s) defining "last" within each group. A tie goes to the last input record. A missing value sorts last, as admiral, so a record with a missing key is last.

required
by list[str] | None

Partition columns (default ["USUBJID"]).

None
where str | Expr | None

Optional pre-filter — only matching rows are candidates.

None
flag_all bool

Flag every tied extreme record instead of one.

False
flag_value str

Value assigned to flagged records (default "Y").

'Y'
false_value str | None

Value assigned otherwise (default null).

None

Returns:

Name Type Description
Self Self

The namespace with target appended; call .to_frame() to materialise.

Examples:

Last analysis-eligible record per subject/parameter::

advs = (
    vs_raw.adam
    .flag_last("ANL01FL", order_by="ADT",
               by=["USUBJID", "PARAMCD"])
    .to_frame()
)
Source code in src/fleet/core/_flag_mixin.py
def flag_last(
    self,
    target: str,
    *,
    order_by: str | list[str],
    by: list[str] | None = None,
    where: str | pl.Expr | None = None,
    flag_all: bool = False,
    flag_value: str = "Y",
    false_value: str | None = None,
) -> Self:
    """Flag the last record per group (``flag(criteria="last")``).

    Args:
        target: Name of the output flag column.
        order_by: Sort column(s) defining "last" within each group.
            A tie goes to the last input record.  A missing value sorts
            last, as admiral, so a record with a missing key is last.
        by: Partition columns (default ``["USUBJID"]``).
        where: Optional pre-filter — only matching rows are candidates.
        flag_all: Flag every tied extreme record instead of one.
        flag_value: Value assigned to flagged records (default ``"Y"``).
        false_value: Value assigned otherwise (default null).

    Returns:
        Self: The namespace with *target* appended; call
            ``.to_frame()`` to materialise.

    Examples:
        Last analysis-eligible record per subject/parameter::

            advs = (
                vs_raw.adam
                .flag_last("ANL01FL", order_by="ADT",
                           by=["USUBJID", "PARAMCD"])
                .to_frame()
            )
    """
    return self.flag(
        target,
        criteria="last",
        order_by=order_by,
        by=by,
        where=where,
        flag_all=flag_all,
        flag_value=flag_value,
        false_value=false_value,
    )

flag_extreme

flag_extreme(
    target,
    *,
    value_col,
    mode="max",
    by=None,
    where=None,
    flag_value="Y",
    false_value=None
)

Flag the extreme-valued record(s) per group (criteria="max"/"min").

Parameters:

Name Type Description Default
target str

Name of the output flag column.

required
value_col str

Column whose extreme value is flagged.

required
mode Literal['max', 'min']

"max" (default) or "min".

'max'
by list[str] | None

Partition columns (default ["USUBJID"]).

None
where str | Expr | None

Optional pre-filter — only matching rows are candidates.

None
flag_value str

Value assigned to flagged records (default "Y").

'Y'
false_value str | None

Value assigned otherwise (default null).

None

Returns:

Name Type Description
Self Self

The namespace with target appended; call .to_frame() to materialise.

Examples:

Worst-severity record per subject and term::

adae = (
    ae_df.adam.occds
    .flag_extreme("ANL01FL", value_col="AESEVN",
                  by=["USUBJID", "AETERM"])
    .to_frame()
)
Source code in src/fleet/core/_flag_mixin.py
def flag_extreme(
    self,
    target: str,
    *,
    value_col: str,
    mode: Literal["max", "min"] = "max",
    by: list[str] | None = None,
    where: str | pl.Expr | None = None,
    flag_value: str = "Y",
    false_value: str | None = None,
) -> Self:
    """Flag the extreme-valued record(s) per group (``criteria="max"/"min"``).

    Args:
        target: Name of the output flag column.
        value_col: Column whose extreme value is flagged.
        mode: ``"max"`` (default) or ``"min"``.
        by: Partition columns (default ``["USUBJID"]``).
        where: Optional pre-filter — only matching rows are candidates.
        flag_value: Value assigned to flagged records (default ``"Y"``).
        false_value: Value assigned otherwise (default null).

    Returns:
        Self: The namespace with *target* appended; call
            ``.to_frame()`` to materialise.

    Examples:
        Worst-severity record per subject and term::

            adae = (
                ae_df.adam.occds
                .flag_extreme("ANL01FL", value_col="AESEVN",
                              by=["USUBJID", "AETERM"])
                .to_frame()
            )
    """
    return self.flag(
        target,
        criteria=mode,
        value_col=value_col,
        by=by,
        where=where,
        flag_value=flag_value,
        false_value=false_value,
    )

flag_exists

flag_exists(
    target,
    *,
    from_dataset,
    on,
    source_filter=None,
    flag_value="Y",
    false_value=None
)

Flag records with a match in external dataset(s) (criteria="exists").

Parameters:

Name Type Description Default
target str

Name of the output flag column.

required
from_dataset DataFrame | list[DataFrame]

External dataset(s) to look up keys in.

required
on list[str]

Join key columns.

required
source_filter Expr | None

Filter applied to from_dataset before key extraction.

None
flag_value str

Value assigned when a match exists (default "Y").

'Y'
false_value str | None

Value assigned otherwise (default null).

None

Returns:

Name Type Description
Self Self

The namespace with target appended; call .to_frame() to materialise.

Examples:

Subjects with a baseline vital-signs record::

adsl = (
    dm.adam.adsl
    .flag_exists("VSEVALFL", from_dataset=advs,
                 on=["USUBJID"],
                 source_filter=pl.col("AVISIT") == "BASELINE")
    .to_frame()
)
Source code in src/fleet/core/_flag_mixin.py
def flag_exists(
    self,
    target: str,
    *,
    from_dataset: pl.DataFrame | list[pl.DataFrame],
    on: list[str],
    source_filter: pl.Expr | None = None,
    flag_value: str = "Y",
    false_value: str | None = None,
) -> Self:
    """Flag records with a match in external dataset(s) (``criteria="exists"``).

    Args:
        target: Name of the output flag column.
        from_dataset: External dataset(s) to look up keys in.
        on: Join key columns.
        source_filter: Filter applied to *from_dataset* before key
            extraction.
        flag_value: Value assigned when a match exists (default ``"Y"``).
        false_value: Value assigned otherwise (default null).

    Returns:
        Self: The namespace with *target* appended; call
            ``.to_frame()`` to materialise.

    Examples:
        Subjects with a baseline vital-signs record::

            adsl = (
                dm.adam.adsl
                .flag_exists("VSEVALFL", from_dataset=advs,
                             on=["USUBJID"],
                             source_filter=pl.col("AVISIT") == "BASELINE")
                .to_frame()
            )
    """
    return self.flag(
        target,
        criteria="exists",
        from_dataset=from_dataset,
        on=on,
        source_filter=source_filter,
        flag_value=flag_value,
        false_value=false_value,
    )

flag_relative

flag_relative(
    target,
    *,
    when,
    condition,
    order_by,
    by=None,
    inclusive=True,
    flag_no_ref_groups=True,
    flag_value="Y",
    false_value=None
)

Flag records before/after a landmark (criteria="before"/"after").

Parameters:

Name Type Description Default
target str

Name of the output flag column.

required
when Literal['before', 'after']

"before" or "after" the first landmark record.

required
condition Expr

Boolean expression identifying landmark rows.

required
order_by str | list[str]

Sort column(s) defining record order within groups.

required
by list[str] | None

Partition columns (default ["USUBJID"]).

None
inclusive bool

Whether the landmark row itself is flagged.

True
flag_no_ref_groups bool

If True (default), every record of a group with no landmark gets flag_value, in both directions, as admiral derive_var_relative_flag. Pass False for a post-event flag, so that such a group gets false_value.

True
flag_value str

Value assigned to flagged records (default "Y").

'Y'
false_value str | None

Value assigned otherwise (default null).

None

Returns:

Name Type Description
Self Self

The namespace with target appended; call .to_frame() to materialise.

Examples:

Analysis flag for records up to first disease progression::

adrs = (
    rs_df.adam
    .flag_relative("ANL02FL", when="before",
                   condition=pl.col("AVALC") == "PD",
                   order_by="AVISITN", by=["USUBJID"])
    .to_frame()
)
Source code in src/fleet/core/_flag_mixin.py
def flag_relative(
    self,
    target: str,
    *,
    when: Literal["before", "after"],
    condition: pl.Expr,
    order_by: str | list[str],
    by: list[str] | None = None,
    inclusive: bool = True,
    flag_no_ref_groups: bool = True,
    flag_value: str = "Y",
    false_value: str | None = None,
) -> Self:
    """Flag records before/after a landmark (``criteria="before"/"after"``).

    Args:
        target: Name of the output flag column.
        when: ``"before"`` or ``"after"`` the first landmark record.
        condition: Boolean expression identifying landmark rows.
        order_by: Sort column(s) defining record order within groups.
        by: Partition columns (default ``["USUBJID"]``).
        inclusive: Whether the landmark row itself is flagged.
        flag_no_ref_groups: If ``True`` (default), every record of a
            group with no landmark gets *flag_value*, in both
            directions, as admiral ``derive_var_relative_flag``.  Pass
            ``False`` for a post-event flag, so that such a group gets
            *false_value*.
        flag_value: Value assigned to flagged records (default ``"Y"``).
        false_value: Value assigned otherwise (default null).

    Returns:
        Self: The namespace with *target* appended; call
            ``.to_frame()`` to materialise.

    Examples:
        Analysis flag for records up to first disease progression::

            adrs = (
                rs_df.adam
                .flag_relative("ANL02FL", when="before",
                               condition=pl.col("AVALC") == "PD",
                               order_by="AVISITN", by=["USUBJID"])
                .to_frame()
            )
    """
    return self.flag(
        target,
        criteria=when,
        condition=condition,
        order_by=order_by,
        by=by,
        inclusive=inclusive,
        flag_no_ref_groups=flag_no_ref_groups,
        flag_value=flag_value,
        false_value=false_value,
    )

criterion

criterion(
    number, *, condition, description=None, prefix="CRIT"
)

Derive criterion flag triple: CRITy, CRITyFL, CRITyFN.

Produces three columns following CDISC ADaM conventions:

  • {prefix}{number} — the criterion description (constant string).
  • {prefix}{number}FL — "Y" if condition is met, "N" if not.
  • {prefix}{number}FN — 1 if met, 0 if not.

When the condition is null (for example AVAL is missing), FL and FN are null, as admiral derive_vars_crit_flag(). For a SAP rule "missing is not met", pass condition=(...).fill_null(False).

References

admiral derive_vars_crit_flag(values_yn = TRUE, create_numeric_flag = TRUE); ADR-0033.

Parameters:

Name Type Description Default
number int

Criterion number (e.g. 1 → CRIT1, CRIT1FL, CRIT1FN).

required
condition Expr

Boolean Polars expression defining the criterion.

required
description str | None

Human-readable description stored in CRITy column. If None, the column is still created with null values.

None
prefix str

Column name prefix (default "CRIT").

'CRIT'

Returns:

Name Type Description
Self Self

The namespace with three new columns appended; call .to_frame() to materialise.

Examples:

Flag records where AVAL >= 10::

adlb = (
    lb_df.adam
    .criterion(1, condition=pl.col("AVAL") >= 10,
               description="AVAL >= 10")
    .to_frame()
)
Source code in src/fleet/core/_flag_mixin.py
def criterion(
    self,
    number: int,
    *,
    condition: pl.Expr,
    description: str | None = None,
    prefix: str = "CRIT",
) -> Self:
    """Derive criterion flag triple: CRITy, CRITyFL, CRITyFN.

    Produces three columns following CDISC ADaM conventions:

    - ``{prefix}{number}`` — the criterion description (constant string).
    - ``{prefix}{number}FL`` — ``"Y"`` if condition is met, ``"N"`` if not.
    - ``{prefix}{number}FN`` — ``1`` if met, ``0`` if not.

    When the condition is null (for example AVAL is missing), FL and FN are
    null, as admiral ``derive_vars_crit_flag()``. For a SAP rule "missing is
    not met", pass ``condition=(...).fill_null(False)``.

    References:
        admiral ``derive_vars_crit_flag(values_yn = TRUE,
        create_numeric_flag = TRUE)``; ADR-0033.

    Args:
        number: Criterion number (e.g. 1 → CRIT1, CRIT1FL, CRIT1FN).
        condition: Boolean Polars expression defining the criterion.
        description: Human-readable description stored in CRITy column.
            If ``None``, the column is still created with null values.
        prefix: Column name prefix (default ``"CRIT"``).

    Returns:
        Self: The namespace with three new columns appended; call
            ``.to_frame()`` to materialise.

    Examples:
        Flag records where AVAL >= 10::

            adlb = (
                lb_df.adam
                .criterion(1, condition=pl.col("AVAL") >= 10,
                           description="AVAL >= 10")
                .to_frame()
            )
    """
    col_crit = f"{prefix}{number}"
    col_fl = f"{prefix}{number}FL"
    col_fn = f"{prefix}{number}FN"

    desc_expr = (
        pl.lit(description).alias(col_crit)
        if description is not None
        else pl.lit(None).cast(pl.String).alias(col_crit)
    )
    fl_expr = (
        pl.when(condition).then(pl.lit("Y")).when(~condition).then(pl.lit("N")).alias(col_fl)
    )
    fn_expr = pl.when(condition).then(pl.lit(1)).when(~condition).then(pl.lit(0)).alias(col_fn)

    return self._chain(desc_expr, fl_expr, fn_expr, verb="criterion")

options: show_root_heading: false heading_level: 3 members_order: source filters: ["!^_"]