Skip to content

Define-XML

Fleet generates and validates CDISC Define-XML 2.1 documents from define.yaml specs.

DefineSpecGenerator

fleet.define_xml.DefineSpecGenerator

Generate Define-XML 2.1 from a simplified Fleet define YAML spec.

Parameters

define_yaml_path: Path to a simplified define YAML file that conforms to define_spec_schema.json. validate_schema: When True (default), validates the YAML against the JSON schema before generating and raises ValueError on schema violations. validate_xml: When True (default), validates the generated document against the vendored Define-XML 2.1 XSDs and raises :class:~fleet.core.exceptions.SpecError rather than emitting a non-conformant define.xml. Set to False to write the file anyway (e.g. to inspect what failed). enrich_methods: When True (default), every Derived variable with a comment: or a derivation: gets a MethodDef. This imports the spec's derivations_module (study Python code); False imports nothing. import_study_code: When False, the generator imports no study code even with enrich_methods: a callable: derivation is described by its comment: or its dotted path. fleet check uses this, so a received study runs no code on a read-only command. strict: When True, refuse (SpecError) a define with gaps: a Derived variable with no method text, a text, integer or float variable with no Length, a float with no SignificantDigits. When False (default), the gaps are named in one UserWarning and the file is written (ADR-0018).

Source code in src/fleet/define_xml/spec_generator.py
 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
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
class DefineSpecGenerator:
    """Generate Define-XML 2.1 from a simplified Fleet define YAML spec.

    Parameters
    ----------
    define_yaml_path:
        Path to a simplified define YAML file that conforms to
        ``define_spec_schema.json``.
    validate_schema:
        When *True* (default), validates the YAML against the JSON schema
        before generating and raises ``ValueError`` on schema violations.
    validate_xml:
        When *True* (default), validates the generated document against the
        vendored Define-XML 2.1 XSDs and raises
        :class:`~fleet.core.exceptions.SpecError` rather than emitting a
        non-conformant define.xml.  Set to ``False`` to write the file
        anyway (e.g. to inspect what failed).
    enrich_methods:
        When *True* (default), every Derived variable with a ``comment:``
        or a ``derivation:`` gets a MethodDef.  This imports the spec's
        ``derivations_module`` (study Python code); *False* imports nothing.
    import_study_code:
        When *False*, the generator imports no study code even with
        *enrich_methods*: a ``callable:`` derivation is described by its
        ``comment:`` or its dotted path.  ``fleet check`` uses this, so a
        received study runs no code on a read-only command.
    strict:
        When *True*, refuse (``SpecError``) a define with gaps: a Derived
        variable with no method text, a text, integer or float variable
        with no Length, a float with no SignificantDigits.  When *False*
        (default), the gaps are named in one ``UserWarning`` and the file
        is written (ADR-0018).
    """

    def __init__(
        self,
        define_yaml_path: str | Path,
        *,
        validate_schema: bool = True,
        validate_xml: bool = True,
        enrich_methods: bool = True,
        import_study_code: bool = True,
        strict: bool = False,
    ) -> None:
        self._path = Path(define_yaml_path)
        self._data: dict[str, Any] = load_spec_yaml(self._path.read_text(encoding="utf-8"))
        self._check_spec_version()
        self._enrich_methods = enrich_methods
        self._import_study_code = import_study_code
        self._strict = strict
        self._validate_xml = validate_xml
        #: "DATASET.VARIABLE: reason" for each define gap of the last build.
        self._gaps: list[str] = []
        #: (dataset, variable) pairs whose methods live at value level.
        self._vlm_parents: set[tuple[str, str]] = set()
        # Populated via _register_method; rendered into MethodDef elements at
        # the end of MetaDataVersion.
        self._method_defs: dict[str, dict[str, str]] = {}
        # ItemDef OID → ValueListDef OID (populated by _build_value_level;
        # consumed by _build_item_def to emit def:ValueListRef).
        self._value_list_refs: dict[str, str] = {}
        if validate_schema:
            self._validate()
        #: Why a qualifier cannot move to SUPP--; _build_odm refuses the define.
        self._qualifier_problems: list[str] = self._move_qualifiers_to_supp()
        # Resolve the CRF page map once (merges external page_map with
        # inline crf_pages; inline takes precedence).
        self._page_map: dict[str, dict[str, Any]] = self._load_page_map()

    # ------------------------------------------------------------------ #
    # Public API                                                           #
    # ------------------------------------------------------------------ #

    def generate(
        self,
        output_path: str | Path,
        *,
        html_preview: bool = True,
        xsl_path: str | Path | None = None,
    ) -> None:
        """Write a Define-XML 2.1 document to *output_path*.

        Parameters
        ----------
        output_path:
            Destination path for the ``.xml`` file.
        html_preview:
            When ``True`` (default), also write an HTML preview by applying
            the CDISC ``define2-1.xsl`` stylesheet via lxml.  The HTML file
            is written alongside the XML with a ``_preview.html`` suffix
            (e.g. ``define_sdtm.xml`` → ``define_sdtm_preview.html``).
        xsl_path:
            Path to the ``define2-1.xsl`` stylesheet.  Defaults to
            ``define2-1.xsl`` in the same directory as *output_path*, which
            is the standard layout used by Fleet.
        """
        root = self._build_odm()
        xml_str = self._serialise(root)
        out = Path(output_path)
        out.parent.mkdir(parents=True, exist_ok=True)
        out.write_text(xml_str, encoding="utf-8")
        print(f"Define-XML generated: {out}")

        if html_preview:
            self._write_html_preview(out, xsl_path)

    def _write_html_preview(
        self,
        xml_path: Path,
        xsl_path: str | Path | None,
    ) -> None:
        """Apply the define2-1.xsl transform and write an HTML preview file.

        The stylesheet often comes with a received define package, so it
        runs with no file or network access.  A stylesheet that cannot run
        skips the preview; the Define-XML is already written.
        """
        resolved_xsl = Path(xsl_path) if xsl_path else xml_path.parent / "define2-1.xsl"

        if not resolved_xsl.exists():
            print(
                f"HTML preview skipped: XSL stylesheet not found at '{resolved_xsl}'. "
                "Place define2-1.xsl in the same directory as the XML output, "
                "or pass xsl_path= explicitly."
            )
            return

        parser = lxml_etree.XMLParser(resolve_entities=False, no_network=True)
        try:
            xml_doc = lxml_etree.parse(str(xml_path), parser)  # noqa: S320 — entities off
            xsl_doc = lxml_etree.parse(str(resolved_xsl), parser)  # noqa: S320 — entities off
            transform = lxml_etree.XSLT(
                xsl_doc, access_control=lxml_etree.XSLTAccessControl.DENY_ALL
            )
            html_doc = transform(xml_doc)
        except (lxml_etree.XSLTError, lxml_etree.XMLSyntaxError) as exc:
            print(f"HTML preview skipped: {resolved_xsl} cannot run: {exc}")
            return

        html_path = xml_path.with_name(xml_path.stem + "_preview.html")
        html_path.write_bytes(lxml_etree.tostring(html_doc, pretty_print=True, method="html"))
        print(f"HTML preview generated: {html_path}")

    def to_xml_string(self) -> str:
        """Return the Define-XML as a formatted string without writing a file."""
        return self._serialise(self._build_odm())

    def _serialise(self, root: ET.Element) -> str:
        """Format *root* and, unless disabled, validate before returning.

        Two layers, same gate: XSD validation (structure, element order,
        enumerations) and the semantic lint (reviewer-facing conformance
        — see :func:`fleet.define_xml.semantic_checks.semantic_errors`).
        A document that fails either never ships silently.
        """
        xml_str = self._to_pretty_xml(root)
        if not self._validate_xml:
            return xml_str

        from fleet.core.exceptions import SpecError
        from fleet.define_xml.semantic_checks import semantic_errors
        from fleet.define_xml.xsd import validate_define_xml

        errors = [f"schema: {e}" for e in validate_define_xml(xml_str)]
        errors += [f"conformance: {e}" for e in semantic_errors(xml_str)]
        if errors:
            shown = "\n  ".join(errors[:10])
            more = f"\n  ... and {len(errors) - 10} more" if len(errors) > 10 else ""
            raise SpecError(
                f"{self._path}: generated Define-XML failed Define-XML 2.1 "
                f"validation ({len(errors)} error(s)):\n  {shown}{more}\n"
                "Correct define.yaml and generate again. From Python, "
                "DefineSpecGenerator(..., validate_xml=False) writes the file anyway."
            )
        return xml_str

    # ------------------------------------------------------------------ #
    # CRF page map                                                         #
    # ------------------------------------------------------------------ #

    def _load_page_map(self) -> dict[str, dict[str, Any]]:
        """Build a merged CRF page map from external file and inline values.

        Returns a dict keyed by ``"DOMAIN.VARIABLE"`` (value level:
        ``"DOMAIN.VARIABLE.<where values>"``) whose values are page
        references in the dict form; a page string or number becomes
        ``{"pages": "7"}``.  Inline ``crf_pages`` take precedence over
        entries in the external ``page_map`` file.  A declared page that
        cannot reach the Define-XML raises or warns: it is never lost
        silently.
        """
        merged: dict[str, dict[str, Any]] = {}
        known = self._page_map_keys()

        # Layer 3: external page_map YAML
        page_map_path = (self._get_acrf_config() or {}).get("page_map")
        if page_map_path:
            resolved = (self._path.parent / page_map_path).resolve()
            if not resolved.is_file():
                raise SpecError(
                    f"{self._path}: annotated_crf page_map {page_map_path} does not exist "
                    f"(looked for {resolved})."
                )
            raw = yaml.safe_load(resolved.read_text(encoding="utf-8"))
            if not isinstance(raw, dict):
                raise SpecError(
                    f"{resolved}: a page map is a mapping of DATASET.VARIABLE to pages, "
                    f"not {type(raw).__name__}."
                )
            for key, value in raw.items():
                merged[str(key)] = self._page_ref_value(value, f"{resolved}: {key}")
            unknown = sorted(k for k in merged if k not in known)
            if unknown:
                shown = ", ".join(unknown[:10]) + (" ..." if len(unknown) > 10 else "")
                warnings.warn(
                    f"{resolved}: {len(unknown)} page map key(s) match no variable of "
                    f"{self._path.name}: {shown}. Their pages are not in the Define-XML.",
                    UserWarning,
                    stacklevel=3,
                )

        # Layer 1 / 2: inline crf_pages (overrides external)
        for key, var in known.items():
            if var.get("crf_pages") is not None:
                merged[key] = self._page_ref_value(var["crf_pages"], key)

        if not self._get_acrf_config():
            lost = [key for key, ref in merged.items() if not ref.get("doc")]
            if lost:
                warnings.warn(
                    f"{self._path}: {', '.join(lost)} declare crf_pages, but "
                    "study.documents has no annotated_crf. Their pages are not in the "
                    "Define-XML. Add study.documents.annotated_crf.",
                    UserWarning,
                    stacklevel=3,
                )
        return merged

    def _page_map_keys(self) -> dict[str, dict[str, Any]]:
        """Map each page map key of the spec to its variable entry."""
        keys: dict[str, dict[str, Any]] = {}
        for ds in self._data.get("datasets", []):
            ds_name = ds["name"]
            for var in ds.get("variables", []):
                keys[f"{ds_name}.{var['name']}"] = var
            for entry in ds.get("value_level") or []:
                vl_key = "_".join(self._normalise_where(ds_name, entry)[2])
                for var in entry.get("variables", []):
                    keys[f"{ds_name}.{var['name']}.{vl_key}"] = var
        return keys

    def _page_ref_value(self, value: Any, where: str) -> dict[str, Any]:
        """Normalise one page reference to the dict form (a YAML ``7`` is page "7")."""
        if isinstance(value, (str, int)) and not isinstance(value, bool):
            return {"pages": str(value)}
        if isinstance(value, dict):
            return {
                k: str(v) if k in ("pages", "first_page", "last_page") else v
                for k, v in value.items()
            }
        raise SpecError(
            f"{where}: a CRF page reference is a page string such as '7 8' or a mapping "
            f"with pages:, not {type(value).__name__}."
        )

    def _get_acrf_config(self) -> dict[str, str] | None:
        """Return the annotated CRF document config, or None if absent."""
        docs = self._data.get("study", {}).get("documents", {})
        return docs.get("annotated_crf")

    def _acrf_leaf_id(self) -> str:
        return "LF.acrf"

    # ------------------------------------------------------------------ #
    # Schema validation                                                    #
    # ------------------------------------------------------------------ #

    def _check_spec_version(self) -> None:
        """Raise ``SpecError`` when the spec declares an unknown future version."""
        from fleet.core._verb_mixin import SUPPORTED_SPEC_VERSION

        version = self._data.get("fleet_spec_version")
        if version is not None and version != SUPPORTED_SPEC_VERSION:
            raise SpecError(
                f"{self._path}: unsupported fleet_spec_version {version!r}. "
                f"This Fleet version supports fleet_spec_version {SUPPORTED_SPEC_VERSION}."
            )

    def _validate(self) -> None:
        from fleet.core.exceptions import SpecSchemaError

        schema = json.loads(_SCHEMA_PATH.read_text(encoding="utf-8"))
        validator = jsonschema.Draft202012Validator(schema)
        errors = list(validator.iter_errors(self._data))
        if not errors:
            return
        empty = [
            e.json_path[2:]
            for e in errors
            if e.json_path in ("$.study.description", "$.study.originator")
            and e.validator == "minLength"
        ]
        lines = [f"  - {e.json_path}: {e.message}" for e in errors if e.json_path[2:] not in empty][
            :5
        ]
        if empty:
            lines.insert(
                0,
                f"  - {' and '.join(empty)} {'is' if len(empty) == 1 else 'are'} empty. "
                "Write the text in this file, or create the study with "
                "`fleet new --description ... --company ...`.",
            )
        msgs = "\n".join(lines)
        raise SpecSchemaError(f"{self._path}: define YAML failed schema validation:\n{msgs}")

    def _validate_codelist_refs(self) -> None:
        """Fail loudly on ``codelist:`` references to undeclared codelists.

        Every ``CodeListRef`` the generated Define-XML would emit must
        point at a ``CodeList`` element declared in this spec's
        ``codelists:`` section — a dangling OID renders a define that
        asserts conformance to nothing.

        Raises:
            SpecError: Naming each offending dataset/variable and listing
                the declared codelist OIDs.
        """
        declared = {cl["oid"] for cl in self._data.get("codelists", [])}
        dangling: list[str] = []
        for ds in self._data.get("datasets", []):
            variables = list(ds.get("variables", []))
            for entry in ds.get("value_level", []) or []:
                variables.extend(entry.get("variables", []))
            for var in variables:
                oid = var.get("codelist")
                if oid and oid not in declared:
                    dangling.append(f"{ds['name']}.{var['name']} → '{oid}'")
        if dangling:
            raise SpecError(
                f"{self._path}: CodeListRef to undeclared codelist(s): "
                f"{'; '.join(dangling)}. Declared codelist OIDs: "
                f"{sorted(declared) or '(none)'}. Add the codelist to the "
                f"spec's `codelists:` section or fix the reference."
            )
        standards = self._declared_standards()
        unknown = [
            f"{cl['oid']} → '{cl['standard_oid']}'"
            for cl in self._data.get("codelists", [])
            if cl.get("standard_oid") and cl["standard_oid"] not in standards
        ]
        if unknown:
            raise SpecError(
                f"{self._path}: codelist standard_oid names no declared standard: "
                f"{'; '.join(unknown)}. Declared standards: {sorted(standards)}. Set "
                "study.ct_version (STD.CT) or study.adam_ct_version (STD.CT.ADAM)."
            )
        empty = [
            cl["oid"]
            for cl in self._data.get("codelists", [])
            if not cl.get("items") and not cl.get("external")
        ]
        if empty:
            raise SpecError(
                f"{self._path}: codelist(s) with no terms: {', '.join(empty)}. A Define-XML "
                "CodeList needs its terms. Run: fleet init ct (it writes the terms of the "
                "pinned CT package into this file), or add items: by hand."
            )

    def _declared_standards(self) -> set[str]:
        """The def:Standard OIDs this define declares."""
        study = self._data["study"]
        declared = {_STANDARD_OIDS.get(study["standard"], f"STD.{study['standard']}")}
        if study.get("ct_version"):
            declared.add(_CT_OID)
        if study.get("adam_ct_version"):
            declared.add(_ADAM_CT_OID)
        return declared

    def leaf_hrefs(self) -> dict[str, str]:
        """Return the ``def:leaf`` href of each dataset, by dataset name.

        Returns:
            dict[str, str]: Dataset name to href, as the Define-XML writes it.

        Examples:
            Check that each leaf names a file that exists::

                gen = DefineSpecGenerator("metadata/sdtm/define.yaml")
                missing = [h for h in gen.leaf_hrefs().values() if not Path("data/sdtm", h).exists()]
        """
        return {ds["name"]: self._leaf_href(ds) for ds in self._data.get("datasets") or []}

    def _leaf_href(self, ds: dict[str, Any]) -> str:
        """Resolve the ``def:leaf`` href for a dataset.

        Uses the per-dataset ``output:`` path verbatim when given;
        otherwise ``{name.lower()}{ext}`` where the extension follows the
        per-dataset or spec-level ``output_format:`` key (default
        ``parquet`` → ``.parquet``).
        """
        output = ds.get("output")
        if output:
            return str(output)
        fmt = ds.get("output_format") or self._data.get("output_format") or "parquet"
        ext = _FORMAT_EXT.get(fmt, ".parquet")
        return f"{ds['name'].lower()}{ext}"

    # ------------------------------------------------------------------ #
    # ODM root                                                             #
    # ------------------------------------------------------------------ #

    def _warn_predecessor_candidates(self) -> None:
        """Warn on ADaM ``algorithm: source`` variables marked Collected.

        A column copied verbatim from an upstream dataset is a
        ``Predecessor`` in Define-XML 2.1 terms; ``Collected`` claims it
        was captured on the CRF.  Output is not changed (origin stays an
        explicit spec decision) — the warning surfaces the likely miss
        where the author can fix it.
        """
        if self._data.get("study", {}).get("standard") != "ADAMIG":
            return
        hits = [
            f"{ds['name']}.{var['name']}"
            for ds in self._data.get("datasets", [])
            for var in ds.get("variables", [])
            if _is_plain_copy(var.get("derivation") or {}) and var.get("origin") == "Collected"
        ]
        if hits:
            warnings.warn(
                f"{self._path}: {', '.join(hits)} use 'algorithm: assign' (a copy) with "
                "origin 'Collected' — a variable carried from an upstream dataset "
                "should declare origin: Predecessor with "
                "predecessor: '<DATASET>.<VARIABLE>'.",
                stacklevel=2,
            )

    def _validate_variable_refs(self) -> None:
        """Fail loudly on keys and value-level names that are not dataset variables.

        A key, a value-level variable or a where-clause variable that the
        dataset does not declare gives a Define-XML reference to an
        ItemDef that does not exist, or a key that is dropped.

        Raises:
            SpecError: Naming each DATASET.VARIABLE and where it is used.
        """
        problems: list[str] = []
        for ds in self._data.get("datasets", []):
            ds_name = ds["name"]
            names = {var["name"] for var in ds.get("variables", [])}
            for key in ds.get("keys") or []:
                if key not in names:
                    problems.append(f"{ds_name}.{key} (keys)")
            for entry in ds.get("value_level") or []:
                wc_var = self._normalise_where(ds_name, entry)[1]
                if wc_var not in names:
                    problems.append(f"{ds_name}.{wc_var} (value_level where)")
                for var in entry.get("variables", []):
                    if var["name"] not in names:
                        problems.append(f"{ds_name}.{var['name']} (value_level variable)")
        if problems:
            raise SpecError(
                f"{self._path}: not declared in the variables: of their dataset: "
                f"{'; '.join(dict.fromkeys(problems))}. Declare each variable, or remove "
                "the reference."
            )

    def _move_qualifiers_to_supp(self) -> list[str]:
        """Describe each SDTMIG 3.4 (or earlier) qualifier in a generated SUPP-- dataset.

        Up to SDTMIG 3.4, a non-standard variable goes to SUPP--, not to
        the parent domain.  The parent dataset of the spec may keep it for
        the derivation (``fleet run`` writes it to ``SUPP<domain>``).  The
        define then leaves it out of the parent and adds ``SUPP<domain>``,
        with value-level metadata on QVAL by QNAM.

        References:
            SDTMIG 3.4, section 8.4 (Relating Non-Standard Variable Values
            to a Parent Domain); ADR-0041; ADR-0044.

        Returns:
            list[str]: Why a qualifier cannot move, one line per problem.
                Empty when every qualifier moved.
        """
        study = self._data.get("study") or {}
        if study.get("standard") != "SDTMIG":
            return []
        version = tuple(int(p) for p in str(study.get("standard_version")).split(".")[:2])
        if version > (3, 4):
            return []
        datasets: list[dict[str, Any]] = self._data.get("datasets") or []
        declared = {ds["name"] for ds in datasets}
        problems: list[str] = []
        result: list[dict[str, Any]] = []
        for ds in datasets:
            qualifiers = [] if ds["name"].startswith("SUPP") else ds.get("variables", [])
            qualifiers = [v for v in qualifiers if _is_qualifier(v)]
            result.append(ds)
            if not qualifiers:
                continue
            found = _supp_problems(ds, qualifiers, declared)
            if found:
                problems.extend(f"SUPP{ds['name']}: {p}" for p in found)
                continue
            result[-1] = {**ds, "variables": [v for v in ds["variables"] if not _is_qualifier(v)]}
            result.append(_supp_dataset(ds, qualifiers))
        self._data["datasets"] = result
        return problems

    def _refuse_parent_qualifiers(self) -> None:
        """Refuse a define with a qualifier that cannot move to SUPP--.

        References:
            SDTMIG 3.4, section 8.4; ADR-0041; ADR-0044.

        Raises:
            SpecError: Naming each problem and the fix.
        """
        if self._qualifier_problems:
            raise SpecError(
                f"{self._path}: a role qualifier (non-standard) variable cannot move to its "
                f"SUPP-- dataset: {'; '.join(self._qualifier_problems)}. SDTMIG "
                f"{self._data['study']['standard_version']} does not allow it in the parent "
                "domain. Correct the spec, then generate the Define-XML again."
            )

    def _build_odm(self) -> ET.Element:
        self._refuse_parent_qualifiers()
        self._validate_codelist_refs()
        self._validate_variable_refs()
        self._warn_predecessor_candidates()
        # Import the spec's derivations_module so short-name `callable:`
        # derivations are registered before their MethodDefs are resolved
        # (from_spec does this too).  Study code runs only to write methods.
        if self._enrich_methods and self._import_study_code:
            _import_derivations_module(load_define_spec(self._path), source="define-xml")
        self._gaps = []
        study = self._data["study"]
        std_oid = _STANDARD_OIDS.get(study["standard"], f"STD.{study['standard']}")
        ts = datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%S")
        file_oid = f"CDISC.{study['id']}.1.Define-XML_2.1.0"
        attribs: dict[str, str] = {
            "xmlns": _NS_ODM,
            "xmlns:xlink": _NS_XLINK,
            "xmlns:def": _NS_DEF,
            "ODMVersion": "1.3.2",
            "FileOID": file_oid,
            "FileType": "Snapshot",
            "CreationDateTime": ts,
            "Originator": study["originator"],
            "SourceSystem": study.get("source_system", "Fleet"),
            "SourceSystemVersion": study.get("source_system_version", "0.1.0"),
            "def:Context": "Submission",
        }
        odm = ET.Element("ODM", attrib=attribs)
        odm.append(self._build_study(study, std_oid))
        self._report_gaps()
        return odm

    def _report_gaps(self) -> None:
        """Refuse the define in strict mode, else name its gaps in one warning."""
        if not self._gaps:
            return
        shown = "\n  ".join(self._gaps[:25])
        more = f"\n  ... and {len(self._gaps) - 25} more" if len(self._gaps) > 25 else ""
        text = (
            f"{self._path}: {len(self._gaps)} Define-XML gap(s):\n  {shown}{more}\n"
            "Define-XML 2.1 requires a MethodOID on each Derived ItemRef, Length on "
            "text, integer and float, and SignificantDigits on float."
        )
        if self._strict:
            raise SpecError(text)
        warnings.warn(
            text + " The file is written; fleet define-xml --strict refuses it.",
            UserWarning,
            stacklevel=4,
        )

    # ------------------------------------------------------------------ #
    # Study / MetaDataVersion                                              #
    # ------------------------------------------------------------------ #

    def _build_study(self, study: dict[str, Any], std_oid: str) -> ET.Element:
        elem = ET.Element("Study", {"OID": study_oid(study["id"])})
        gv = ET.SubElement(elem, "GlobalVariables")
        ET.SubElement(gv, "StudyName").text = study["name"]
        ET.SubElement(gv, "StudyDescription").text = study["description"].strip()
        ET.SubElement(gv, "ProtocolName").text = study["protocol_name"]
        elem.append(self._build_metadata_version(study, std_oid))
        return elem

    def _build_metadata_version(self, study: dict[str, Any], std_oid: str) -> ET.Element:
        ig = study["standard"]
        mdv_oid = metadata_version_oid(study["id"], ig, study["standard_version"])
        attribs = {
            "OID": mdv_oid,
            "Name": f"{study['id']} {ig} Data Definitions",
            "Description": f"Dataset metadata for {study['id']} {ig} datasets",
            "def:DefineVersion": "2.1.0",
        }
        mdv = ET.Element("MetaDataVersion", attrib=attribs)

        # Standards list — must be wrapped in def:Standards per Define-XML 2.1 spec
        stds_container = ET.SubElement(mdv, "def:Standards")
        stds_container.append(
            self._build_standard(
                std_oid,
                _STANDARD_NAMES.get(study["standard"], study["standard"]),
                "IG",
                study["standard_version"],
            )
        )
        if study.get("ct_version"):
            stds_container.append(
                self._build_standard(
                    _CT_OID,
                    "CDISC/NCI",
                    "CT",
                    study["ct_version"],
                    publishing_set="SEND" if study["standard"] == "SENDIG" else "SDTM",
                )
            )
        if study.get("adam_ct_version"):
            stds_container.append(
                self._build_standard(
                    _ADAM_CT_OID,
                    "CDISC/NCI",
                    "CT",
                    study["adam_ct_version"],
                    publishing_set="ADaM",
                )
            )

        # AnnotatedCRF — emitted when study.documents.annotated_crf is set
        acrf_cfg = self._get_acrf_config()
        if acrf_cfg:
            acrf_elem = ET.SubElement(mdv, "def:AnnotatedCRF")
            ET.SubElement(acrf_elem, "def:DocumentRef", {"leafID": self._acrf_leaf_id()})

        # SupplementalDoc — additional supporting documents
        docs = self._data.get("study", {}).get("documents", {})
        supp_docs = docs.get("supplemental_docs", [])
        if supp_docs:
            supp_elem = ET.SubElement(mdv, "def:SupplementalDoc")
            for sd in supp_docs:
                ET.SubElement(supp_elem, "def:DocumentRef", {"leafID": sd["id"]})

        datasets: list[dict[str, Any]] = self._data.get("datasets", [])
        self._vlm_parents = {
            (ds["name"], var["name"])
            for ds in datasets
            for entry in ds.get("value_level") or []
            for var in entry.get("variables", [])
        }

        # Value-level metadata (def:ValueListDef / def:WhereClauseDef) —
        # placed before ItemGroupDefs per the Define-XML 2.1 element order.
        # Must run before ItemDefs so def:ValueListRef wiring is known.
        vl_defs, wc_defs, vl_item_defs = self._build_value_level(datasets)
        mdv.extend(vl_defs)
        mdv.extend(wc_defs)

        # ItemGroupDefs (one per dataset)
        for ds in datasets:
            mdv.append(self._build_item_group_def(ds, study["id"]))

        # ItemDefs (collect all unique variables across datasets), then the
        # value-level ItemDefs referenced from the ValueListDefs.
        mdv.extend(self._build_all_item_defs(datasets))
        mdv.extend(vl_item_defs)

        # CodeLists
        for cl in self._data.get("codelists", []):
            mdv.append(self._build_codelist(cl))

        # MethodDefs (only populated when enrich_methods=True; lazily
        # registered by _build_item_def via _register_method).
        for method_oid in sorted(self._method_defs):
            mdv.append(self._build_method_def(method_oid, self._method_defs[method_oid]))

        # def:CommentDefs: the record selection of each dataset (row_steps, ADR-0034).
        for ds in datasets:
            if ds.get("row_steps"):
                comment = ET.Element("def:CommentDef", {"OID": f"COM.{ds['name']}.ROWS"})
                desc = ET.SubElement(comment, "Description")
                ET.SubElement(desc, "TranslatedText", {"xml:lang": "en"}).text = _row_steps_text(
                    ds["row_steps"]
                )
                mdv.append(comment)

        # Annotated CRF leaf
        if acrf_cfg:
            acrf_leaf = ET.Element(
                "def:leaf",
                {
                    "ID": self._acrf_leaf_id(),
                    "xlink:href": acrf_cfg["href"],
                },
            )
            ET.SubElement(acrf_leaf, "def:title").text = acrf_cfg.get(
                "title", "Annotated Case Report Form"
            )
            mdv.append(acrf_leaf)

        # Supplemental document leaves
        for sd in supp_docs:
            sd_leaf = ET.Element("def:leaf", {"ID": sd["id"], "xlink:href": sd["href"]})
            ET.SubElement(sd_leaf, "def:title").text = sd["title"]
            mdv.append(sd_leaf)

        return mdv

    # ------------------------------------------------------------------ #
    # Element builders                                                     #
    # ------------------------------------------------------------------ #

    @staticmethod
    def _build_standard(
        oid: str, name: str, kind: str, version: str, publishing_set: str | None = None
    ) -> ET.Element:
        attribs: dict[str, str] = {
            "OID": oid,
            "Name": name,
            "Type": kind,
            "Version": version,
            "Status": "Final",
        }
        if publishing_set:
            attribs["PublishingSet"] = publishing_set
        return ET.Element("def:Standard", attrib=attribs)

    def _build_item_group_def(self, ds: dict[str, Any], study_id: str) -> ET.Element:
        name = ds["name"]
        ig_oid = f"IG.{name}"
        leaf_id = f"LF.{name}"
        std_oid = _STANDARD_OIDS.get(self._data["study"]["standard"], "STD.IG")
        repeating = ds.get("repeating")
        if repeating is None:
            repeating = default_repeating(name)
        reference = ds.get("is_reference_data")
        if reference is None:
            reference = default_is_reference_data(name, ds.get("class"))
        # A SUPP-- dataset describes its parent domain (SUPPAE: Domain AE).
        domain = name[4:] if name.startswith("SUPP") and len(name) > 4 else name

        attribs: dict[str, str] = {
            "OID": ig_oid,
            "Name": name,
            "Repeating": "Yes" if repeating else "No",
            "IsReferenceData": "Yes" if reference else "No",
            "SASDatasetName": name,
            "Domain": domain,
            "def:Structure": ds["structure"],
            "Purpose": "Tabulation" if self._data["study"]["standard"] == "SDTMIG" else "Analysis",
            "def:StandardOID": std_oid,
            "def:ArchiveLocationID": leaf_id,
        }
        if ds.get("row_steps"):
            attribs["def:CommentOID"] = f"COM.{name}.ROWS"
        elem = ET.Element("ItemGroupDef", attrib=attribs)

        desc = ET.SubElement(elem, "Description")
        ET.SubElement(desc, "TranslatedText", {"xml:lang": "en"}).text = ds["label"]

        key_vars: set[str] = set(ds.get("keys", []))
        key_order: dict[str, int] = {v: i + 1 for i, v in enumerate(ds.get("keys", []))}

        for order, var in enumerate(ds["variables"], start=1):
            var_name = var["name"]
            item_oid = self._item_oid(name, var_name)
            ref_attrs: dict[str, str] = {
                "ItemOID": item_oid,
                "OrderNumber": str(order),
                "Mandatory": "Yes" if var.get("mandatory") else "No",
            }
            if var_name in key_vars:
                ref_attrs["KeySequence"] = str(key_order[var_name])
            if var.get("sdtm_role"):
                ref_attrs["Role"] = var["sdtm_role"]
            # Define-XML 2.1 places MethodOID on the ItemRef (usage site),
            # not on the ItemDef — and only Derived-origin variables carry
            # a computational method (a collected column rename is not a
            # MethodDef).  A parent with value-level metadata is judged there.
            if (
                var.get("origin", "Derived") == "Derived"
                and (name, var_name) not in self._vlm_parents
            ):
                method_oid = self._method_ref(
                    var, dataset=name, target=var_name, label=f"{name}.{var_name}"
                )
                if method_oid:
                    ref_attrs["MethodOID"] = method_oid
            ET.SubElement(elem, "ItemRef", attrib=ref_attrs)

        # Define-XML 2.1 orders ItemGroupDef children Description → ItemRef*
        # → def:Class → def:leaf; emitting Class earlier invalidates the file.
        if ds.get("class"):
            ET.SubElement(elem, "def:Class", {"Name": ds["class"]})

        # Leaf reference — href follows the actual export format
        href = self._leaf_href(ds)
        leaf = ET.SubElement(elem, "def:leaf", {"ID": leaf_id, "xlink:href": href})
        ET.SubElement(leaf, "def:title").text = href

        return elem

    def _build_all_item_defs(self, datasets: list[dict[str, Any]]) -> list[ET.Element]:
        """Build one ItemDef per dataset variable, from that dataset's metadata."""
        seen: dict[str, ET.Element] = {}  # item_oid → element
        result: list[ET.Element] = []
        for ds in datasets:
            for var in ds["variables"]:
                item_oid = self._item_oid(ds["name"], var["name"])
                if item_oid not in seen:
                    elem = self._build_item_def(item_oid, var, ds["name"])
                    seen[item_oid] = elem
                    result.append(elem)
        return result

    def _build_item_def(
        self,
        item_oid: str,
        var: dict[str, Any],
        dataset_name: str,
        *,
        vl_key: str | None = None,
        label: str | None = None,
    ) -> ET.Element:
        attribs: dict[str, str] = {
            "OID": item_oid,
            "Name": var["name"],
            "DataType": _TYPE_TO_ODM[var["type"]],
            "SASFieldName": var["name"],
        }
        where = label or f"{dataset_name}.{var['name']}"
        if var.get("length") is not None:
            attribs["Length"] = str(var["length"])
        elif var["type"] in ("text", "integer", "float"):
            self._gaps.append(f"{where}: no Length (required on text, integer and float)")
        if var.get("significant_digits") is not None:
            attribs["SignificantDigits"] = str(var["significant_digits"])
        elif var["type"] == "float":
            self._gaps.append(f"{where}: no SignificantDigits (required on float)")

        elem = ET.Element("ItemDef", attrib=attribs)

        desc = ET.SubElement(elem, "Description")
        ET.SubElement(desc, "TranslatedText", {"xml:lang": "en"}).text = var["label"]

        if var.get("codelist"):
            ET.SubElement(elem, "CodeListRef", {"CodeListOID": var["codelist"]})

        origin_type = var.get("origin", "Derived")
        origin_attrs = {"Type": origin_type}
        # Define-XML 2.1 pairs a collected value with its source; CRF data
        # (the common case) is Investigator-provided unless stated.
        if origin_type == "Collected":
            origin_attrs["Source"] = var.get("origin_source") or "Investigator"
        orig_elem = ET.SubElement(elem, "def:Origin", origin_attrs)

        # Origin description — study-authored text only, never Fleet
        # docstrings.  Precedence: a Predecessor names its
        # DATASET.VARIABLE source; a comment: that already became this
        # variable's MethodDef description is not repeated here; a
        # value-level parent points reviewers at the VLM section; a
        # CRF-collected variable with no page reference still names its
        # source document.  (MethodDefs are registered before ItemDefs
        # are built — see _build_metadata_version ordering.)
        vl_oid = self._value_list_refs.get(item_oid)
        comment = var.get("comment") or ""
        if origin_type == "Predecessor":
            desc_text = var.get("predecessor") or comment
        elif self._method_oid(dataset_name, var["name"], vl_key) in self._method_defs:
            desc_text = ""
        else:
            desc_text = comment
        if not desc_text and vl_oid:
            desc_text = "See Value Level Metadata"
        crf_ref = self._crf_page_ref(dataset_name, var["name"], vl_key)
        if (
            not desc_text
            and origin_type == "Collected"
            and origin_attrs["Source"] == "Investigator"
            and crf_ref is None
        ):
            desc_text = "Case Report Form"
        if desc_text:
            orig_desc = ET.SubElement(orig_elem, "Description")
            ET.SubElement(orig_desc, "TranslatedText", {"xml:lang": "en"}).text = desc_text

        # CRF page references — emit DocumentRef/PDFPageRef inside Origin
        if crf_ref is not None:
            self._append_crf_page_ref(orig_elem, *crf_ref)

        # Value-level metadata: point the parent ItemDef at its ValueListDef
        if vl_oid:
            ET.SubElement(elem, "def:ValueListRef", {"ValueListOID": vl_oid})

        return elem

    def _method_ref(
        self,
        var: dict[str, Any],
        *,
        dataset: str,
        target: str,
        label: str,
        vl_key: str | None = None,
    ) -> str | None:
        """Return the MethodOID of one Derived variable, or record why it has none."""
        if not self._enrich_methods:
            self._gaps.append(f"{label}: no MethodDef (enrich_methods=False)")
            return None
        derivation = var.get("derivation") or {}
        if not derivation and not var.get("comment"):
            self._gaps.append(f"{label}: no method text (add a comment: or a derivation: block)")
            return None
        method_oid, problem = self._register_method(
            derivation,
            dataset=dataset,
            target=target,
            comment=var.get("comment"),
            vl_key=vl_key,
            codelist=var.get("codelist"),
        )
        if problem:
            self._gaps.append(f"{label}: {problem}")
        return method_oid

    @staticmethod
    def _method_oid(dataset: str, target: str, vl_key: str | None = None) -> str:
        """Per-variable MethodDef OID: ``MT.<dataset>.<target>[.<vl_key>]``."""
        oid = f"MT.{dataset}.{target}"
        return f"{oid}.{vl_key}" if vl_key else oid

    @staticmethod
    def _resolve_callable(callable_path: str) -> tuple[str | None, str | None]:
        """Summary + dotted path for a ``callable:`` derivation.

        Prefers a registered ``Derivation`` object's own docstring and
        ``dotted_path``; falls back to importing the dotted path.  This
        is *study-authored* text (unlike Fleet verb docstrings, which are
        never used in a define).
        """
        try:
            from fleet.adam.transforms import get_transform

            obj = get_transform(callable_path)
            if hasattr(obj, "dotted_path"):
                return (docstring_summary(obj.fn.__doc__), obj.dotted_path)
        except Exception:
            pass
        return resolve_callable_docstring(callable_path)

    def _register_method(
        self,
        derivation: dict[str, Any],
        *,
        dataset: str,
        target: str,
        comment: str | None = None,
        vl_key: str | None = None,
        codelist: str | None = None,
    ) -> tuple[str | None, str | None]:
        """Register the MethodDef for one derived variable; return its OID and a problem.

        One MethodDef per derived variable, named ``Algorithm for
        <target>`` — never Fleet's internal algorithm id.  Description
        precedence: the spec ``comment:``, then the study callable's
        docstring (``callable:`` escape hatch), then the registry's
        submission-facing template / synthesised text
        (:func:`fleet.core.spec_registry.render_method_text`).  The OID is
        ``None`` when no reviewer-facing text can be produced — the
        variable then ships without a MethodDef rather than with API
        prose.  The problem names what the define reviewer must fix (a
        callable that does not import is a problem even with a comment).
        """
        callable_path = derivation.get("callable")
        algorithm = str(derivation.get("algorithm") or "")
        description = (comment or "").strip()
        context = "Python/Fleet"
        expression = ""
        problem: str | None = None

        if callable_path and algorithm in ("", "derivation") and not self._import_study_code:
            # No study import: the comment, or the dotted path, describes it.
            description = description or f"Study derivation {callable_path}."
            expression = str(callable_path)
            context = "Python"
        elif callable_path and algorithm in ("", "derivation"):
            summary, dotted = self._resolve_callable(str(callable_path))
            if summary is None and dotted is None:
                problem = f"callable {callable_path} does not import"
            elif summary is None and not description:
                problem = f"callable {callable_path} has no docstring"
            description = description or _strip_rest_markup(summary or "")
            expression = dotted or ""
            context = "Python"
        elif algorithm:
            std = _REGISTRY_STANDARDS.get(self._data["study"]["standard"], "sdtm")
            # The variable's codelist: is the ct: of its assign (ADR-0008), so the
            # method text says "mapped to controlled terminology" when it applies.
            try:
                block = spec_registry.with_codelist(std, derivation, codelist)
            except ValueError:
                block = dict(derivation)
            params = {k: v for k, v in block.items() if k != "algorithm"}
            description = description or (
                spec_registry.render_method_text(std, algorithm, params, target=target) or ""
            )
            expression = (
                spec_registry.render_formal_expression(std, algorithm, params, target=target)
                or algorithm
            )

        if not description:
            return None, problem or "no method text (add a comment:)"

        method_oid = self._method_oid(dataset, target, vl_key)
        self._method_defs.setdefault(
            method_oid,
            {
                "name": f"Algorithm for {target}",
                "description": description,
                "expression": expression,
                "context": context,
            },
        )
        return method_oid, problem

    @staticmethod
    def _build_method_def(method_oid: str, info: dict[str, str]) -> ET.Element:
        """Render a Define-XML 2.1 ``MethodDef`` element.

        See CDISC Define-XML 2.1 §4.2.2 for the FormalExpression contract.
        FormalExpression is optional: a method described only in words
        (a ``comment:``) has none, as in the CDISC ADaM example define.
        """
        elem = ET.Element(
            "MethodDef",
            {"OID": method_oid, "Name": info["name"], "Type": "Computation"},
        )
        desc = ET.SubElement(elem, "Description")
        ET.SubElement(desc, "TranslatedText", {"xml:lang": "en"}).text = info["description"]
        if info["expression"]:
            formal = ET.SubElement(elem, "FormalExpression", {"Context": info["context"]})
            formal.text = info["expression"]
        return elem

    def _build_codelist(self, cl: dict[str, Any]) -> ET.Element:
        """Render one CodeList in the form its terms call for.

        Every term with a decode gives ``CodeListItem``; no term with a
        decode gives ``EnumeratedItem``; ``external:`` gives
        ``ExternalCodeList`` (MedDRA).  ``nci_code`` gives the NCI
        ``Alias``, ``extended: true`` marks a sponsor term.

        Raises:
            SpecError: When some terms have a decode and some do not.
        """
        attribs: dict[str, str] = {
            "OID": cl["oid"],
            "Name": cl["name"],
            "DataType": _TYPE_TO_ODM[cl["type"]],
        }
        standard = cl.get("standard_oid")
        if not standard and _CT_OID in self._declared_standards() and _NCI_CODE.match(cl["oid"]):
            standard = _CT_OID
        if standard:
            attribs["def:StandardOID"] = standard
        elem = ET.Element("CodeList", attrib=attribs)
        external = cl.get("external")
        if external:
            ET.SubElement(
                elem,
                "ExternalCodeList",
                {"Dictionary": external["dictionary"], "Version": str(external["version"])},
            )
        items = [] if external else cl.get("items", [])
        undecoded = [item["coded_value"] for item in items if not item.get("decode")]
        if undecoded and len(undecoded) < len(items):
            raise SpecError(
                f"{self._path}: codelist {cl['oid']} mixes terms with and without a decode "
                f"(term {undecoded[0]!r} has none). Give every term a decode "
                "(CodeListItem) or none (EnumeratedItem)."
            )
        tag = "EnumeratedItem" if undecoded else "CodeListItem"
        for item in items:
            item_attrs = {"CodedValue": item["coded_value"]}
            if item.get("extended"):
                item_attrs["def:ExtendedValue"] = "Yes"
            ci = ET.SubElement(elem, tag, item_attrs)
            if item.get("decode"):
                decode = ET.SubElement(ci, "Decode")
                ET.SubElement(decode, "TranslatedText", {"xml:lang": "en"}).text = item["decode"]
            if item.get("nci_code"):
                ET.SubElement(ci, "Alias", {"Context": "nci:ExtCodeID", "Name": item["nci_code"]})
        if cl.get("nci_code"):
            ET.SubElement(elem, "Alias", {"Context": "nci:ExtCodeID", "Name": cl["nci_code"]})
        return elem

    # ------------------------------------------------------------------ #
    # Value-level metadata (def:ValueListDef / def:WhereClauseDef)         #
    # ------------------------------------------------------------------ #

    @staticmethod
    def _normalise_where(ds_name: str, entry: dict[str, Any]) -> tuple[str, str, list[str]]:
        """Resolve a value-level entry's condition to (wc_oid, variable, values).

        ``param: SYSBP`` is sugar for ``where: {variable: PARAMCD,
        value: SYSBP}`` — the idiomatic BDS case.
        """
        if entry.get("param") is not None:
            wc_var, values = "PARAMCD", [str(entry["param"])]
        else:
            where = entry["where"]
            wc_var = where["variable"]
            raw = where["value"]
            values = [str(v) for v in raw] if isinstance(raw, list) else [str(raw)]
        key = "_".join(values)
        return f"WC.{ds_name}.{wc_var}.{key}", wc_var, values

    def _build_value_level(
        self, datasets: list[dict[str, Any]]
    ) -> tuple[list[ET.Element], list[ET.Element], list[ET.Element]]:
        """Build value-level metadata elements from ``value_level:`` specs.

        For each dataset entry ``{param|where, variables}``, emits:

        * one ``def:WhereClauseDef`` per condition (``RangeCheck`` with
          ``EQ`` for a single value, ``IN`` for a list);
        * per value-level variable, an ``ItemRef`` (with
          ``def:WhereClauseRef`` and, when method enrichment is on, a
          ``MethodOID``) inside that variable's ``def:ValueListDef``;
        * one ``ItemDef`` per (variable, condition) pair.

        Also populates ``self._value_list_refs`` so the parent ItemDefs
        emit their ``def:ValueListRef``.

        Returns:
            tuple: ``(value_list_defs, where_clause_defs, item_defs)``.
        """
        value_lists: dict[str, ET.Element] = {}  # VL OID → element
        vl_counters: dict[str, int] = {}
        where_defs: dict[str, ET.Element] = {}  # WC OID → element
        item_defs: list[ET.Element] = []

        for ds in datasets:
            ds_name = ds["name"]
            for entry in ds.get("value_level", []) or []:
                wc_oid, wc_var, values = self._normalise_where(ds_name, entry)

                if wc_oid not in where_defs:
                    wc_elem = ET.Element("def:WhereClauseDef", {"OID": wc_oid})
                    rc = ET.SubElement(
                        wc_elem,
                        "RangeCheck",
                        {
                            "Comparator": "EQ" if len(values) == 1 else "IN",
                            "SoftHard": "Soft",
                            "def:ItemOID": self._item_oid(ds_name, wc_var),
                        },
                    )
                    for value in values:
                        ET.SubElement(rc, "CheckValue").text = value
                    where_defs[wc_oid] = wc_elem

                for var in entry.get("variables", []):
                    var_name = var["name"]
                    parent_oid = self._item_oid(ds_name, var_name)
                    vl_oid = f"VL.{ds_name}.{var_name}"
                    self._value_list_refs[parent_oid] = vl_oid
                    if vl_oid not in value_lists:
                        value_lists[vl_oid] = ET.Element("def:ValueListDef", {"OID": vl_oid})
                        vl_counters[vl_oid] = 0

                    key = "_".join(values)
                    item_oid = f"IT.{ds_name}.{var_name}.{key}"
                    label = f"{ds_name}.{var_name} ({wc_var} = {', '.join(values)})"

                    vl_counters[vl_oid] += 1
                    ref_attrs: dict[str, str] = {
                        "ItemOID": item_oid,
                        "OrderNumber": str(vl_counters[vl_oid]),
                        "Mandatory": "Yes" if var.get("mandatory") else "No",
                    }
                    if var.get("origin", "Derived") == "Derived":
                        method_oid = self._method_ref(
                            var, dataset=ds_name, target=var_name, label=label, vl_key=key
                        )
                        if method_oid:
                            ref_attrs["MethodOID"] = method_oid
                    item_ref = ET.SubElement(value_lists[vl_oid], "ItemRef", ref_attrs)
                    ET.SubElement(item_ref, "def:WhereClauseRef", {"WhereClauseOID": wc_oid})
                    # Built after _register_method so the ItemDef knows its
                    # comment: was consumed by the MethodDef.
                    item_defs.append(
                        self._build_item_def(item_oid, var, ds_name, vl_key=key, label=label)
                    )

        return list(value_lists.values()), list(where_defs.values()), item_defs

    def _crf_page_ref(
        self, dataset_name: str, var_name: str, vl_key: str | None = None
    ) -> tuple[str, dict[str, Any]] | None:
        """Return the leaf ID and page reference of one variable, or None.

        A value-level item reads ``DATASET.VARIABLE.<where values>`` first,
        then its parent ``DATASET.VARIABLE``.  ``doc:`` names the href of
        the annotated CRF or of a supplemental document.

        Raises:
            SpecError: When ``doc:`` matches no declared document href.
        """
        key = f"{dataset_name}.{var_name}"
        crf_ref = self._page_map.get(f"{key}.{vl_key}") if vl_key else None
        if crf_ref is None:
            crf_ref = self._page_map.get(key)
        if crf_ref is None:
            return None
        acrf_cfg = self._get_acrf_config()
        doc_href = crf_ref.get("doc")
        if not doc_href:
            # No annotated CRF: _load_page_map warned that the page is lost.
            return (self._acrf_leaf_id(), crf_ref) if acrf_cfg else None
        if acrf_cfg and doc_href == acrf_cfg.get("href"):
            return self._acrf_leaf_id(), crf_ref
        docs = self._data.get("study", {}).get("documents", {})
        for sd in docs.get("supplemental_docs", []):
            if sd["href"] == doc_href:
                return sd["id"], crf_ref
        raise SpecError(
            f"{self._path}: {key} crf_pages doc {doc_href} matches no annotated_crf or "
            "supplemental_docs href. Declare the document under study.documents."
        )

    @staticmethod
    def _append_crf_page_ref(origin_elem: ET.Element, leaf_id: str, crf_ref: dict) -> None:
        """Append a ``def:DocumentRef`` with ``def:PDFPageRef`` to an Origin element."""
        doc_ref = ET.SubElement(origin_elem, "def:DocumentRef", {"leafID": leaf_id})
        pages = crf_ref.get("pages")
        first_page = crf_ref.get("first_page")
        last_page = crf_ref.get("last_page")
        if pages or first_page:
            pr_attrs: dict[str, str] = {"Type": crf_ref.get("type", "PhysicalRef")}
            if pages:
                pr_attrs["PageRefs"] = pages
            if first_page:
                pr_attrs["FirstPage"] = first_page
            if last_page:
                pr_attrs["LastPage"] = last_page
            ET.SubElement(doc_ref, "def:PDFPageRef", pr_attrs)

    # ------------------------------------------------------------------ #
    # Helpers                                                              #
    # ------------------------------------------------------------------ #

    _item_oid = staticmethod(item_oid)

    @staticmethod
    def _to_pretty_xml(root: ET.Element) -> str:
        raw = ET.tostring(root, encoding="unicode", method="xml")
        dom = xml.dom.minidom.parseString(raw)
        pretty = dom.toprettyxml(indent="  ", encoding="utf-8").decode("utf-8")
        lines = [ln for ln in pretty.split("\n") if ln.strip()]
        if lines and lines[0].startswith("<?xml"):
            lines.insert(1, '<?xml-stylesheet type="text/xsl" href="define2-1.xsl"?>')
        return "\n".join(lines)

generate

generate(output_path, *, html_preview=True, xsl_path=None)

Write a Define-XML 2.1 document to output_path.

Parameters

output_path: Destination path for the .xml file. html_preview: When True (default), also write an HTML preview by applying the CDISC define2-1.xsl stylesheet via lxml. The HTML file is written alongside the XML with a _preview.html suffix (e.g. define_sdtm.xml → define_sdtm_preview.html). xsl_path: Path to the define2-1.xsl stylesheet. Defaults to define2-1.xsl in the same directory as output_path, which is the standard layout used by Fleet.

Source code in src/fleet/define_xml/spec_generator.py
def generate(
    self,
    output_path: str | Path,
    *,
    html_preview: bool = True,
    xsl_path: str | Path | None = None,
) -> None:
    """Write a Define-XML 2.1 document to *output_path*.

    Parameters
    ----------
    output_path:
        Destination path for the ``.xml`` file.
    html_preview:
        When ``True`` (default), also write an HTML preview by applying
        the CDISC ``define2-1.xsl`` stylesheet via lxml.  The HTML file
        is written alongside the XML with a ``_preview.html`` suffix
        (e.g. ``define_sdtm.xml`` → ``define_sdtm_preview.html``).
    xsl_path:
        Path to the ``define2-1.xsl`` stylesheet.  Defaults to
        ``define2-1.xsl`` in the same directory as *output_path*, which
        is the standard layout used by Fleet.
    """
    root = self._build_odm()
    xml_str = self._serialise(root)
    out = Path(output_path)
    out.parent.mkdir(parents=True, exist_ok=True)
    out.write_text(xml_str, encoding="utf-8")
    print(f"Define-XML generated: {out}")

    if html_preview:
        self._write_html_preview(out, xsl_path)

to_xml_string

to_xml_string()

Return the Define-XML as a formatted string without writing a file.

Source code in src/fleet/define_xml/spec_generator.py
def to_xml_string(self) -> str:
    """Return the Define-XML as a formatted string without writing a file."""
    return self._serialise(self._build_odm())

leaf_hrefs

leaf_hrefs()

Return the def:leaf href of each dataset, by dataset name.

Returns:

Type Description
dict[str, str]

dict[str, str]: Dataset name to href, as the Define-XML writes it.

Examples:

Check that each leaf names a file that exists::

gen = DefineSpecGenerator("metadata/sdtm/define.yaml")
missing = [h for h in gen.leaf_hrefs().values() if not Path("data/sdtm", h).exists()]
Source code in src/fleet/define_xml/spec_generator.py
def leaf_hrefs(self) -> dict[str, str]:
    """Return the ``def:leaf`` href of each dataset, by dataset name.

    Returns:
        dict[str, str]: Dataset name to href, as the Define-XML writes it.

    Examples:
        Check that each leaf names a file that exists::

            gen = DefineSpecGenerator("metadata/sdtm/define.yaml")
            missing = [h for h in gen.leaf_hrefs().values() if not Path("data/sdtm", h).exists()]
    """
    return {ds["name"]: self._leaf_href(ds) for ds in self._data.get("datasets") or []}

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

Method definitions

DefineSpecGenerator emits one Define-XML 2.1 <MethodDef> per Derived variable (named Algorithm for <VARIABLE>), referenced from the variable's <ItemRef> via MethodOID. Variables with any other origin (Collected, Assigned, Protocol, Predecessor) never reference a method: a collected column is not a computation.

The <Description> is submission text, resolved as: the variable's comment: → the study callable's docstring (callable: derivations) → the algorithm registry's submission-facing template with the spec params filled in (fleet.core.spec_registry.render_method_text). Fleet verb docstrings are never emitted. <FormalExpression Context="Python/Fleet"> records the faithful call (dotted verb path + spec params), so identical specs produce identical text across Fleet versions. A method with a comment: only has no <FormalExpression>.

Define-XML gaps

Define-XML 2.1 requires a MethodOID on each Derived ItemRef, a Length on text, integer and float items, and SignificantDigits on float items. The generator names each item that misses one, for example DM.SAFFL: no method text (add a comment: or a derivation: block) or VS.AVAL (PARAMCD = SYSBP): no SignificantDigits (required on float).

  • By default it writes the document and gives one UserWarning with the list.
  • With strict=True (CLI: fleet define-xml --strict) it raises SpecError and writes nothing. fleet check runs the generator in strict mode.

significant_digits: sets SignificantDigits on a variable or on a value-level entry. The schema refuses it on a type other than float, and refuses length: on date and datetime.

Validation of generated documents

Every generated document is validated before it is written: structurally against the vendored CDISC ODM 1.3.2 + Define-XML 2.1 XSDs (validate_define_xml), and semantically by a reviewer-facing lint (semantic_errors) that rejects a MethodOID on a non-Derived variable, API markup in TranslatedText, algorithm ids as MethodDef names, and Predecessor origins that do not name a DATASET.VARIABLE. Pass validate_xml=False to bypass both (e.g. to inspect a failing document).

from fleet import DefineSpecGenerator

DefineSpecGenerator(
    "examples/cdiscpilot01/sdtm/define.yaml",
    strict=True,
).generate("outputs/define_sdtm.xml")

CLI equivalent:

uv run fleet define-xml \
  --spec examples/cdiscpilot01/sdtm/define.yaml \
  --output outputs/define_sdtm.xml \
  --strict

The derivation block accepts either form:

# Standard verb — resolves against fleet.sdtm / fleet.adam namespaces
derivation:
  algorithm: assign
  source: sex
  ct: C66731

# Study-specific callable — full dotted path importable at generation time
derivation:
  callable: examples.cdiscpilot01.adam.derivations.derive_aval

DatasetChecker

fleet.define_xml.DatasetChecker

Validate a pl.DataFrame against a simplified Fleet define YAML.

Parameters

define_yaml_path: Path to a define.yaml conforming to define_spec_schema.json. enabled: Master switch. When False all checks are skipped and check() returns an empty CheckResult immediately. check_columns: When True (default), verify column completeness (missing / extra). check_types: When True (default), verify Polars dtype compatibility. check_ct: When True (default), verify values of variables declaring a codelist: against the spec's inline codelists: items. Out-of-codelist values are errors. validate_schema: When True (default), validate the YAML against the JSON schema on load. Set to False to skip during tight inner loops.

Source code in src/fleet/define_xml/checker.py
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
class DatasetChecker:
    """Validate a ``pl.DataFrame`` against a simplified Fleet define YAML.

    Parameters
    ----------
    define_yaml_path:
        Path to a ``define.yaml`` conforming to ``define_spec_schema.json``.
    enabled:
        Master switch.  When *False* all checks are skipped and ``check()``
        returns an empty ``CheckResult`` immediately.
    check_columns:
        When *True* (default), verify column completeness (missing / extra).
    check_types:
        When *True* (default), verify Polars dtype compatibility.
    check_ct:
        When *True* (default), verify values of variables declaring a
        ``codelist:`` against the spec's inline ``codelists:`` items.
        Out-of-codelist values are errors.
    validate_schema:
        When *True* (default), validate the YAML against the JSON schema on
        load.  Set to *False* to skip during tight inner loops.
    """

    def __init__(
        self,
        define_yaml_path: str | Path,
        *,
        enabled: bool = True,
        check_columns: bool = True,
        check_types: bool = True,
        check_ct: bool = True,
        validate_schema: bool = True,
    ) -> None:
        self._enabled = enabled
        self._check_columns = check_columns
        self._check_types = check_types
        self._check_ct = check_ct

        path = Path(define_yaml_path)
        self._data: dict[str, Any] = load_spec_yaml(path.read_text(encoding="utf-8"))

        if validate_schema and enabled:
            self._validate_schema()

        # Build a lookup: dataset_name (upper) → dataset dict
        self._datasets: dict[str, dict[str, Any]] = {
            ds["name"].upper(): ds for ds in self._data.get("datasets", [])
        }
        # Inline codelists: oid → codelist dict (used by the CT check)
        self._codelists: dict[str, dict[str, Any]] = {
            cl["oid"]: cl for cl in self._data.get("codelists", [])
        }

    # ------------------------------------------------------------------ #
    # Public API                                                           #
    # ------------------------------------------------------------------ #

    def check(
        self,
        df: pl.DataFrame,
        dataset: str,
        *,
        strict: bool = True,
    ) -> CheckResult:
        """Check *df* against the define for *dataset*.

        Parameters
        ----------
        df:
            The materialised ``pl.DataFrame`` to check.
        dataset:
            Dataset name to look up in the define (e.g. ``"DM"``).
            Case-insensitive.
        strict:
            When ``True`` (default), ``core="Req"`` issues are errors.
            When ``False``, ``Req`` issues are downgraded to warnings so
            the pipeline can proceed despite missing required variables
            (e.g. during development or when source data is incomplete).

        Returns
        -------
        CheckResult
            Always returns a result — never raises unless you call
            ``result.raise_on_errors()``.
        """
        result = CheckResult(dataset=dataset.upper())

        if not self._enabled:
            return result

        ds_def = self._datasets.get(dataset.upper())
        if ds_def is None:
            result.errors.append(
                f"Dataset '{dataset}' not found in define. Available: {sorted(self._datasets)}"
            )
            return result

        # Build variable index (exclude private _-prefix names)
        vars_by_name: dict[str, dict[str, Any]] = {
            v["name"]: v for v in ds_def["variables"] if not v["name"].startswith("_")
        }

        # Labels always populated regardless of other flags
        result.labels = {name: v["label"] for name, v in vars_by_name.items()}

        # Actual DataFrame columns excluding private _-prefix columns
        actual_cols: set[str] = {c for c in df.columns if not c.startswith("_")}

        if self._check_columns:
            self._run_column_checks(result, vars_by_name, actual_cols, strict=strict)

        if self._check_types:
            self._run_type_checks(result, df, vars_by_name, actual_cols, strict=strict)

        if self._check_ct:
            self._run_ct_checks(result, df, vars_by_name, actual_cols)

        return result

    def datasets(self) -> list[str]:
        """Return the list of dataset names declared in the define."""
        return list(self._datasets)

    def labels(self, dataset: str) -> dict[str, str]:
        """Return the variable → label mapping for *dataset* without running full checks."""
        ds_def = self._datasets.get(dataset.upper())
        if ds_def is None:
            return {}
        return {v["name"]: v["label"] for v in ds_def["variables"] if not v["name"].startswith("_")}

    # ------------------------------------------------------------------ #
    # Check runners                                                        #
    # ------------------------------------------------------------------ #

    @staticmethod
    def _run_column_checks(
        result: CheckResult,
        vars_by_name: dict[str, dict[str, Any]],
        actual_cols: set[str],
        *,
        strict: bool = True,
    ) -> None:
        define_cols = set(vars_by_name)

        missing = define_cols - actual_cols
        for col in sorted(missing):
            var_def = vars_by_name[col]
            core = var_def.get("core", "")
            msg = f"Column '{col}' declared in define is missing from the DataFrame."
            result.missing_columns.append(col)
            _classify(
                result, msg, core=core, mandatory=var_def.get("mandatory", False), strict=strict
            )

        extra = actual_cols - define_cols
        for col in sorted(extra):
            msg = f"Column '{col}' is present in the DataFrame but not declared in the define."
            result.extra_columns.append(col)
            result.warnings.append(msg)

    @staticmethod
    def _run_type_checks(
        result: CheckResult,
        df: pl.DataFrame,
        vars_by_name: dict[str, dict[str, Any]],
        actual_cols: set[str],
        *,
        strict: bool = True,
    ) -> None:
        schema = df.schema
        for col_name, var_def in vars_by_name.items():
            if col_name not in actual_cols:
                continue  # already reported as missing
            define_type = var_def["type"]
            actual_dtype = schema[col_name]
            # --DTC is ISO 8601 text whatever the define type says (SDTMIG 3.4 4.4)
            is_dtc = col_name.upper().endswith("DTC")
            compat_types = (pl.String,) if is_dtc else _POLARS_COMPAT.get(define_type, ())

            ok = isinstance(actual_dtype, compat_types)
            if not ok:
                mm = TypeMismatch(
                    variable=col_name,
                    define_type=define_type,
                    actual_dtype=str(actual_dtype),
                )
                result.type_mismatches.append(mm)
                expected_label = (
                    "String (ISO 8601 text)"
                    if is_dtc
                    else _TYPE_LABEL.get(define_type, define_type)
                )
                msg = (
                    f"Column '{col_name}': define type '{define_type}' "
                    f"(expects {expected_label}) but actual dtype is '{actual_dtype}'."
                )
                core = var_def.get("core", "")
                _classify(
                    result, msg, core=core, mandatory=var_def.get("mandatory", False), strict=strict
                )

    def _run_ct_checks(
        self,
        result: CheckResult,
        df: pl.DataFrame,
        vars_by_name: dict[str, dict[str, Any]],
        actual_cols: set[str],
    ) -> None:
        """Verify variable values against the spec's inline codelists.

        The define.yaml already declares each codelist's submission values
        (``codelists[].items[].coded_value``) — a dataset asserting
        conformance to them must actually contain them.  Out-of-codelist
        values are **errors**.  When an offending value matches a decode
        (or a raw ``ct_map`` key from the variable's derivation), the
        message says so — those are almost always unapplied mappings.
        """
        for col_name, var_def in vars_by_name.items():
            oid = var_def.get("codelist")
            if not oid or col_name not in actual_cols:
                continue
            codelist = self._codelists.get(oid)
            if codelist is None:
                result.warnings.append(
                    f"Column '{col_name}' references codelist '{oid}' which is not "
                    f"declared in this define. Declared codelist OIDs: "
                    f"{sorted(self._codelists)}"
                )
                continue
            items = codelist.get("items") or []
            if not items:
                result.warnings.append(
                    f"Column '{col_name}': codelist {oid} has no items, so its values "
                    "are not checked; run fleet init ct."
                )
                continue
            coded: set[str] = {str(item["coded_value"]) for item in items}
            decode_of: dict[str, str] = {
                str(item["decode"]): str(item["coded_value"])
                for item in items
                if item.get("decode")
            }
            ct_mapping: dict[str, Any] = (var_def.get("derivation") or {}).get("ct_map") or {}

            values = [str(v) for v in df[col_name].drop_nulls().unique().to_list() if str(v) != ""]
            invalid = sorted(v for v in values if v not in coded)
            if not invalid:
                continue

            hints: list[str] = []
            for v in invalid:
                if v in decode_of:
                    hints.append(f"'{v}' is the decode of submission value '{decode_of[v]}'")
                elif v in ct_mapping:
                    hints.append(f"'{v}' is a raw ct_map key — the mapping was not applied")
            hint = f" ({'; '.join(hints)})" if hints else ""
            msg = (
                f"Column '{col_name}': value(s) {invalid} not in codelist "
                f"'{oid}' ({codelist.get('name', oid)}). "
                f"Valid values: {sorted(coded)}.{hint}"
            )
            result.ct_violations.append(msg)
            result.errors.append(msg)

    # ------------------------------------------------------------------ #
    # CDISC Core validation                                                #
    # ------------------------------------------------------------------ #

    def validate_core(
        self,
        df: pl.DataFrame,
        dataset: str,
        *,
        standard: str | None = None,
        version: str | None = None,
    ) -> ValidationResult:
        """Run the official CDISC Rules Engine against *df*.

        Standard (``"SDTMIG"`` / ``"ADAMIG"``) and version are auto-detected
        from the ``study`` block in the define YAML.  Override either with the
        *standard* / *version* keyword arguments.

        Requires the CDISC Rules Engine to be installed and discoverable.  See
        ``OfficialCDISCValidator`` for setup instructions.

        Parameters
        ----------
        df:
            The materialised ``pl.DataFrame`` to validate.
        dataset:
            Dataset / domain name (e.g. ``"DM"``, ``"ADVS"``).
        standard:
            Override — e.g. ``"SDTMIG"`` or ``"ADAMIG"``.
        version:
            Override — e.g. ``"3.4"`` or ``"1.1"``.

        Returns
        -------
        ValidationResult
        """
        from fleet.validation.service import ValidationService

        study = self._data.get("study", {})
        detected_standard = (standard or study.get("standard", "SDTMIG")).upper()
        detected_version = version or str(study.get("standard_version", "3.4"))

        svc = ValidationService()
        if "ADAM" in detected_standard:
            return svc.validate_adam(df, dataset=dataset, version=detected_version)
        return svc.validate_sdtm(df, domain=dataset, version=detected_version)

    # ------------------------------------------------------------------ #
    # XPT export                                                           #
    # ------------------------------------------------------------------ #

    def write_xpt(
        self,
        df: pl.DataFrame,
        dataset: str,
        path: str | Path,
        *,
        reorder: bool = True,
    ) -> Path:
        """Write *df* as a SAS transport file, version 5, with the define labels.

        When *reorder* is ``True`` (default) the DataFrame columns are
        rearranged to match the variable order declared in the define before
        writing.  Columns not declared in the define (e.g. private ``_``-prefix
        columns) are silently dropped so the XPT only contains define-declared
        variables.  The dataset and variable labels come from the define;
        the rules of the file are those of :func:`fleet.io.save_xpt`.

        Requires ``pyreadstat``.  Install with ``uv add "fleet-cdisc[io]"``.

        Parameters
        ----------
        df:
            The materialised ``pl.DataFrame`` to write.
        dataset:
            Dataset name used to look up the variable order in the define.
            It must equal the file name (FDA TCG 3.1.1).
        path:
            Destination file path (e.g. ``"outputs/dm.xpt"``).
        reorder:
            Whether to reorder / filter columns to match define order.

        Returns
        -------
        Path
            Resolved path of the written file.
        """
        from fleet.core.exceptions import IOError as FleetIOError
        from fleet.io import save_xpt

        out = Path(path)
        if out.stem.upper() != dataset.upper():
            raise FleetIOError(
                f"{out.name} would hold dataset {dataset.upper()}; name the file "
                f"{dataset.lower()}.xpt, because the member is named as the file (FDA TCG 3.1.1)."
            )

        ds_def = self._datasets.get(dataset.upper())
        if reorder and ds_def is not None:
            define_names = [v["name"] for v in ds_def["variables"]]
            # Keep only columns that are both in define and in df; preserve define order
            ordered = [c for c in define_names if c in df.columns]
            df = df.select(ordered)

        return save_xpt(
            df,
            out,
            label=ds_def.get("label") if ds_def is not None else None,
            column_labels=self.labels(dataset),
        )

    # ------------------------------------------------------------------ #
    # Schema validation                                                    #
    # ------------------------------------------------------------------ #

    def _validate_schema(self) -> None:
        import jsonschema

        from fleet.core.exceptions import SpecSchemaError

        schema = json.loads(_SCHEMA_PATH.read_text(encoding="utf-8"))
        validator = jsonschema.Draft202012Validator(schema)
        errors = list(validator.iter_errors(self._data))
        if errors:
            msgs = "\n".join(f"  - {e.json_path}: {e.message}" for e in errors[:5])
            raise SpecSchemaError(f"define YAML failed schema validation:\n{msgs}")

check

check(df, dataset, *, strict=True)

Check df against the define for dataset.

Parameters

df: The materialised pl.DataFrame to check. dataset: Dataset name to look up in the define (e.g. "DM"). Case-insensitive. strict: When True (default), core="Req" issues are errors. When False, Req issues are downgraded to warnings so the pipeline can proceed despite missing required variables (e.g. during development or when source data is incomplete).

Returns

CheckResult Always returns a result — never raises unless you call result.raise_on_errors().

Source code in src/fleet/define_xml/checker.py
def check(
    self,
    df: pl.DataFrame,
    dataset: str,
    *,
    strict: bool = True,
) -> CheckResult:
    """Check *df* against the define for *dataset*.

    Parameters
    ----------
    df:
        The materialised ``pl.DataFrame`` to check.
    dataset:
        Dataset name to look up in the define (e.g. ``"DM"``).
        Case-insensitive.
    strict:
        When ``True`` (default), ``core="Req"`` issues are errors.
        When ``False``, ``Req`` issues are downgraded to warnings so
        the pipeline can proceed despite missing required variables
        (e.g. during development or when source data is incomplete).

    Returns
    -------
    CheckResult
        Always returns a result — never raises unless you call
        ``result.raise_on_errors()``.
    """
    result = CheckResult(dataset=dataset.upper())

    if not self._enabled:
        return result

    ds_def = self._datasets.get(dataset.upper())
    if ds_def is None:
        result.errors.append(
            f"Dataset '{dataset}' not found in define. Available: {sorted(self._datasets)}"
        )
        return result

    # Build variable index (exclude private _-prefix names)
    vars_by_name: dict[str, dict[str, Any]] = {
        v["name"]: v for v in ds_def["variables"] if not v["name"].startswith("_")
    }

    # Labels always populated regardless of other flags
    result.labels = {name: v["label"] for name, v in vars_by_name.items()}

    # Actual DataFrame columns excluding private _-prefix columns
    actual_cols: set[str] = {c for c in df.columns if not c.startswith("_")}

    if self._check_columns:
        self._run_column_checks(result, vars_by_name, actual_cols, strict=strict)

    if self._check_types:
        self._run_type_checks(result, df, vars_by_name, actual_cols, strict=strict)

    if self._check_ct:
        self._run_ct_checks(result, df, vars_by_name, actual_cols)

    return result

datasets

datasets()

Return the list of dataset names declared in the define.

Source code in src/fleet/define_xml/checker.py
def datasets(self) -> list[str]:
    """Return the list of dataset names declared in the define."""
    return list(self._datasets)

labels

labels(dataset)

Return the variable → label mapping for dataset without running full checks.

Source code in src/fleet/define_xml/checker.py
def labels(self, dataset: str) -> dict[str, str]:
    """Return the variable → label mapping for *dataset* without running full checks."""
    ds_def = self._datasets.get(dataset.upper())
    if ds_def is None:
        return {}
    return {v["name"]: v["label"] for v in ds_def["variables"] if not v["name"].startswith("_")}

validate_core

validate_core(df, dataset, *, standard=None, version=None)

Run the official CDISC Rules Engine against df.

Standard ("SDTMIG" / "ADAMIG") and version are auto-detected from the study block in the define YAML. Override either with the standard / version keyword arguments.

Requires the CDISC Rules Engine to be installed and discoverable. See OfficialCDISCValidator for setup instructions.

Parameters

df: The materialised pl.DataFrame to validate. dataset: Dataset / domain name (e.g. "DM", "ADVS"). standard: Override — e.g. "SDTMIG" or "ADAMIG". version: Override — e.g. "3.4" or "1.1".

Returns

ValidationResult

Source code in src/fleet/define_xml/checker.py
def validate_core(
    self,
    df: pl.DataFrame,
    dataset: str,
    *,
    standard: str | None = None,
    version: str | None = None,
) -> ValidationResult:
    """Run the official CDISC Rules Engine against *df*.

    Standard (``"SDTMIG"`` / ``"ADAMIG"``) and version are auto-detected
    from the ``study`` block in the define YAML.  Override either with the
    *standard* / *version* keyword arguments.

    Requires the CDISC Rules Engine to be installed and discoverable.  See
    ``OfficialCDISCValidator`` for setup instructions.

    Parameters
    ----------
    df:
        The materialised ``pl.DataFrame`` to validate.
    dataset:
        Dataset / domain name (e.g. ``"DM"``, ``"ADVS"``).
    standard:
        Override — e.g. ``"SDTMIG"`` or ``"ADAMIG"``.
    version:
        Override — e.g. ``"3.4"`` or ``"1.1"``.

    Returns
    -------
    ValidationResult
    """
    from fleet.validation.service import ValidationService

    study = self._data.get("study", {})
    detected_standard = (standard or study.get("standard", "SDTMIG")).upper()
    detected_version = version or str(study.get("standard_version", "3.4"))

    svc = ValidationService()
    if "ADAM" in detected_standard:
        return svc.validate_adam(df, dataset=dataset, version=detected_version)
    return svc.validate_sdtm(df, domain=dataset, version=detected_version)

write_xpt

write_xpt(df, dataset, path, *, reorder=True)

Write df as a SAS transport file, version 5, with the define labels.

When reorder is True (default) the DataFrame columns are rearranged to match the variable order declared in the define before writing. Columns not declared in the define (e.g. private _-prefix columns) are silently dropped so the XPT only contains define-declared variables. The dataset and variable labels come from the define; the rules of the file are those of :func:fleet.io.save_xpt.

Requires pyreadstat. Install with uv add "fleet-cdisc[io]".

Parameters

df: The materialised pl.DataFrame to write. dataset: Dataset name used to look up the variable order in the define. It must equal the file name (FDA TCG 3.1.1). path: Destination file path (e.g. "outputs/dm.xpt"). reorder: Whether to reorder / filter columns to match define order.

Returns

Path Resolved path of the written file.

Source code in src/fleet/define_xml/checker.py
def write_xpt(
    self,
    df: pl.DataFrame,
    dataset: str,
    path: str | Path,
    *,
    reorder: bool = True,
) -> Path:
    """Write *df* as a SAS transport file, version 5, with the define labels.

    When *reorder* is ``True`` (default) the DataFrame columns are
    rearranged to match the variable order declared in the define before
    writing.  Columns not declared in the define (e.g. private ``_``-prefix
    columns) are silently dropped so the XPT only contains define-declared
    variables.  The dataset and variable labels come from the define;
    the rules of the file are those of :func:`fleet.io.save_xpt`.

    Requires ``pyreadstat``.  Install with ``uv add "fleet-cdisc[io]"``.

    Parameters
    ----------
    df:
        The materialised ``pl.DataFrame`` to write.
    dataset:
        Dataset name used to look up the variable order in the define.
        It must equal the file name (FDA TCG 3.1.1).
    path:
        Destination file path (e.g. ``"outputs/dm.xpt"``).
    reorder:
        Whether to reorder / filter columns to match define order.

    Returns
    -------
    Path
        Resolved path of the written file.
    """
    from fleet.core.exceptions import IOError as FleetIOError
    from fleet.io import save_xpt

    out = Path(path)
    if out.stem.upper() != dataset.upper():
        raise FleetIOError(
            f"{out.name} would hold dataset {dataset.upper()}; name the file "
            f"{dataset.lower()}.xpt, because the member is named as the file (FDA TCG 3.1.1)."
        )

    ds_def = self._datasets.get(dataset.upper())
    if reorder and ds_def is not None:
        define_names = [v["name"] for v in ds_def["variables"]]
        # Keep only columns that are both in define and in df; preserve define order
        ordered = [c for c in define_names if c in df.columns]
        df = df.select(ordered)

    return save_xpt(
        df,
        out,
        label=ds_def.get("label") if ds_def is not None else None,
        column_labels=self.labels(dataset),
    )

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