Skip to content

Trial Design Domains API

fleet.sdtm.design

Study design aggregate — define the trial design once, derive every domain.

StudyDesign is the single typed source of truth for a study's structure: elements, arms (as ordered element paths), visits, criteria, and summary parameters. Every Trial Design domain (TE, TA, TV, TS, TI, TD, TM) is derived from it, so TAETORD ordering, element/epoch duplication across arms, and cross-domain FK consistency fall out mechanically instead of being hand-maintained per row.

Usage::

import fleet

design = fleet.StudyDesign(
    study_id="CDISCPILOT01",
    elements=[
        {"etcd": "SCRN", "element": "Screening", "tedur": "P14D",
         "epoch": "SCREENING"},
        {"etcd": "TRT", "element": "Treatment", "tedur": "P84D",
         "epoch": "TREATMENT"},
        {"etcd": "FU", "element": "Follow-up", "tedur": "P28D",
         "epoch": "FOLLOW-UP"},
    ],
    arms={"PBO": ["SCRN", "TRT", "FU"], "XAN_LO": ["SCRN", "TRT", "FU"]},
    arm_names={"PBO": "Placebo", "XAN_LO": "Xanomeline Low Dose"},
)
ta = design.to_ta()
frames = design.domains()       # {"TE": df, "TA": df, ...}
findings = design.audit()       # P21-style conformance pre-check

ArmStep

Bases: BaseModel

One position of an arm path, with the TA values of that position.

A plain ETCD string in a path is the short form of a step with no override. epoch replaces the element's epoch at this position (a crossover, an element that repeats). tabranch replaces the default Randomized to <arm> text, and tatrans gives the TATRANS rule.

Source code in src/fleet/sdtm/design.py
class ArmStep(BaseModel):
    """One position of an arm path, with the TA values of that position.

    A plain ETCD string in a path is the short form of a step with no
    override.  *epoch* replaces the element's epoch at this position (a
    crossover, an element that repeats).  *tabranch* replaces the default
    ``Randomized to <arm>`` text, and *tatrans* gives the TATRANS rule.
    """

    model_config = ConfigDict(extra="forbid")

    etcd: ElementCode
    epoch: EpochLike | None = None
    tabranch: RuleExpression = ""
    tatrans: RuleExpression = ""

StudyDesign

Bases: BaseModel

Typed aggregate of a study's trial design.

arms maps each ARMCD to its ordered path of element codes — the per-arm element name/epoch/TAETORD repetition of raw TA rows is derived, never written by hand. A path entry is an ETCD string or an :class:ArmStep ({"etcd": ..., "epoch": ..., "tabranch": ..., "tatrans": ...}) for the TA values of one position. All fields accept plain dicts (Pydantic coerces), so a trial_design.yaml deserialises directly via :meth:from_yaml. An unknown key raises.

TABRANCH defaults to Randomized to <arm> on the last element that every arm shares, or on the randomized_at element when it is given. A step's tabranch replaces that text: state the real rule when the branch is not a randomization.

Source code in src/fleet/sdtm/design.py
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
class StudyDesign(BaseModel):
    """Typed aggregate of a study's trial design.

    ``arms`` maps each ARMCD to its ordered path of element codes — the
    per-arm element name/epoch/TAETORD repetition of raw TA rows is derived,
    never written by hand.  A path entry is an ETCD string or an
    :class:`ArmStep` (``{"etcd": ..., "epoch": ..., "tabranch": ...,
    "tatrans": ...}``) for the TA values of one position.  All fields accept
    plain dicts (Pydantic coerces), so a ``trial_design.yaml`` deserialises
    directly via :meth:`from_yaml`.  An unknown key raises.

    TABRANCH defaults to ``Randomized to <arm>`` on the last element that
    every arm shares, or on the *randomized_at* element when it is given.
    A step's *tabranch* replaces that text: state the real rule when the
    branch is not a randomization.
    """

    model_config = ConfigDict(extra="forbid")

    study_id: str = Field(min_length=1)
    elements: list[TrialElement] = []
    arms: dict[str, list[str | ArmStep]] = {}
    arm_names: dict[str, str] = {}
    randomized_at: str | None = None
    visits: list[TrialVisit] = []
    criteria: list[TrialCriterion] = []
    parameters: list[TrialParameter] = []
    assessments: list[TrialDiseaseAssessment] = []
    milestones: list[TrialMilestone] = []

    @model_validator(mode="after")
    def check_referential_integrity(self) -> StudyDesign:
        TrialElements(elements=self.elements)  # uniqueness + epoch consistency
        known = {e.etcd for e in self.elements}
        for armcd, path in self.arms.items():
            if not path:
                raise ValueError(f"Arm '{armcd}' has an empty element path")
            missing = [_etcd(entry) for entry in path if _etcd(entry) not in known]
            if missing:
                raise ValueError(f"Arm '{armcd}' references undefined elements: {missing}")
        stray_names = sorted(set(self.arm_names) - set(self.arms))
        if stray_names:
            raise ValueError(f"arm_names holds ARMCD(s) that are not in arms: {stray_names}")
        if self.randomized_at is not None and self.randomized_at not in known:
            raise ValueError(f"randomized_at '{self.randomized_at}' is not a defined element")
        for visit in self.visits:
            if visit.armcd and visit.armcd not in self.arms:
                raise ValueError(f"Visit '{visit.visit}' references undefined arm '{visit.armcd}'")
        return self

    # ------------------------------------------------------------------ #
    # Derivation                                                           #
    # ------------------------------------------------------------------ #

    def _frame(self, df: pl.DataFrame, domain: str) -> pl.DataFrame:
        """Prepend STUDYID/DOMAIN in SDTM column order."""
        return df.select(
            pl.lit(self.study_id).alias("STUDYID"),
            pl.lit(domain).alias("DOMAIN"),
            pl.all(),
        )

    def _branch_index(self) -> int | None:
        """Index of the last element shared by every arm before paths diverge.

        ponytail: single randomized-branch designs only; nested or adaptive
        branch points need explicit TrialArm rows built by hand.
        """
        paths = [[_etcd(e) for e in p] for p in self.arms.values()]
        if len(paths) < 2:
            return None
        prefix = 0
        while all(len(p) > prefix for p in paths) and len({p[prefix] for p in paths}) == 1:
            prefix += 1
        if prefix == 0 or all(p[prefix:] == paths[0][prefix:] for p in paths):
            return None  # identical paths or no shared prefix — no branch to describe
        return prefix - 1

    def arm_collection(self) -> TrialArms:
        """Derive the validated ``TrialArms`` collection from the arm paths.

        Returns:
            TrialArms: One row per arm/element with TAETORD, ELEMENT, EPOCH
                looked up from the element definitions (or the step's epoch)
                and TABRANCH rendered at the branch point (or the step's
                tabranch).

        References:
            SDTMIG 3.4 TA: EPOCH is the epoch of this element of the arm,
            TABRANCH the condition met at the end of the element; see
            ``docs/adr/0036-an-arm-path-entry-is-an-element-or-a-step.md``.

        Examples:
            Derive TA rows from a design::

                design = fleet.StudyDesign(study_id="S1", elements=[...],
                                           arms={"PBO": ["SCRN", "TRT"]})
                ta_rows = design.arm_collection()
        """
        lookup = {e.etcd: e for e in self.elements}
        branch_at = None if self.randomized_at else self._branch_index()
        rows = []
        for armcd, path in self.arms.items():
            arm = self.arm_names.get(armcd) or armcd.replace("_", " ").title()
            codes = [_etcd(e) for e in path]
            randomized = codes.index(self.randomized_at) if self.randomized_at in codes else None
            for order, entry in enumerate(path, start=1):
                step = ArmStep(etcd=entry) if isinstance(entry, str) else entry
                el = lookup[step.etcd]
                at_branch = order - 1 in (branch_at, randomized)
                default = f"Randomized to {arm}" if at_branch else ""
                rows.append(
                    TrialArm(
                        armcd=armcd,
                        arm=arm,
                        taetord=order,
                        etcd=step.etcd,
                        element=el.element,
                        tabranch=step.tabranch or default,
                        tatrans=step.tatrans,
                        epoch=step.epoch or el.epoch,
                    )
                )
        return TrialArms(arms=rows)

    def to_te(self) -> pl.DataFrame:
        """Derive the TE (Trial Elements) domain.

        Returns:
            pl.DataFrame: TE with STUDYID/DOMAIN and SDTM column names.

        Examples:
            Derive TE from a design::

                te = design.to_te()
        """
        return self._frame(TrialElements(elements=self.elements).to_polars(), "TE")

    def to_ta(self) -> pl.DataFrame:
        """Derive the TA (Trial Arms) domain from the arm paths.

        Returns:
            pl.DataFrame: TA with STUDYID/DOMAIN and SDTM column names.

        Examples:
            Derive TA from a design::

                ta = design.to_ta()
        """
        return self._frame(self.arm_collection().to_polars(), "TA")

    def to_tv(self) -> pl.DataFrame:
        """Derive the TV (Trial Visits) domain.

        Returns:
            pl.DataFrame: TV with STUDYID/DOMAIN and SDTM column names.

        Examples:
            Derive TV from a design::

                tv = design.to_tv()
        """
        return self._frame(TrialVisits(visits=self.visits).to_polars(), "TV")

    def to_ts(self) -> pl.DataFrame:
        """Derive the TS (Trial Summary) domain.

        Returns:
            pl.DataFrame: TS with STUDYID/DOMAIN and SDTM column names.

        Examples:
            Derive TS from a design::

                ts = design.to_ts()
        """
        return self._frame(TrialParameters(parameters=self.parameters).to_polars(), "TS")

    def to_ti(self) -> pl.DataFrame:
        """Derive the TI (Trial Inclusion/Exclusion) domain.

        Returns:
            pl.DataFrame: TI with STUDYID/DOMAIN and SDTM column names.

        Examples:
            Derive TI from a design::

                ti = design.to_ti()
        """
        return self._frame(TrialCriteria(criteria=self.criteria).to_polars(), "TI")

    def to_td(self) -> pl.DataFrame:
        """Derive the TD (Trial Disease Assessments) domain.

        Returns:
            pl.DataFrame: TD with STUDYID/DOMAIN and SDTM column names.

        Examples:
            Derive TD from a design::

                td = design.to_td()
        """
        return self._frame(TrialDiseaseAssessments(assessments=self.assessments).to_polars(), "TD")

    def to_tm(self) -> pl.DataFrame:
        """Derive the TM (Trial Disease Milestones) domain.

        Returns:
            pl.DataFrame: TM with STUDYID/DOMAIN and SDTM column names.

        Examples:
            Derive TM from a design::

                tm = design.to_tm()
        """
        return self._frame(TrialMilestones(milestones=self.milestones).to_polars(), "TM")

    def domains(self) -> dict[str, pl.DataFrame]:
        """Derive every populated Trial Design domain.

        Returns:
            dict[str, pl.DataFrame]: Domain code → DataFrame, skipping
                domains whose design section is empty.

        Examples:
            Build all domains and write them out::

                for domain, df in design.domains().items():
                    df.write_parquet(f"data/sdtm/{domain.lower()}.parquet")
        """
        sections = {
            "TE": (self.elements, self.to_te),
            "TA": (self.arms, self.to_ta),
            "TV": (self.visits, self.to_tv),
            "TS": (self.parameters, self.to_ts),
            "TI": (self.criteria, self.to_ti),
            "TD": (self.assessments, self.to_td),
            "TM": (self.milestones, self.to_tm),
        }
        return {domain: build() for domain, (section, build) in sections.items() if section}

    def audit(self, *, dm: pl.DataFrame | None = None) -> pl.DataFrame:
        """Run the P21-style conformance pre-check over the derived domains.

        Two design checks come first: arms with the same path
        (``FLEETTD04``), and an element that repeats in one arm with no
        per-position epoch (``FLEETTD05``).

        Args:
            dm: Optional DM domain for cross-checking ARMCD assignments.

        Returns:
            pl.DataFrame: One row per finding (``rule_id``, ``severity``,
                ``domain``, ``message``); empty when clean.

        Examples:
            Audit a design before export::

                findings = design.audit()
                errors = findings.filter(pl.col("severity") == "error")
        """
        from fleet.sdtm.tdd_audit import audit

        frames = self.domains()
        findings = audit(
            te=frames.get("TE"),
            ta=frames.get("TA"),
            tv=frames.get("TV"),
            # TS is always audited: an absent parameters section means every
            # FDA-required parameter is missing (rejection-level), not "skip".
            ts=frames.get("TS", self.to_ts()),
            ti=frames.get("TI"),
            dm=dm,
        )
        return pl.concat([pl.DataFrame(self._design_findings(), schema=findings.schema), findings])

    def _design_findings(self) -> list[dict[str, str]]:
        """Findings on the arm paths that the derived domains cannot show."""
        found = []
        by_path: dict[tuple[str, ...], list[str]] = {}
        for armcd, path in self.arms.items():
            by_path.setdefault(tuple(_etcd(e) for e in path), []).append(armcd)
            codes = [_etcd(e) for e in path]
            for etcd in sorted({c for c in codes if codes.count(c) > 1}):
                plain = [
                    e for e in path if _etcd(e) == etcd and (isinstance(e, str) or not e.epoch)
                ]
                if plain:
                    found.append(
                        {
                            "rule_id": "FLEETTD05",
                            "severity": "warning",
                            "domain": "TA",
                            "message": f"Arm '{armcd}' repeats element '{etcd}' with no "
                            "per-position epoch: give each position {etcd, epoch}.",
                        }
                    )
        for arms in by_path.values():
            if len(arms) > 1:
                found.append(
                    {
                        "rule_id": "FLEETTD04",
                        "severity": "warning",
                        "domain": "TA",
                        "message": f"Arms {arms} have the same element path, so TA cannot "
                        "tell them apart: check the protocol.",
                    }
                )
        return found

    # ------------------------------------------------------------------ #
    # Interchange                                                          #
    # ------------------------------------------------------------------ #

    @classmethod
    def from_yaml(cls, path: str | Path) -> StudyDesign:
        """Load a design from a ``trial_design.yaml`` spec.

        The YAML mirrors the model schema; a top-level ``trial_design:``
        wrapper key is accepted so the section can live inside a larger
        study file.  A repeated key or a key the model does not read
        raises, so a typo cannot drop a rule, a visit or an arm.

        Args:
            path: Path to the YAML file.

        Returns:
            StudyDesign: The validated design.

        Raises:
            yaml.constructor.ConstructorError: When a mapping repeats a key.
            pydantic.ValidationError: When a key is unknown or a value is
                not valid.

        Examples:
            Load and build every domain::

                design = fleet.StudyDesign.from_yaml("metadata/trial_design.yaml")
                frames = design.domains()
        """
        data = load_strict_yaml(Path(path).read_text(encoding="utf-8"))
        return cls(**_dates_to_iso(data.get("trial_design", data)))

    def to_yaml(self, path: str | Path | None = None) -> str:
        """Serialise the design to YAML (the ``from_yaml`` round-trip).

        Args:
            path: Optional file path to write to.

        Returns:
            str: The YAML document.

        Examples:
            Persist a design next to the study metadata::

                design.to_yaml("metadata/trial_design.yaml")
        """
        text = yaml.dump(
            self.model_dump(mode="json", exclude_defaults=True),
            default_flow_style=False,
            sort_keys=False,
            allow_unicode=True,
        )
        if path is not None:
            Path(path).write_text(text, encoding="utf-8")
        return text

    @classmethod
    def from_mermaid(cls, mermaid_text: str, *, study_id: str, **sections: Any) -> StudyDesign:
        """Build a design from a Mermaid flowchart.

        The diagram gives the elements and the arm paths.  ARM comes from
        *arm_names* when given, else from the ARMCD.

        Args:
            mermaid_text: A Mermaid ``flowchart TD`` string (see
                :func:`fleet.sdtm.tdd.parse_trial_design`).
            study_id: The study identifier.
            **sections: Extra design sections (``arm_names=``, ``visits=``,
                ``criteria=``, ``parameters=``, ...) passed through to the
                constructor.

        Returns:
            StudyDesign: Design with elements and arm paths from the diagram.

        Raises:
            ValueError: When the diagram cannot give a design (see
                :func:`fleet.sdtm.tdd.parse_trial_design`).

        Examples:
            Diagram in, datasets out::

                design = fleet.StudyDesign.from_mermaid(diagram_text,
                                                        study_id="CDISCPILOT01")
                ta = design.to_ta()
        """
        te, ta = parse_trial_design(mermaid_text)
        arms: dict[str, list[str | ArmStep]] = {}
        arm_names: dict[str, str] = {}
        for row in sorted(ta.arms, key=lambda a: (a.armcd, a.taetord)):
            arms.setdefault(row.armcd, []).append(row.etcd)
            arm_names[row.armcd] = row.arm
        arm_names.update(sections.pop("arm_names", None) or {})
        return cls(
            study_id=study_id,
            elements=te.elements,
            arms=arms,
            arm_names=arm_names,
            **sections,
        )

    def to_mermaid(self) -> str:
        """Render the design as a Mermaid flowchart for a review document.

        Elements are grouped into epoch subgraphs; edges follow the arm
        paths, labelled with the ARMCD where the design branches (on the
        first edge for a single arm).  The diagram is a review view: it
        carries ETCD, ELEMENT, TEDUR, the element epochs and the arm paths,
        but not ARM, TESTRL, TEENRL, TABRANCH, TATRANS or a per-position
        epoch.  When :meth:`from_mermaid` cannot read the paths back (arms
        with the same path, a repeated element, a crossover), a warning says
        so.  YAML (:meth:`to_yaml`) is the lossless round trip.

        Returns:
            str: A Mermaid ``flowchart TD`` document.

        Examples:
            Render for a design-review doc::

                print(design.to_mermaid())
        """
        lines = ["flowchart TD"]
        by_epoch: dict[str, list[TrialElement]] = {}
        for el in self.elements:
            by_epoch.setdefault(str(el.epoch), []).append(el)
        for i, (epoch, els) in enumerate(by_epoch.items()):
            lines.append(f"    subgraph EP{i}[{epoch}]")
            for el in els:
                dur = f"<br/>{el.tedur}" if el.tedur else ""
                name = el.element.replace('"', "#quot;")
                lines.append(f'        {el.etcd}["{name}{dur}"]')
            lines.append("    end")
        branch_at = 0 if len(self.arms) == 1 else self._branch_index()
        paths = {armcd: [_etcd(e) for e in path] for armcd, path in self.arms.items()}
        seen: set[tuple[str, str, str]] = set()
        for armcd, path in paths.items():
            for i, (src, dst) in enumerate(zip(path, path[1:])):
                label = f"|{armcd}|" if branch_at is not None and i == branch_at else ""
                edge = (src, label, dst)
                if edge not in seen:
                    seen.add(edge)
                    lines.append(f"    {src} -->{label} {dst}")
        text = "\n".join(lines)
        try:
            with warnings.catch_warnings():
                warnings.simplefilter("ignore")
                _, ta = parse_trial_design(text)
            back: dict[str, list[str]] = {}
            for row in ta.arms:
                back.setdefault(row.armcd, []).append(row.etcd)
            lossless = back == paths and not any(
                isinstance(e, ArmStep) and e.epoch for path in self.arms.values() for e in path
            )
        except ValueError:
            lossless = False
        if not lossless:
            warnings.warn(
                "to_mermaid: from_mermaid cannot read this design back (arms with the same "
                "path, a repeated element, a crossover or a per-position epoch). Use to_yaml() "
                "for a lossless copy.",
                stacklevel=2,
            )
        return text

    @classmethod
    def from_usdm(cls, data: dict, *, study_id: str | None = None) -> StudyDesign:
        """Build a design from a CDISC USDM (DDF) study definition.

        Maps the structural subset of USDM v3/v4 JSON: arms + epochs +
        elements + studyCells become the arm paths (with the epoch of each
        cell), encounters become visits, and eligibility criteria become TI
        rows.  TI text comes from the v4 criterion item (or the v3
        population criteria), with ``usdm:tag`` resolved through the syntax
        dictionary and XHTML removed.  An identifier that starts with a
        digit takes an IN or EX prefix (SDTMIG 3.4 section 4.5.3).

        ponytail: schedule timelines, objectives/endpoints, and biomedical
        concepts are intentionally not mapped — extend when a consumer needs
        them.

        Args:
            data: Parsed USDM JSON (the ``{"study": ...}`` wrapper or the
                study object itself).
            study_id: Override for STUDYID; defaults to the first study
                identifier found in the USDM document.

        Returns:
            StudyDesign: Design with the mapped structural subset.

        Raises:
            ValueError: When a criterion has no text or no inclusion or
                exclusion category, a tag cannot be resolved, or two
                criteria give the same IETESTCD.

        Examples:
            Import an OpenStudyBuilder / DDF export::

                import json
                design = fleet.StudyDesign.from_usdm(
                    json.loads(Path("usdm.json").read_text()),
                    study_id="CDISCPILOT01",
                )
        """
        study = data.get("study", data)
        versions = study.get("versions") or study.get("studyVersions") or [study]
        version = versions[0]
        designs = version.get("studyDesigns") or []
        sd = designs[0] if designs else {}

        if study_id is None:
            idents = version.get("studyIdentifiers") or []
            study_id = next(
                (i.get("studyIdentifier") or i.get("text") for i in idents if isinstance(i, dict)),
                None,
            ) or (study.get("name") or "STUDY")

        def label(obj: dict) -> str:
            return obj.get("label") or obj.get("name") or obj.get("id", "")

        epoch_order = [e["id"] for e in sd.get("epochs", [])]
        epoch_label = {e["id"]: label(e).upper() for e in sd.get("epochs", [])}
        taken: set[str] = set()
        etcd_by_id: dict[str, str] = {}
        element_models: dict[str, dict] = {}
        for el in sd.get("elements", []):
            etcd = _sdtm_code(label(el), 8, taken)
            etcd_by_id[el["id"]] = etcd
            element_models[el["id"]] = {
                "etcd": etcd,
                "element": label(el)[:200],
                "testrl": (el.get("transitionStartRule") or {}).get("text", "")[:2000],
                "teenrl": (el.get("transitionEndRule") or {}).get("text", "")[:2000],
            }

        arm_label = {a["id"]: label(a) for a in sd.get("arms", [])}
        arm_taken: set[str] = set()
        armcd_by_id = {aid: _sdtm_code(name, 20, arm_taken) for aid, name in arm_label.items()}

        arms: dict[str, list[str | ArmStep]] = {}
        cells = sorted(
            sd.get("studyCells", []),
            key=lambda c: epoch_order.index(c["epochId"]) if c.get("epochId") in epoch_order else 0,
        )
        for cell in cells:
            armcd = armcd_by_id.get(cell.get("armId", ""))
            if armcd is None:
                continue
            cell_epoch = epoch_label.get(cell.get("epochId", ""), "TREATMENT")
            for element_id in cell.get("elementIds", []):
                if element_id in element_models:
                    epoch = element_models[element_id].setdefault("epoch", cell_epoch)
                    etcd = etcd_by_id[element_id]
                    arms.setdefault(armcd, []).append(
                        etcd if epoch == cell_epoch else ArmStep(etcd=etcd, epoch=cell_epoch)
                    )

        elements = [
            TrialElement(**{"epoch": "TREATMENT", **model}) for model in element_models.values()
        ]

        visits = [
            TrialVisit(visitnum=num, visit=label(enc)[:200])
            for num, enc in enumerate(sd.get("encounters", []), start=1)
        ]

        return cls(
            study_id=study_id,
            elements=elements,
            arms=arms,
            arm_names={armcd_by_id[aid]: name for aid, name in arm_label.items()},
            visits=visits,
            criteria=_usdm_criteria(study, version, sd),
        )

arm_collection

arm_collection()

Derive the validated TrialArms collection from the arm paths.

Returns:

Name Type Description
TrialArms TrialArms

One row per arm/element with TAETORD, ELEMENT, EPOCH looked up from the element definitions (or the step's epoch) and TABRANCH rendered at the branch point (or the step's tabranch).

References

SDTMIG 3.4 TA: EPOCH is the epoch of this element of the arm, TABRANCH the condition met at the end of the element; see docs/adr/0036-an-arm-path-entry-is-an-element-or-a-step.md.

Examples:

Derive TA rows from a design::

design = fleet.StudyDesign(study_id="S1", elements=[...],
                           arms={"PBO": ["SCRN", "TRT"]})
ta_rows = design.arm_collection()
Source code in src/fleet/sdtm/design.py
def arm_collection(self) -> TrialArms:
    """Derive the validated ``TrialArms`` collection from the arm paths.

    Returns:
        TrialArms: One row per arm/element with TAETORD, ELEMENT, EPOCH
            looked up from the element definitions (or the step's epoch)
            and TABRANCH rendered at the branch point (or the step's
            tabranch).

    References:
        SDTMIG 3.4 TA: EPOCH is the epoch of this element of the arm,
        TABRANCH the condition met at the end of the element; see
        ``docs/adr/0036-an-arm-path-entry-is-an-element-or-a-step.md``.

    Examples:
        Derive TA rows from a design::

            design = fleet.StudyDesign(study_id="S1", elements=[...],
                                       arms={"PBO": ["SCRN", "TRT"]})
            ta_rows = design.arm_collection()
    """
    lookup = {e.etcd: e for e in self.elements}
    branch_at = None if self.randomized_at else self._branch_index()
    rows = []
    for armcd, path in self.arms.items():
        arm = self.arm_names.get(armcd) or armcd.replace("_", " ").title()
        codes = [_etcd(e) for e in path]
        randomized = codes.index(self.randomized_at) if self.randomized_at in codes else None
        for order, entry in enumerate(path, start=1):
            step = ArmStep(etcd=entry) if isinstance(entry, str) else entry
            el = lookup[step.etcd]
            at_branch = order - 1 in (branch_at, randomized)
            default = f"Randomized to {arm}" if at_branch else ""
            rows.append(
                TrialArm(
                    armcd=armcd,
                    arm=arm,
                    taetord=order,
                    etcd=step.etcd,
                    element=el.element,
                    tabranch=step.tabranch or default,
                    tatrans=step.tatrans,
                    epoch=step.epoch or el.epoch,
                )
            )
    return TrialArms(arms=rows)

to_te

to_te()

Derive the TE (Trial Elements) domain.

Returns:

Type Description
DataFrame

pl.DataFrame: TE with STUDYID/DOMAIN and SDTM column names.

Examples:

Derive TE from a design::

te = design.to_te()
Source code in src/fleet/sdtm/design.py
def to_te(self) -> pl.DataFrame:
    """Derive the TE (Trial Elements) domain.

    Returns:
        pl.DataFrame: TE with STUDYID/DOMAIN and SDTM column names.

    Examples:
        Derive TE from a design::

            te = design.to_te()
    """
    return self._frame(TrialElements(elements=self.elements).to_polars(), "TE")

to_ta

to_ta()

Derive the TA (Trial Arms) domain from the arm paths.

Returns:

Type Description
DataFrame

pl.DataFrame: TA with STUDYID/DOMAIN and SDTM column names.

Examples:

Derive TA from a design::

ta = design.to_ta()
Source code in src/fleet/sdtm/design.py
def to_ta(self) -> pl.DataFrame:
    """Derive the TA (Trial Arms) domain from the arm paths.

    Returns:
        pl.DataFrame: TA with STUDYID/DOMAIN and SDTM column names.

    Examples:
        Derive TA from a design::

            ta = design.to_ta()
    """
    return self._frame(self.arm_collection().to_polars(), "TA")

to_tv

to_tv()

Derive the TV (Trial Visits) domain.

Returns:

Type Description
DataFrame

pl.DataFrame: TV with STUDYID/DOMAIN and SDTM column names.

Examples:

Derive TV from a design::

tv = design.to_tv()
Source code in src/fleet/sdtm/design.py
def to_tv(self) -> pl.DataFrame:
    """Derive the TV (Trial Visits) domain.

    Returns:
        pl.DataFrame: TV with STUDYID/DOMAIN and SDTM column names.

    Examples:
        Derive TV from a design::

            tv = design.to_tv()
    """
    return self._frame(TrialVisits(visits=self.visits).to_polars(), "TV")

to_ts

to_ts()

Derive the TS (Trial Summary) domain.

Returns:

Type Description
DataFrame

pl.DataFrame: TS with STUDYID/DOMAIN and SDTM column names.

Examples:

Derive TS from a design::

ts = design.to_ts()
Source code in src/fleet/sdtm/design.py
def to_ts(self) -> pl.DataFrame:
    """Derive the TS (Trial Summary) domain.

    Returns:
        pl.DataFrame: TS with STUDYID/DOMAIN and SDTM column names.

    Examples:
        Derive TS from a design::

            ts = design.to_ts()
    """
    return self._frame(TrialParameters(parameters=self.parameters).to_polars(), "TS")

to_ti

to_ti()

Derive the TI (Trial Inclusion/Exclusion) domain.

Returns:

Type Description
DataFrame

pl.DataFrame: TI with STUDYID/DOMAIN and SDTM column names.

Examples:

Derive TI from a design::

ti = design.to_ti()
Source code in src/fleet/sdtm/design.py
def to_ti(self) -> pl.DataFrame:
    """Derive the TI (Trial Inclusion/Exclusion) domain.

    Returns:
        pl.DataFrame: TI with STUDYID/DOMAIN and SDTM column names.

    Examples:
        Derive TI from a design::

            ti = design.to_ti()
    """
    return self._frame(TrialCriteria(criteria=self.criteria).to_polars(), "TI")

to_td

to_td()

Derive the TD (Trial Disease Assessments) domain.

Returns:

Type Description
DataFrame

pl.DataFrame: TD with STUDYID/DOMAIN and SDTM column names.

Examples:

Derive TD from a design::

td = design.to_td()
Source code in src/fleet/sdtm/design.py
def to_td(self) -> pl.DataFrame:
    """Derive the TD (Trial Disease Assessments) domain.

    Returns:
        pl.DataFrame: TD with STUDYID/DOMAIN and SDTM column names.

    Examples:
        Derive TD from a design::

            td = design.to_td()
    """
    return self._frame(TrialDiseaseAssessments(assessments=self.assessments).to_polars(), "TD")

to_tm

to_tm()

Derive the TM (Trial Disease Milestones) domain.

Returns:

Type Description
DataFrame

pl.DataFrame: TM with STUDYID/DOMAIN and SDTM column names.

Examples:

Derive TM from a design::

tm = design.to_tm()
Source code in src/fleet/sdtm/design.py
def to_tm(self) -> pl.DataFrame:
    """Derive the TM (Trial Disease Milestones) domain.

    Returns:
        pl.DataFrame: TM with STUDYID/DOMAIN and SDTM column names.

    Examples:
        Derive TM from a design::

            tm = design.to_tm()
    """
    return self._frame(TrialMilestones(milestones=self.milestones).to_polars(), "TM")

domains

domains()

Derive every populated Trial Design domain.

Returns:

Type Description
dict[str, DataFrame]

dict[str, pl.DataFrame]: Domain code → DataFrame, skipping domains whose design section is empty.

Examples:

Build all domains and write them out::

for domain, df in design.domains().items():
    df.write_parquet(f"data/sdtm/{domain.lower()}.parquet")
Source code in src/fleet/sdtm/design.py
def domains(self) -> dict[str, pl.DataFrame]:
    """Derive every populated Trial Design domain.

    Returns:
        dict[str, pl.DataFrame]: Domain code → DataFrame, skipping
            domains whose design section is empty.

    Examples:
        Build all domains and write them out::

            for domain, df in design.domains().items():
                df.write_parquet(f"data/sdtm/{domain.lower()}.parquet")
    """
    sections = {
        "TE": (self.elements, self.to_te),
        "TA": (self.arms, self.to_ta),
        "TV": (self.visits, self.to_tv),
        "TS": (self.parameters, self.to_ts),
        "TI": (self.criteria, self.to_ti),
        "TD": (self.assessments, self.to_td),
        "TM": (self.milestones, self.to_tm),
    }
    return {domain: build() for domain, (section, build) in sections.items() if section}

audit

audit(*, dm=None)

Run the P21-style conformance pre-check over the derived domains.

Two design checks come first: arms with the same path (FLEETTD04), and an element that repeats in one arm with no per-position epoch (FLEETTD05).

Parameters:

Name Type Description Default
dm DataFrame | None

Optional DM domain for cross-checking ARMCD assignments.

None

Returns:

Type Description
DataFrame

pl.DataFrame: One row per finding (rule_id, severity, domain, message); empty when clean.

Examples:

Audit a design before export::

findings = design.audit()
errors = findings.filter(pl.col("severity") == "error")
Source code in src/fleet/sdtm/design.py
def audit(self, *, dm: pl.DataFrame | None = None) -> pl.DataFrame:
    """Run the P21-style conformance pre-check over the derived domains.

    Two design checks come first: arms with the same path
    (``FLEETTD04``), and an element that repeats in one arm with no
    per-position epoch (``FLEETTD05``).

    Args:
        dm: Optional DM domain for cross-checking ARMCD assignments.

    Returns:
        pl.DataFrame: One row per finding (``rule_id``, ``severity``,
            ``domain``, ``message``); empty when clean.

    Examples:
        Audit a design before export::

            findings = design.audit()
            errors = findings.filter(pl.col("severity") == "error")
    """
    from fleet.sdtm.tdd_audit import audit

    frames = self.domains()
    findings = audit(
        te=frames.get("TE"),
        ta=frames.get("TA"),
        tv=frames.get("TV"),
        # TS is always audited: an absent parameters section means every
        # FDA-required parameter is missing (rejection-level), not "skip".
        ts=frames.get("TS", self.to_ts()),
        ti=frames.get("TI"),
        dm=dm,
    )
    return pl.concat([pl.DataFrame(self._design_findings(), schema=findings.schema), findings])

from_yaml classmethod

from_yaml(path)

Load a design from a trial_design.yaml spec.

The YAML mirrors the model schema; a top-level trial_design: wrapper key is accepted so the section can live inside a larger study file. A repeated key or a key the model does not read raises, so a typo cannot drop a rule, a visit or an arm.

Parameters:

Name Type Description Default
path str | Path

Path to the YAML file.

required

Returns:

Name Type Description
StudyDesign StudyDesign

The validated design.

Raises:

Type Description
ConstructorError

When a mapping repeats a key.

ValidationError

When a key is unknown or a value is not valid.

Examples:

Load and build every domain::

design = fleet.StudyDesign.from_yaml("metadata/trial_design.yaml")
frames = design.domains()
Source code in src/fleet/sdtm/design.py
@classmethod
def from_yaml(cls, path: str | Path) -> StudyDesign:
    """Load a design from a ``trial_design.yaml`` spec.

    The YAML mirrors the model schema; a top-level ``trial_design:``
    wrapper key is accepted so the section can live inside a larger
    study file.  A repeated key or a key the model does not read
    raises, so a typo cannot drop a rule, a visit or an arm.

    Args:
        path: Path to the YAML file.

    Returns:
        StudyDesign: The validated design.

    Raises:
        yaml.constructor.ConstructorError: When a mapping repeats a key.
        pydantic.ValidationError: When a key is unknown or a value is
            not valid.

    Examples:
        Load and build every domain::

            design = fleet.StudyDesign.from_yaml("metadata/trial_design.yaml")
            frames = design.domains()
    """
    data = load_strict_yaml(Path(path).read_text(encoding="utf-8"))
    return cls(**_dates_to_iso(data.get("trial_design", data)))

to_yaml

to_yaml(path=None)

Serialise the design to YAML (the from_yaml round-trip).

Parameters:

Name Type Description Default
path str | Path | None

Optional file path to write to.

None

Returns:

Name Type Description
str str

The YAML document.

Examples:

Persist a design next to the study metadata::

design.to_yaml("metadata/trial_design.yaml")
Source code in src/fleet/sdtm/design.py
def to_yaml(self, path: str | Path | None = None) -> str:
    """Serialise the design to YAML (the ``from_yaml`` round-trip).

    Args:
        path: Optional file path to write to.

    Returns:
        str: The YAML document.

    Examples:
        Persist a design next to the study metadata::

            design.to_yaml("metadata/trial_design.yaml")
    """
    text = yaml.dump(
        self.model_dump(mode="json", exclude_defaults=True),
        default_flow_style=False,
        sort_keys=False,
        allow_unicode=True,
    )
    if path is not None:
        Path(path).write_text(text, encoding="utf-8")
    return text

from_mermaid classmethod

from_mermaid(mermaid_text, *, study_id, **sections)

Build a design from a Mermaid flowchart.

The diagram gives the elements and the arm paths. ARM comes from arm_names when given, else from the ARMCD.

Parameters:

Name Type Description Default
mermaid_text str

A Mermaid flowchart TD string (see :func:fleet.sdtm.tdd.parse_trial_design).

required
study_id str

The study identifier.

required
**sections Any

Extra design sections (arm_names=, visits=, criteria=, parameters=, ...) passed through to the constructor.

{}

Returns:

Name Type Description
StudyDesign StudyDesign

Design with elements and arm paths from the diagram.

Raises:

Type Description
ValueError

When the diagram cannot give a design (see :func:fleet.sdtm.tdd.parse_trial_design).

Examples:

Diagram in, datasets out::

design = fleet.StudyDesign.from_mermaid(diagram_text,
                                        study_id="CDISCPILOT01")
ta = design.to_ta()
Source code in src/fleet/sdtm/design.py
@classmethod
def from_mermaid(cls, mermaid_text: str, *, study_id: str, **sections: Any) -> StudyDesign:
    """Build a design from a Mermaid flowchart.

    The diagram gives the elements and the arm paths.  ARM comes from
    *arm_names* when given, else from the ARMCD.

    Args:
        mermaid_text: A Mermaid ``flowchart TD`` string (see
            :func:`fleet.sdtm.tdd.parse_trial_design`).
        study_id: The study identifier.
        **sections: Extra design sections (``arm_names=``, ``visits=``,
            ``criteria=``, ``parameters=``, ...) passed through to the
            constructor.

    Returns:
        StudyDesign: Design with elements and arm paths from the diagram.

    Raises:
        ValueError: When the diagram cannot give a design (see
            :func:`fleet.sdtm.tdd.parse_trial_design`).

    Examples:
        Diagram in, datasets out::

            design = fleet.StudyDesign.from_mermaid(diagram_text,
                                                    study_id="CDISCPILOT01")
            ta = design.to_ta()
    """
    te, ta = parse_trial_design(mermaid_text)
    arms: dict[str, list[str | ArmStep]] = {}
    arm_names: dict[str, str] = {}
    for row in sorted(ta.arms, key=lambda a: (a.armcd, a.taetord)):
        arms.setdefault(row.armcd, []).append(row.etcd)
        arm_names[row.armcd] = row.arm
    arm_names.update(sections.pop("arm_names", None) or {})
    return cls(
        study_id=study_id,
        elements=te.elements,
        arms=arms,
        arm_names=arm_names,
        **sections,
    )

to_mermaid

to_mermaid()

Render the design as a Mermaid flowchart for a review document.

Elements are grouped into epoch subgraphs; edges follow the arm paths, labelled with the ARMCD where the design branches (on the first edge for a single arm). The diagram is a review view: it carries ETCD, ELEMENT, TEDUR, the element epochs and the arm paths, but not ARM, TESTRL, TEENRL, TABRANCH, TATRANS or a per-position epoch. When :meth:from_mermaid cannot read the paths back (arms with the same path, a repeated element, a crossover), a warning says so. YAML (:meth:to_yaml) is the lossless round trip.

Returns:

Name Type Description
str str

A Mermaid flowchart TD document.

Examples:

Render for a design-review doc::

print(design.to_mermaid())
Source code in src/fleet/sdtm/design.py
def to_mermaid(self) -> str:
    """Render the design as a Mermaid flowchart for a review document.

    Elements are grouped into epoch subgraphs; edges follow the arm
    paths, labelled with the ARMCD where the design branches (on the
    first edge for a single arm).  The diagram is a review view: it
    carries ETCD, ELEMENT, TEDUR, the element epochs and the arm paths,
    but not ARM, TESTRL, TEENRL, TABRANCH, TATRANS or a per-position
    epoch.  When :meth:`from_mermaid` cannot read the paths back (arms
    with the same path, a repeated element, a crossover), a warning says
    so.  YAML (:meth:`to_yaml`) is the lossless round trip.

    Returns:
        str: A Mermaid ``flowchart TD`` document.

    Examples:
        Render for a design-review doc::

            print(design.to_mermaid())
    """
    lines = ["flowchart TD"]
    by_epoch: dict[str, list[TrialElement]] = {}
    for el in self.elements:
        by_epoch.setdefault(str(el.epoch), []).append(el)
    for i, (epoch, els) in enumerate(by_epoch.items()):
        lines.append(f"    subgraph EP{i}[{epoch}]")
        for el in els:
            dur = f"<br/>{el.tedur}" if el.tedur else ""
            name = el.element.replace('"', "#quot;")
            lines.append(f'        {el.etcd}["{name}{dur}"]')
        lines.append("    end")
    branch_at = 0 if len(self.arms) == 1 else self._branch_index()
    paths = {armcd: [_etcd(e) for e in path] for armcd, path in self.arms.items()}
    seen: set[tuple[str, str, str]] = set()
    for armcd, path in paths.items():
        for i, (src, dst) in enumerate(zip(path, path[1:])):
            label = f"|{armcd}|" if branch_at is not None and i == branch_at else ""
            edge = (src, label, dst)
            if edge not in seen:
                seen.add(edge)
                lines.append(f"    {src} -->{label} {dst}")
    text = "\n".join(lines)
    try:
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            _, ta = parse_trial_design(text)
        back: dict[str, list[str]] = {}
        for row in ta.arms:
            back.setdefault(row.armcd, []).append(row.etcd)
        lossless = back == paths and not any(
            isinstance(e, ArmStep) and e.epoch for path in self.arms.values() for e in path
        )
    except ValueError:
        lossless = False
    if not lossless:
        warnings.warn(
            "to_mermaid: from_mermaid cannot read this design back (arms with the same "
            "path, a repeated element, a crossover or a per-position epoch). Use to_yaml() "
            "for a lossless copy.",
            stacklevel=2,
        )
    return text

from_usdm classmethod

from_usdm(data, *, study_id=None)

Build a design from a CDISC USDM (DDF) study definition.

Maps the structural subset of USDM v3/v4 JSON: arms + epochs + elements + studyCells become the arm paths (with the epoch of each cell), encounters become visits, and eligibility criteria become TI rows. TI text comes from the v4 criterion item (or the v3 population criteria), with usdm:tag resolved through the syntax dictionary and XHTML removed. An identifier that starts with a digit takes an IN or EX prefix (SDTMIG 3.4 section 4.5.3).

ponytail: schedule timelines, objectives/endpoints, and biomedical concepts are intentionally not mapped — extend when a consumer needs them.

Parameters:

Name Type Description Default
data dict

Parsed USDM JSON (the {"study": ...} wrapper or the study object itself).

required
study_id str | None

Override for STUDYID; defaults to the first study identifier found in the USDM document.

None

Returns:

Name Type Description
StudyDesign StudyDesign

Design with the mapped structural subset.

Raises:

Type Description
ValueError

When a criterion has no text or no inclusion or exclusion category, a tag cannot be resolved, or two criteria give the same IETESTCD.

Examples:

Import an OpenStudyBuilder / DDF export::

import json
design = fleet.StudyDesign.from_usdm(
    json.loads(Path("usdm.json").read_text()),
    study_id="CDISCPILOT01",
)
Source code in src/fleet/sdtm/design.py
@classmethod
def from_usdm(cls, data: dict, *, study_id: str | None = None) -> StudyDesign:
    """Build a design from a CDISC USDM (DDF) study definition.

    Maps the structural subset of USDM v3/v4 JSON: arms + epochs +
    elements + studyCells become the arm paths (with the epoch of each
    cell), encounters become visits, and eligibility criteria become TI
    rows.  TI text comes from the v4 criterion item (or the v3
    population criteria), with ``usdm:tag`` resolved through the syntax
    dictionary and XHTML removed.  An identifier that starts with a
    digit takes an IN or EX prefix (SDTMIG 3.4 section 4.5.3).

    ponytail: schedule timelines, objectives/endpoints, and biomedical
    concepts are intentionally not mapped — extend when a consumer needs
    them.

    Args:
        data: Parsed USDM JSON (the ``{"study": ...}`` wrapper or the
            study object itself).
        study_id: Override for STUDYID; defaults to the first study
            identifier found in the USDM document.

    Returns:
        StudyDesign: Design with the mapped structural subset.

    Raises:
        ValueError: When a criterion has no text or no inclusion or
            exclusion category, a tag cannot be resolved, or two
            criteria give the same IETESTCD.

    Examples:
        Import an OpenStudyBuilder / DDF export::

            import json
            design = fleet.StudyDesign.from_usdm(
                json.loads(Path("usdm.json").read_text()),
                study_id="CDISCPILOT01",
            )
    """
    study = data.get("study", data)
    versions = study.get("versions") or study.get("studyVersions") or [study]
    version = versions[0]
    designs = version.get("studyDesigns") or []
    sd = designs[0] if designs else {}

    if study_id is None:
        idents = version.get("studyIdentifiers") or []
        study_id = next(
            (i.get("studyIdentifier") or i.get("text") for i in idents if isinstance(i, dict)),
            None,
        ) or (study.get("name") or "STUDY")

    def label(obj: dict) -> str:
        return obj.get("label") or obj.get("name") or obj.get("id", "")

    epoch_order = [e["id"] for e in sd.get("epochs", [])]
    epoch_label = {e["id"]: label(e).upper() for e in sd.get("epochs", [])}
    taken: set[str] = set()
    etcd_by_id: dict[str, str] = {}
    element_models: dict[str, dict] = {}
    for el in sd.get("elements", []):
        etcd = _sdtm_code(label(el), 8, taken)
        etcd_by_id[el["id"]] = etcd
        element_models[el["id"]] = {
            "etcd": etcd,
            "element": label(el)[:200],
            "testrl": (el.get("transitionStartRule") or {}).get("text", "")[:2000],
            "teenrl": (el.get("transitionEndRule") or {}).get("text", "")[:2000],
        }

    arm_label = {a["id"]: label(a) for a in sd.get("arms", [])}
    arm_taken: set[str] = set()
    armcd_by_id = {aid: _sdtm_code(name, 20, arm_taken) for aid, name in arm_label.items()}

    arms: dict[str, list[str | ArmStep]] = {}
    cells = sorted(
        sd.get("studyCells", []),
        key=lambda c: epoch_order.index(c["epochId"]) if c.get("epochId") in epoch_order else 0,
    )
    for cell in cells:
        armcd = armcd_by_id.get(cell.get("armId", ""))
        if armcd is None:
            continue
        cell_epoch = epoch_label.get(cell.get("epochId", ""), "TREATMENT")
        for element_id in cell.get("elementIds", []):
            if element_id in element_models:
                epoch = element_models[element_id].setdefault("epoch", cell_epoch)
                etcd = etcd_by_id[element_id]
                arms.setdefault(armcd, []).append(
                    etcd if epoch == cell_epoch else ArmStep(etcd=etcd, epoch=cell_epoch)
                )

    elements = [
        TrialElement(**{"epoch": "TREATMENT", **model}) for model in element_models.values()
    ]

    visits = [
        TrialVisit(visitnum=num, visit=label(enc)[:200])
        for num, enc in enumerate(sd.get("encounters", []), start=1)
    ]

    return cls(
        study_id=study_id,
        elements=elements,
        arms=arms,
        arm_names={armcd_by_id[aid]: name for aid, name in arm_label.items()},
        visits=visits,
        criteria=_usdm_criteria(study, version, sd),
    )

load_strict_yaml

load_strict_yaml(text)

Parse YAML like yaml.safe_load, but raise on a repeated key.

Parameters:

Name Type Description Default
text str

The YAML document.

required

Returns:

Name Type Description
Any Any

The parsed document.

Raises:

Type Description
ConstructorError

When a mapping repeats a key.

Examples:

Load a trial design spec::

data = load_strict_yaml(Path("trial_design.yaml").read_text())
Source code in src/fleet/sdtm/design.py
def load_strict_yaml(text: str) -> Any:
    """Parse YAML like ``yaml.safe_load``, but raise on a repeated key.

    Args:
        text: The YAML document.

    Returns:
        Any: The parsed document.

    Raises:
        yaml.constructor.ConstructorError: When a mapping repeats a key.

    Examples:
        Load a trial design spec::

            data = load_strict_yaml(Path("trial_design.yaml").read_text())
    """
    return yaml.load(text, Loader=_StrictLoader)  # noqa: S506 - a SafeLoader subclass

options: show_source: false heading_level: 2 members_order: source show_root_heading: true

fleet.sdtm.tdd_audit

Trial Design conformance pre-check — a P21-style dry run, offline.

Encodes the published, machine-checkable conformance rules that hit Trial Design domains hardest: the SD-series cross-domain structural checks and the FDA Technical Conformance Guide TS parameter profile (TS is the only rejection-level dataset — eCTD Technical Rejection Criterion 1734).

Rule IDs reference the public Pinnacle 21 Community / FDA business rule identifiers so findings can be cross-checked against a real P21 report. Sources: FDA TCG TS parameter list (fda.gov/media/153632), PHUSE US Connect 2026 paper DS22, PharmaSUG 2023 DS-149.

ponytail: a curated high-signal subset, not the full 100+ TDM rule catalog — fleet validate runs the CDISC Rules Engine for exhaustive coverage.

audit

audit(
    *, te=None, ta=None, tv=None, ts=None, ti=None, dm=None
)

Cross-check Trial Design domains against published conformance rules.

Every argument is optional — checks run only when the domains they need are present. Inputs may be DataFrames, LazyFrames, or the TDD collection models (TrialElements, TrialArms, ...).

Parameters:

Name Type Description Default
te Any

Trial Elements domain.

None
ta Any

Trial Arms domain.

None
tv Any

Trial Visits domain.

None
ts Any

Trial Summary domain.

None
ti Any

Trial Inclusion/Exclusion domain.

None
dm Any

Demographics domain, for ARMCD cross-checks.

None

Returns:

Type Description
DataFrame

pl.DataFrame: One row per finding with rule_id, severity (error/warning), domain, and message; empty (schema preserved) when everything passes.

Examples:

Pre-validate before shipping to P21::

findings = fleet.sdtm.tdd_audit.audit(te=te, ta=ta, ts=ts)
assert findings.filter(pl.col("severity") == "error").is_empty()
Source code in src/fleet/sdtm/tdd_audit.py
def audit(
    *,
    te: Any = None,
    ta: Any = None,
    tv: Any = None,
    ts: Any = None,
    ti: Any = None,
    dm: Any = None,
) -> pl.DataFrame:
    """Cross-check Trial Design domains against published conformance rules.

    Every argument is optional — checks run only when the domains they need
    are present.  Inputs may be DataFrames, LazyFrames, or the TDD
    collection models (``TrialElements``, ``TrialArms``, ...).

    Args:
        te: Trial Elements domain.
        ta: Trial Arms domain.
        tv: Trial Visits domain.
        ts: Trial Summary domain.
        ti: Trial Inclusion/Exclusion domain.
        dm: Demographics domain, for ARMCD cross-checks.

    Returns:
        pl.DataFrame: One row per finding with ``rule_id``, ``severity``
            (``error``/``warning``), ``domain``, and ``message``; empty
            (schema preserved) when everything passes.

    Examples:
        Pre-validate before shipping to P21::

            findings = fleet.sdtm.tdd_audit.audit(te=te, ta=ta, ts=ts)
            assert findings.filter(pl.col("severity") == "error").is_empty()
    """
    te, ta, tv, ts, ti, dm = (_to_df(f) for f in (te, ta, tv, ts, ti, dm))
    findings: list[dict[str, str]] = []

    def add(rule_id: str, severity: str, domain: str, message: str) -> None:
        findings.append(
            {"rule_id": rule_id, "severity": severity, "domain": domain, "message": message}
        )

    # -- TE structural ------------------------------------------------- #
    if te is not None:
        for etcd in te.filter(pl.col("ETCD").str.len_chars() > 8)["ETCD"].to_list():
            add("SD1009", "error", "TE", f"ETCD '{etcd}' exceeds 8 characters")
        if {"TEENRL", "TEDUR"}.issubset(te.columns):
            unbounded = te.filter(
                pl.col("TEENRL").fill_null("").eq("") & pl.col("TEDUR").fill_null("").eq("")
            )
            for etcd in unbounded["ETCD"].to_list():
                add("SD0089", "error", "TE", f"Element '{etcd}' has neither TEENRL nor TEDUR")
        dup = te.group_by("ETCD").len().filter(pl.col("len") > 1)["ETCD"].to_list()
        for etcd in dup:
            add("SD1271", "error", "TE", f"Duplicate ETCD '{etcd}' in TE")

    # -- TA structural ------------------------------------------------- #
    if ta is not None:
        for armcd in ta.filter(pl.col("ARMCD").str.len_chars() > 20)["ARMCD"].unique().to_list():
            add("SD1004", "error", "TA", f"ARMCD '{armcd}' exceeds 20 characters")
        dup_ord = ta.group_by("ARMCD", "TAETORD").len().filter(pl.col("len") > 1)["ARMCD"].unique()
        for armcd in dup_ord.to_list():
            add("SD1052", "error", "TA", f"TAETORD values not unique within ARMCD '{armcd}'")
        for col, rule in (("ARMCD", "SD1033"), ("ARM", "SD1034")):
            other = "ARM" if col == "ARMCD" else "ARMCD"
            bad = ta.group_by(col).agg(pl.col(other).n_unique().alias("n")).filter(pl.col("n") > 1)
            for value in bad[col].to_list():
                add(rule, "error", "TA", f"{col} '{value}' maps to multiple {other} values")
        for armcd in _RESERVED_ARMCDS:
            if armcd in ta["ARMCD"].to_list():
                add("SD1053", "error", "TA", f"Reserved ARMCD '{armcd}' must not appear in TA")

    # -- TA ↔ TE consistency ------------------------------------------- #
    if ta is not None and te is not None:
        te_pairs = te.select("ETCD", "ELEMENT").unique()
        stray = (
            ta.filter(pl.col("ETCD") != "UNPLAN")
            .select("ETCD", "ELEMENT")
            .unique()
            .join(te_pairs, on=["ETCD", "ELEMENT"], how="anti")
        )
        for row in stray.iter_rows(named=True):
            add(
                "SD0067",
                "error",
                "TA",
                f"(ETCD '{row['ETCD']}', ELEMENT '{row['ELEMENT']}') in TA does not match TE",
            )
        unused = te.join(ta.select("ETCD").unique(), on="ETCD", how="anti")["ETCD"].to_list()
        for etcd in unused:
            add("SD1378", "warning", "TE", f"Element '{etcd}' defined in TE but used by no arm")

    # -- TV ------------------------------------------------------------- #
    if tv is not None:
        dup = tv.group_by("VISITNUM").len().filter(pl.col("len") > 1)["VISITNUM"].to_list()
        for num in dup:
            add("SD1064", "error", "TV", f"Duplicate VISITNUM {num} in TV")
        if "ARMCD" in tv.columns:
            for armcd in _RESERVED_ARMCDS:
                if armcd in tv["ARMCD"].to_list():
                    add("SD1053", "error", "TV", f"Reserved ARMCD '{armcd}' must not appear in TV")
            if ta is not None:
                known = set(ta["ARMCD"].to_list())
                stray_arms = {a for a in tv["ARMCD"].to_list() if a and a not in known}
                for armcd in stray_arms:
                    add("FLEETTD01", "error", "TV", f"TV.ARMCD '{armcd}' not defined in TA")

    # -- TI ------------------------------------------------------------- #
    if ti is not None:
        for code in ti.filter(
            pl.col("IETESTCD").str.len_chars().gt(8) | pl.col("IETESTCD").str.contains(r"^\d")
        )["IETESTCD"].to_list():
            add("SD0018", "error", "TI", f"IETESTCD '{code}' invalid (>8 chars or leading digit)")
        vers = ["TIVERS"] if "TIVERS" in ti.columns else []
        dup = ti.group_by("IETESTCD", *vers).len().filter(pl.col("len") > 1)["IETESTCD"].to_list()
        for code in dup:
            add("SD1286", "error", "TI", f"Duplicate IETESTCD '{code}' within protocol version")

    # -- Char values over the XPT V5 limit ------------------------------- #
    for domain, frame in (("TE", te), ("TA", ta), ("TV", tv), ("TS", ts), ("TI", ti)):
        if frame is None:
            continue
        for col, dtype in frame.schema.items():
            if dtype != pl.String or (domain == "TS" and col.startswith("TSVAL")):
                continue
            long = frame.filter(pl.col(col).str.len_chars() > 200).height
            if long:
                add(
                    "FLEETTD03",
                    "warning",
                    domain,
                    f"{domain}.{col} holds {long} value(s) over 200 characters, the XPT V5 "
                    "limit. Reword the text; only TSVAL splits into TSVAL1-TSVALn.",
                )

    # -- DM ↔ TA -------------------------------------------------------- #
    if dm is not None and ta is not None and "ARMCD" in dm.columns:
        ta_arms = set(ta["ARMCD"].to_list())
        dm_arms = {a for a in dm["ARMCD"].to_list() if a}
        for armcd in sorted(dm_arms - ta_arms - set(_RESERVED_ARMCDS)):
            add("FLEETTD02", "error", "DM", f"DM.ARMCD '{armcd}' not defined in TA")
        for armcd in sorted(ta_arms - dm_arms):
            add("SD1354", "warning", "TA", f"ARMCD '{armcd}' in TA has no subjects in DM")

    # -- TS FDA profile -------------------------------------------------- #
    if ts is not None:
        # An empty TS frame (no rows / no columns) still runs the profile:
        # every required parameter is then missing.
        if "TSPARMCD" in ts.columns:
            present = set(ts["TSPARMCD"].to_list())
            values = {
                row["TSPARMCD"]: row["TSVAL"]
                for row in ts.select("TSPARMCD", "TSVAL").iter_rows(named=True)
            }
        else:
            present, values = set(), {}
        for parm, rule in TS_REQUIRED.items():
            if parm not in present:
                extra = " (FDA rejection criterion 1734)" if parm == "SSTDTC" else ""
                add(rule, "error", "TS", f"Required TS parameter '{parm}' is missing{extra}")
        for trigger, value, required, rule in TS_CONDITIONAL:
            if values.get(trigger, "").upper() == value and required not in present:
                add(
                    rule,
                    "error",
                    "TS",
                    f"TS parameter '{required}' is required when {trigger}={value}",
                )
        randqt = values.get("RANDQT")
        if randqt is not None:
            try:
                ok = 0.0 <= float(randqt) <= 1.0
            except ValueError:
                ok = False
            if not ok:
                add("SD1269", "error", "TS", f"RANDQT '{randqt}' is not a number in [0, 1]")

    return pl.DataFrame(findings, schema=_FINDING_SCHEMA)

options: show_source: false heading_level: 2 members_order: source show_root_heading: true

fleet.sdtm.tdd

Trial Design Domain (TDD) Pydantic models.

Provides row models, collection models, constrained types, and an Epoch enum for the CDISC Trial Design domains: TE, TA, TV, TS, TI, TD, TM (protocol-reference) and SV, SE (subject-level).

Each row model maps one record in the target SDTM domain and carries a _SDTM_MAP that translates Python-friendly field names to official CDISC variable names.

Each collection model wraps a list of row models and enforces integrity constraints (uniqueness, ordering, FK references) at construction time via Pydantic @model_validator. The to_polars() method converts the validated collection into a pl.DataFrame with CDISC column names.

Usage::

from fleet.sdtm.tdd import TrialElement, TrialElements, Epoch

te = TrialElements(elements=[
    TrialElement(etcd="SCRN", element="Screening",
                 tedur="P14D", epoch=Epoch.SCREENING),
    TrialElement(etcd="TRT", element="Treatment",
                 tedur="P84D", epoch=Epoch.TREATMENT),
])
df = te.to_polars()

Epoch

Bases: StrEnum

EPOCH (C99079) — all 14 CDISC-standard trial epoch values.

Source code in src/fleet/sdtm/tdd.py
class Epoch(StrEnum):
    """EPOCH (C99079) — all 14 CDISC-standard trial epoch values."""

    SCREENING = "SCREENING"
    BASELINE = "BASELINE"
    RUN_IN = "RUN-IN"
    WASHOUT = "WASHOUT"
    TREATMENT = "TREATMENT"
    BLINDED_TREATMENT = "BLINDED TREATMENT"
    OPEN_LABEL_TREATMENT = "OPEN LABEL TREATMENT"
    CONTINUATION_TREATMENT = "CONTINUATION TREATMENT"
    INDUCTION_TREATMENT = "INDUCTION TREATMENT"
    FOLLOW_UP = "FOLLOW-UP"
    LONG_TERM_FOLLOW_UP = "LONG-TERM FOLLOW-UP"
    OBSERVATION = "OBSERVATION"
    PRE_SCREENING = "PRE-SCREENING"

    _concept_id: ClassVar[str] = "C99079"

TrialElement

Bases: BaseModel

One row in the TE (Trial Elements) domain.

epoch is a design-time attribute: SDTMIG 3.4 has no EPOCH variable in TE, so it is excluded from to_polars() output — but it drives the element→epoch mapping used when deriving TA and SE.

Source code in src/fleet/sdtm/tdd.py
class TrialElement(BaseModel):
    """One row in the TE (Trial Elements) domain.

    ``epoch`` is a design-time attribute: SDTMIG 3.4 has no EPOCH variable
    in TE, so it is excluded from ``to_polars()`` output — but it drives the
    element→epoch mapping used when deriving TA and SE.
    """

    model_config = ConfigDict(extra="forbid")

    _SDTM_MAP: ClassVar[dict[str, str]] = {
        "etcd": "ETCD",
        "element": "ELEMENT",
        "testrl": "TESTRL",
        "teenrl": "TEENRL",
        "tedur": "TEDUR",
    }

    etcd: ElementCode
    element: str = Field(min_length=1, max_length=200)
    testrl: RuleExpression = ""
    teenrl: RuleExpression = ""
    tedur: ISODuration | Literal[""] = ""
    epoch: EpochLike

TrialArm

Bases: BaseModel

One row-per-element in the TA (Trial Arms) domain.

Source code in src/fleet/sdtm/tdd.py
class TrialArm(BaseModel):
    """One row-per-element in the TA (Trial Arms) domain."""

    model_config = ConfigDict(extra="forbid")

    _SDTM_MAP: ClassVar[dict[str, str]] = {
        "armcd": "ARMCD",
        "arm": "ARM",
        "taetord": "TAETORD",
        "etcd": "ETCD",
        "element": "ELEMENT",
        "tabranch": "TABRANCH",
        "tatrans": "TATRANS",
        "epoch": "EPOCH",
    }

    armcd: ArmCode
    arm: str = Field(min_length=1, max_length=200)
    taetord: int = Field(ge=1)
    etcd: ElementCode
    element: str = Field(min_length=1, max_length=200)
    tabranch: RuleExpression = ""
    tatrans: RuleExpression = ""
    epoch: EpochLike

TrialVisit

Bases: BaseModel

One row in the TV (Trial Visits) domain.

Source code in src/fleet/sdtm/tdd.py
class TrialVisit(BaseModel):
    """One row in the TV (Trial Visits) domain."""

    model_config = ConfigDict(extra="forbid")

    _SDTM_MAP: ClassVar[dict[str, str]] = {
        "visitnum": "VISITNUM",
        "visit": "VISIT",
        "visitdy": "VISITDY",
        "armcd": "ARMCD",
        "arm": "ARM",
        "tvstrl": "TVSTRL",
        "tvenrl": "TVENRL",
    }

    visitnum: int = Field(ge=1)
    visit: str = Field(min_length=1, max_length=200)
    visitdy: int | None = None
    armcd: ArmCode | Literal[""] = ""
    arm: str = Field(default="", max_length=200)
    tvstrl: RuleExpression = ""
    tvenrl: RuleExpression = ""

TrialParameter

Bases: BaseModel

One row in the TS (Trial Summary) domain.

Source code in src/fleet/sdtm/tdd.py
class TrialParameter(BaseModel):
    """One row in the TS (Trial Summary) domain."""

    model_config = ConfigDict(extra="forbid")

    _SDTM_MAP: ClassVar[dict[str, str]] = {
        "tsseq": "TSSEQ",
        "tsgrpid": "TSGRPID",
        "tsparmcd": "TSPARMCD",
        "tsparm": "TSPARM",
        "tsval": "TSVAL",
        "tsvalnf": "TSVALNF",
        "tsvalcd": "TSVALCD",
        "tsvcdref": "TSVCDREF",
        "tsvcdver": "TSVCDVER",
    }

    tsseq: int = Field(default=1, ge=1)
    tsgrpid: str = ""
    tsparmcd: str = Field(min_length=1, max_length=8, pattern=r"^[A-Z0-9_]+$")
    tsparm: str = Field(min_length=1, max_length=40)
    tsval: str = ""
    tsvalnf: str = ""
    tsvalcd: str = ""
    tsvcdref: str = ""
    tsvcdver: str = ""

TrialCriterion

Bases: BaseModel

One row in the TI (Trial Inclusion/Exclusion) domain.

Source code in src/fleet/sdtm/tdd.py
class TrialCriterion(BaseModel):
    """One row in the TI (Trial Inclusion/Exclusion) domain."""

    model_config = ConfigDict(extra="forbid")

    _SDTM_MAP: ClassVar[dict[str, str]] = {
        "ietestcd": "IETESTCD",
        "ietest": "IETEST",
        "iecat": "IECAT",
        "iescat": "IESCAT",
        "tirl": "TIRL",
        "tivers": "TIVERS",
    }

    ietestcd: str = Field(min_length=1, max_length=8, pattern=r"^[A-Z0-9_]+$")
    ietest: str = Field(min_length=1, max_length=200)
    iecat: Literal["INCLUSION", "EXCLUSION"]
    iescat: str = ""
    tirl: RuleExpression = ""
    tivers: str = ""

TrialDiseaseAssessment

Bases: BaseModel

One row in the TD (Trial Disease Assessments) domain.

Source code in src/fleet/sdtm/tdd.py
class TrialDiseaseAssessment(BaseModel):
    """One row in the TD (Trial Disease Assessments) domain."""

    model_config = ConfigDict(extra="forbid")

    _SDTM_MAP: ClassVar[dict[str, str]] = {
        "tdorder": "TDORDER",
        "tdancvar": "TDANCVAR",
        "tdstoff": "TDSTOFF",
        "tdtgtpai": "TDTGTPAI",
        "tdminpai": "TDMINPAI",
        "tdmaxpai": "TDMAXPAI",
        "tdnumrpt": "TDNUMRPT",
    }

    tdorder: int = Field(ge=1)
    tdancvar: str = Field(min_length=1, max_length=8)
    tdstoff: ISODuration | Literal[""] = ""
    tdtgtpai: ISODuration
    tdminpai: ISODuration | Literal[""] = ""
    tdmaxpai: ISODuration | Literal[""] = ""
    tdnumrpt: int = Field(ge=1)

TrialMilestone

Bases: BaseModel

One row in the TM (Trial Disease Milestones) domain.

Source code in src/fleet/sdtm/tdd.py
class TrialMilestone(BaseModel):
    """One row in the TM (Trial Disease Milestones) domain."""

    model_config = ConfigDict(extra="forbid")

    _SDTM_MAP: ClassVar[dict[str, str]] = {
        "midstype": "MIDSTYPE",
        "tmdef": "TMDEF",
        "tmrpt": "TMRPT",
    }

    midstype: str = Field(min_length=1, max_length=200)
    tmdef: str = Field(min_length=1, max_length=2000)
    tmrpt: Literal["Y", "N"]

TrialElements

Bases: BaseModel

Typed collection of TE rows with TDD-specific integrity validation.

Source code in src/fleet/sdtm/tdd.py
class TrialElements(BaseModel):
    """Typed collection of TE rows with TDD-specific integrity validation."""

    elements: list[TrialElement]

    @model_validator(mode="after")
    def check_unique_etcd(self) -> TrialElements:
        codes = [e.etcd for e in self.elements]
        dupes = [c for c in codes if codes.count(c) > 1]
        if dupes:
            raise ValueError(f"Duplicate ETCD: {set(dupes)}")
        return self

    @model_validator(mode="after")
    def check_epochs_consistent(self) -> TrialElements:
        mapping: dict[str, Epoch] = {}
        for e in self.elements:
            if e.etcd in mapping and mapping[e.etcd] != e.epoch:
                raise ValueError(f"ETCD {e.etcd} maps to multiple EPOCHs")
            mapping[e.etcd] = e.epoch
        return self

    def to_polars(self) -> pl.DataFrame:
        """Convert validated elements to a Polars DataFrame with SDTM names.

        Returns:
            pl.DataFrame: DataFrame with columns named per CDISC SDTM (e.g.
                ``ETCD``, ``ELEMENT``, ``EPOCH``).

        Examples:
            Materialise trial elements::

                te = TrialElements(elements=[...])
                df = te.to_polars()
        """
        return _rows_to_polars(self.elements)

to_polars

to_polars()

Convert validated elements to a Polars DataFrame with SDTM names.

Returns:

Type Description
DataFrame

pl.DataFrame: DataFrame with columns named per CDISC SDTM (e.g. ETCD, ELEMENT, EPOCH).

Examples:

Materialise trial elements::

te = TrialElements(elements=[...])
df = te.to_polars()
Source code in src/fleet/sdtm/tdd.py
def to_polars(self) -> pl.DataFrame:
    """Convert validated elements to a Polars DataFrame with SDTM names.

    Returns:
        pl.DataFrame: DataFrame with columns named per CDISC SDTM (e.g.
            ``ETCD``, ``ELEMENT``, ``EPOCH``).

    Examples:
        Materialise trial elements::

            te = TrialElements(elements=[...])
            df = te.to_polars()
    """
    return _rows_to_polars(self.elements)

TrialArms

Bases: BaseModel

Typed collection of TA rows with TDD integrity validation.

Source code in src/fleet/sdtm/tdd.py
class TrialArms(BaseModel):
    """Typed collection of TA rows with TDD integrity validation."""

    arms: list[TrialArm]

    @model_validator(mode="after")
    def check_taetord_sequential(self) -> TrialArms:
        by_arm: dict[str, list[int]] = {}
        for a in self.arms:
            by_arm.setdefault(a.armcd, []).append(a.taetord)
        for armcd, orders in by_arm.items():
            expected = list(range(1, len(orders) + 1))
            if sorted(orders) != expected:
                raise ValueError(
                    f"TAETORD for {armcd} must be sequential 1..N, got {sorted(orders)}"
                )
        return self

    def to_polars(self) -> pl.DataFrame:
        """Convert validated arms to a Polars DataFrame with SDTM names.

        Returns:
            pl.DataFrame: DataFrame with columns named per CDISC SDTM (e.g.
                ``ARMCD``, ``ARM``, ``TAETORD``, ``ETCD``).

        Examples:
            Materialise trial arms::

                ta = TrialArms(arms=[...])
                df = ta.to_polars()
        """
        return _rows_to_polars(self.arms)

to_polars

to_polars()

Convert validated arms to a Polars DataFrame with SDTM names.

Returns:

Type Description
DataFrame

pl.DataFrame: DataFrame with columns named per CDISC SDTM (e.g. ARMCD, ARM, TAETORD, ETCD).

Examples:

Materialise trial arms::

ta = TrialArms(arms=[...])
df = ta.to_polars()
Source code in src/fleet/sdtm/tdd.py
def to_polars(self) -> pl.DataFrame:
    """Convert validated arms to a Polars DataFrame with SDTM names.

    Returns:
        pl.DataFrame: DataFrame with columns named per CDISC SDTM (e.g.
            ``ARMCD``, ``ARM``, ``TAETORD``, ``ETCD``).

    Examples:
        Materialise trial arms::

            ta = TrialArms(arms=[...])
            df = ta.to_polars()
    """
    return _rows_to_polars(self.arms)

TrialVisits

Bases: BaseModel

Typed collection of TV rows with TDD integrity validation.

Source code in src/fleet/sdtm/tdd.py
class TrialVisits(BaseModel):
    """Typed collection of TV rows with TDD integrity validation."""

    visits: list[TrialVisit]

    @model_validator(mode="after")
    def check_visitnum_unique(self) -> TrialVisits:
        nums = [v.visitnum for v in self.visits]
        if len(nums) != len(set(nums)):
            raise ValueError("Duplicate VISITNUM values")
        return self

    @model_validator(mode="after")
    def check_visitdy_ordering(self) -> TrialVisits:
        sorted_visits = sorted(self.visits, key=lambda v: v.visitnum)
        days = [v.visitdy for v in sorted_visits if v.visitdy is not None]
        if days != sorted(days):
            raise ValueError("VISITDY must increase with VISITNUM")
        return self

    @classmethod
    def from_schedule(
        cls,
        schedule: list[tuple[str, int]],
        *,
        anchor: str = "RANDOMIZATION",
        window: int | tuple[int, int] | None = None,
    ) -> TrialVisits:
        """Build a visit schedule from day offsets relative to an anchor event.

        Visits are sorted by offset; ``VISITNUM`` is assigned 1..N in that
        order and ``VISITDY`` follows the CDISC no-day-zero convention
        (offset 0 → day 1, negative offsets stay negative).  ``TVSTRL`` is
        rendered deterministically from the offset, anchor, and window, so
        rule text stays consistent across visits and study amendments.

        Args:
            schedule: ``(visit_name, day_offset)`` pairs; offsets are days
                relative to the *anchor* event (day 0).
            anchor: Name of the anchoring milestone (e.g. ``"RANDOMIZATION"``).
            window: Allowed deviation in study days (no Day 0, as
                ``visit_map``) — a single int for a symmetric window or a
                ``(before, after)`` tuple.

        Returns:
            TrialVisits: A validated collection ready for ``add_visits()``.

        Examples:
            Build a 12-week schedule anchored on randomization::

                tv_rows = TrialVisits.from_schedule(
                    [("Screening", -14), ("Baseline", 0), ("Week 4", 28),
                     ("Week 8", 56), ("Week 12", 84)],
                    anchor="RANDOMIZATION",
                    window=3,
                )
                tv = (
                    fleet.frame(pl.DataFrame()).sdtm
                    .fetch_structure("TV")
                    .study_header("CDISCPILOT01", "TV")
                    .add_visits(tv_rows)
                    .to_frame()
                )
        """
        before, after = (window, window) if isinstance(window, int) else (window or (0, 0))
        window_txt = f"; window -{before}/+{after} study days, no Day 0" if window else ""
        visits = []
        for num, (name, offset) in enumerate(sorted(schedule, key=lambda p: p[1]), start=1):
            if offset == 0:
                rule = f"On day of {anchor}"
            elif offset > 0:
                rule = f"{offset} days after {anchor}"
            else:
                rule = f"{-offset} days before {anchor}"
            visits.append(
                TrialVisit(
                    visitnum=num,
                    visit=name,
                    visitdy=offset + 1 if offset >= 0 else offset,
                    tvstrl=rule + window_txt,
                )
            )
        return cls(visits=visits)

    def to_polars(self) -> pl.DataFrame:
        """Convert validated visits to a Polars DataFrame with SDTM names.

        Returns:
            pl.DataFrame: DataFrame with columns named per CDISC SDTM (e.g.
                ``VISITNUM``, ``VISIT``, ``VISITDY``).

        Examples:
            Materialise trial visits::

                tv = TrialVisits(visits=[...])
                df = tv.to_polars()
        """
        return _rows_to_polars(self.visits)

from_schedule classmethod

from_schedule(
    schedule, *, anchor="RANDOMIZATION", window=None
)

Build a visit schedule from day offsets relative to an anchor event.

Visits are sorted by offset; VISITNUM is assigned 1..N in that order and VISITDY follows the CDISC no-day-zero convention (offset 0 → day 1, negative offsets stay negative). TVSTRL is rendered deterministically from the offset, anchor, and window, so rule text stays consistent across visits and study amendments.

Parameters:

Name Type Description Default
schedule list[tuple[str, int]]

(visit_name, day_offset) pairs; offsets are days relative to the anchor event (day 0).

required
anchor str

Name of the anchoring milestone (e.g. "RANDOMIZATION").

'RANDOMIZATION'
window int | tuple[int, int] | None

Allowed deviation in study days (no Day 0, as visit_map) — a single int for a symmetric window or a (before, after) tuple.

None

Returns:

Name Type Description
TrialVisits TrialVisits

A validated collection ready for add_visits().

Examples:

Build a 12-week schedule anchored on randomization::

tv_rows = TrialVisits.from_schedule(
    [("Screening", -14), ("Baseline", 0), ("Week 4", 28),
     ("Week 8", 56), ("Week 12", 84)],
    anchor="RANDOMIZATION",
    window=3,
)
tv = (
    fleet.frame(pl.DataFrame()).sdtm
    .fetch_structure("TV")
    .study_header("CDISCPILOT01", "TV")
    .add_visits(tv_rows)
    .to_frame()
)
Source code in src/fleet/sdtm/tdd.py
@classmethod
def from_schedule(
    cls,
    schedule: list[tuple[str, int]],
    *,
    anchor: str = "RANDOMIZATION",
    window: int | tuple[int, int] | None = None,
) -> TrialVisits:
    """Build a visit schedule from day offsets relative to an anchor event.

    Visits are sorted by offset; ``VISITNUM`` is assigned 1..N in that
    order and ``VISITDY`` follows the CDISC no-day-zero convention
    (offset 0 → day 1, negative offsets stay negative).  ``TVSTRL`` is
    rendered deterministically from the offset, anchor, and window, so
    rule text stays consistent across visits and study amendments.

    Args:
        schedule: ``(visit_name, day_offset)`` pairs; offsets are days
            relative to the *anchor* event (day 0).
        anchor: Name of the anchoring milestone (e.g. ``"RANDOMIZATION"``).
        window: Allowed deviation in study days (no Day 0, as
            ``visit_map``) — a single int for a symmetric window or a
            ``(before, after)`` tuple.

    Returns:
        TrialVisits: A validated collection ready for ``add_visits()``.

    Examples:
        Build a 12-week schedule anchored on randomization::

            tv_rows = TrialVisits.from_schedule(
                [("Screening", -14), ("Baseline", 0), ("Week 4", 28),
                 ("Week 8", 56), ("Week 12", 84)],
                anchor="RANDOMIZATION",
                window=3,
            )
            tv = (
                fleet.frame(pl.DataFrame()).sdtm
                .fetch_structure("TV")
                .study_header("CDISCPILOT01", "TV")
                .add_visits(tv_rows)
                .to_frame()
            )
    """
    before, after = (window, window) if isinstance(window, int) else (window or (0, 0))
    window_txt = f"; window -{before}/+{after} study days, no Day 0" if window else ""
    visits = []
    for num, (name, offset) in enumerate(sorted(schedule, key=lambda p: p[1]), start=1):
        if offset == 0:
            rule = f"On day of {anchor}"
        elif offset > 0:
            rule = f"{offset} days after {anchor}"
        else:
            rule = f"{-offset} days before {anchor}"
        visits.append(
            TrialVisit(
                visitnum=num,
                visit=name,
                visitdy=offset + 1 if offset >= 0 else offset,
                tvstrl=rule + window_txt,
            )
        )
    return cls(visits=visits)

to_polars

to_polars()

Convert validated visits to a Polars DataFrame with SDTM names.

Returns:

Type Description
DataFrame

pl.DataFrame: DataFrame with columns named per CDISC SDTM (e.g. VISITNUM, VISIT, VISITDY).

Examples:

Materialise trial visits::

tv = TrialVisits(visits=[...])
df = tv.to_polars()
Source code in src/fleet/sdtm/tdd.py
def to_polars(self) -> pl.DataFrame:
    """Convert validated visits to a Polars DataFrame with SDTM names.

    Returns:
        pl.DataFrame: DataFrame with columns named per CDISC SDTM (e.g.
            ``VISITNUM``, ``VISIT``, ``VISITDY``).

    Examples:
        Materialise trial visits::

            tv = TrialVisits(visits=[...])
            df = tv.to_polars()
    """
    return _rows_to_polars(self.visits)

TrialParameters

Bases: BaseModel

Typed collection of TS rows.

Source code in src/fleet/sdtm/tdd.py
class TrialParameters(BaseModel):
    """Typed collection of TS rows."""

    parameters: list[TrialParameter]

    @model_validator(mode="after")
    def check_unique_tsparmcd(self) -> TrialParameters:
        keys = [(p.tsparmcd, p.tsseq) for p in self.parameters]
        if len(keys) != len(set(keys)):
            dupes = {k for k in keys if keys.count(k) > 1}
            raise ValueError(f"Duplicate (TSPARMCD, TSSEQ) pairs: {sorted(dupes)}")
        return self

    @classmethod
    def from_ctgov(cls, nct_id: str, *, timeout: float = 30.0) -> TrialParameters:
        """Seed TS parameters from a ClinicalTrials.gov registration.

        Fetches the study record from the ClinicalTrials.gov v2 JSON API and
        maps the cleanly-derivable fields to TS parameters.  The result is a
        **starting point**, not a submission-ready TS: dictionary-bound
        parameters (INDIC/SNOMED, TRT/UNII, PCLAS/MED-RT) are deliberately
        not guessed and must be added by the study team.

        Args:
            nct_id: ClinicalTrials.gov identifier (e.g. ``"NCT01234567"``).
            timeout: HTTP timeout in seconds.

        Returns:
            TrialParameters: Collection with one row per derivable parameter
                (repeating parameters such as FCNTRY get incrementing TSSEQ).

        Raises:
            urllib.error.HTTPError: When the NCT ID is unknown to the registry.

        Examples:
            Seed TS from the registry, then extend and build::

                ts_rows = TrialParameters.from_ctgov("NCT00048217")
                ts = (
                    fleet.frame(pl.DataFrame()).sdtm
                    .fetch_structure("TS")
                    .study_header("CDISCPILOT01", "TS")
                    .add_parameters(ts_rows)
                    .to_frame()
                )
        """
        import json
        import urllib.request

        # ponytail: stdlib on purpose — ctgov's WAF 403s httpx's TLS/client
        # fingerprint in some environments while urllib passes.
        req = urllib.request.Request(
            f"https://clinicaltrials.gov/api/v2/studies/{nct_id}",
            headers={
                "User-Agent": "fleet-cdisc (https://github.com/RealSlimMahdi/fleet-cdisc)",
                "Accept": "application/json",
            },
        )
        with urllib.request.urlopen(req, timeout=timeout) as resp:  # noqa: S310 — fixed https URL
            return cls(parameters=_ctgov_to_parameters(json.load(resp)))

    def to_polars(self) -> pl.DataFrame:
        """Convert validated parameters to a Polars DataFrame with SDTM names.

        A TSVAL over 200 characters is split at a word boundary into TSVAL,
        TSVAL1, ..., TSVALn (SDTMIG 3.4 TS assumption 8).  The space goes to
        the start of the next piece, so the pieces joined give the source
        text.  A word over 200 characters is cut at 200.

        Returns:
            pl.DataFrame: DataFrame with columns named per CDISC SDTM (e.g.
                ``TSPARMCD``, ``TSPARM``, ``TSVAL``).

        Examples:
            Materialise trial summary parameters::

                ts = TrialParameters(parameters=[...])
                df = ts.to_polars()
        """
        df = _rows_to_polars(self.parameters)
        pieces = [_split_tsval(p.tsval) for p in self.parameters]
        width = max((len(p) for p in pieces), default=1)
        if width == 1:
            return df
        split = pl.DataFrame(
            {
                ("TSVAL" if i == 0 else f"TSVAL{i}"): [p[i] if i < len(p) else "" for p in pieces]
                for i in range(width)
            }
        )
        at = df.columns.index("TSVAL")
        return df.select(df.columns[:at]).hstack(split).hstack(df.select(df.columns[at + 1 :]))

from_ctgov classmethod

from_ctgov(nct_id, *, timeout=30.0)

Seed TS parameters from a ClinicalTrials.gov registration.

Fetches the study record from the ClinicalTrials.gov v2 JSON API and maps the cleanly-derivable fields to TS parameters. The result is a starting point, not a submission-ready TS: dictionary-bound parameters (INDIC/SNOMED, TRT/UNII, PCLAS/MED-RT) are deliberately not guessed and must be added by the study team.

Parameters:

Name Type Description Default
nct_id str

ClinicalTrials.gov identifier (e.g. "NCT01234567").

required
timeout float

HTTP timeout in seconds.

30.0

Returns:

Name Type Description
TrialParameters TrialParameters

Collection with one row per derivable parameter (repeating parameters such as FCNTRY get incrementing TSSEQ).

Raises:

Type Description
HTTPError

When the NCT ID is unknown to the registry.

Examples:

Seed TS from the registry, then extend and build::

ts_rows = TrialParameters.from_ctgov("NCT00048217")
ts = (
    fleet.frame(pl.DataFrame()).sdtm
    .fetch_structure("TS")
    .study_header("CDISCPILOT01", "TS")
    .add_parameters(ts_rows)
    .to_frame()
)
Source code in src/fleet/sdtm/tdd.py
@classmethod
def from_ctgov(cls, nct_id: str, *, timeout: float = 30.0) -> TrialParameters:
    """Seed TS parameters from a ClinicalTrials.gov registration.

    Fetches the study record from the ClinicalTrials.gov v2 JSON API and
    maps the cleanly-derivable fields to TS parameters.  The result is a
    **starting point**, not a submission-ready TS: dictionary-bound
    parameters (INDIC/SNOMED, TRT/UNII, PCLAS/MED-RT) are deliberately
    not guessed and must be added by the study team.

    Args:
        nct_id: ClinicalTrials.gov identifier (e.g. ``"NCT01234567"``).
        timeout: HTTP timeout in seconds.

    Returns:
        TrialParameters: Collection with one row per derivable parameter
            (repeating parameters such as FCNTRY get incrementing TSSEQ).

    Raises:
        urllib.error.HTTPError: When the NCT ID is unknown to the registry.

    Examples:
        Seed TS from the registry, then extend and build::

            ts_rows = TrialParameters.from_ctgov("NCT00048217")
            ts = (
                fleet.frame(pl.DataFrame()).sdtm
                .fetch_structure("TS")
                .study_header("CDISCPILOT01", "TS")
                .add_parameters(ts_rows)
                .to_frame()
            )
    """
    import json
    import urllib.request

    # ponytail: stdlib on purpose — ctgov's WAF 403s httpx's TLS/client
    # fingerprint in some environments while urllib passes.
    req = urllib.request.Request(
        f"https://clinicaltrials.gov/api/v2/studies/{nct_id}",
        headers={
            "User-Agent": "fleet-cdisc (https://github.com/RealSlimMahdi/fleet-cdisc)",
            "Accept": "application/json",
        },
    )
    with urllib.request.urlopen(req, timeout=timeout) as resp:  # noqa: S310 — fixed https URL
        return cls(parameters=_ctgov_to_parameters(json.load(resp)))

to_polars

to_polars()

Convert validated parameters to a Polars DataFrame with SDTM names.

A TSVAL over 200 characters is split at a word boundary into TSVAL, TSVAL1, ..., TSVALn (SDTMIG 3.4 TS assumption 8). The space goes to the start of the next piece, so the pieces joined give the source text. A word over 200 characters is cut at 200.

Returns:

Type Description
DataFrame

pl.DataFrame: DataFrame with columns named per CDISC SDTM (e.g. TSPARMCD, TSPARM, TSVAL).

Examples:

Materialise trial summary parameters::

ts = TrialParameters(parameters=[...])
df = ts.to_polars()
Source code in src/fleet/sdtm/tdd.py
def to_polars(self) -> pl.DataFrame:
    """Convert validated parameters to a Polars DataFrame with SDTM names.

    A TSVAL over 200 characters is split at a word boundary into TSVAL,
    TSVAL1, ..., TSVALn (SDTMIG 3.4 TS assumption 8).  The space goes to
    the start of the next piece, so the pieces joined give the source
    text.  A word over 200 characters is cut at 200.

    Returns:
        pl.DataFrame: DataFrame with columns named per CDISC SDTM (e.g.
            ``TSPARMCD``, ``TSPARM``, ``TSVAL``).

    Examples:
        Materialise trial summary parameters::

            ts = TrialParameters(parameters=[...])
            df = ts.to_polars()
    """
    df = _rows_to_polars(self.parameters)
    pieces = [_split_tsval(p.tsval) for p in self.parameters]
    width = max((len(p) for p in pieces), default=1)
    if width == 1:
        return df
    split = pl.DataFrame(
        {
            ("TSVAL" if i == 0 else f"TSVAL{i}"): [p[i] if i < len(p) else "" for p in pieces]
            for i in range(width)
        }
    )
    at = df.columns.index("TSVAL")
    return df.select(df.columns[:at]).hstack(split).hstack(df.select(df.columns[at + 1 :]))

TrialCriteria

Bases: BaseModel

Typed collection of TI rows.

Source code in src/fleet/sdtm/tdd.py
class TrialCriteria(BaseModel):
    """Typed collection of TI rows."""

    criteria: list[TrialCriterion]

    @model_validator(mode="after")
    def check_unique_ietestcd(self) -> TrialCriteria:
        codes = [c.ietestcd for c in self.criteria]
        if len(codes) != len(set(codes)):
            raise ValueError("Duplicate IETESTCD values")
        return self

    def to_polars(self) -> pl.DataFrame:
        """Convert validated criteria to a Polars DataFrame with SDTM names.

        Returns:
            pl.DataFrame: DataFrame with columns named per CDISC SDTM (e.g.
                ``IETESTCD``, ``IETEST``, ``IECAT``).

        Examples:
            Materialise trial criteria::

                ti = TrialCriteria(criteria=[...])
                df = ti.to_polars()
        """
        return _rows_to_polars(self.criteria)

to_polars

to_polars()

Convert validated criteria to a Polars DataFrame with SDTM names.

Returns:

Type Description
DataFrame

pl.DataFrame: DataFrame with columns named per CDISC SDTM (e.g. IETESTCD, IETEST, IECAT).

Examples:

Materialise trial criteria::

ti = TrialCriteria(criteria=[...])
df = ti.to_polars()
Source code in src/fleet/sdtm/tdd.py
def to_polars(self) -> pl.DataFrame:
    """Convert validated criteria to a Polars DataFrame with SDTM names.

    Returns:
        pl.DataFrame: DataFrame with columns named per CDISC SDTM (e.g.
            ``IETESTCD``, ``IETEST``, ``IECAT``).

    Examples:
        Materialise trial criteria::

            ti = TrialCriteria(criteria=[...])
            df = ti.to_polars()
    """
    return _rows_to_polars(self.criteria)

TrialDiseaseAssessments

Bases: BaseModel

Typed collection of TD rows.

Source code in src/fleet/sdtm/tdd.py
class TrialDiseaseAssessments(BaseModel):
    """Typed collection of TD rows."""

    assessments: list[TrialDiseaseAssessment]

    @model_validator(mode="after")
    def check_unique_tdorder(self) -> TrialDiseaseAssessments:
        orders = [a.tdorder for a in self.assessments]
        if len(orders) != len(set(orders)):
            raise ValueError("Duplicate TDORDER values")
        return self

    def to_polars(self) -> pl.DataFrame:
        """Convert validated assessments to a Polars DataFrame with SDTM names.

        Returns:
            pl.DataFrame: DataFrame with columns named per CDISC SDTM (e.g.
                ``TDORDER``, ``TDANCVAR``, ``TDTGTPAI``).

        Examples:
            Materialise trial disease assessments::

                td = TrialDiseaseAssessments(assessments=[...])
                df = td.to_polars()
        """
        return _rows_to_polars(self.assessments)

to_polars

to_polars()

Convert validated assessments to a Polars DataFrame with SDTM names.

Returns:

Type Description
DataFrame

pl.DataFrame: DataFrame with columns named per CDISC SDTM (e.g. TDORDER, TDANCVAR, TDTGTPAI).

Examples:

Materialise trial disease assessments::

td = TrialDiseaseAssessments(assessments=[...])
df = td.to_polars()
Source code in src/fleet/sdtm/tdd.py
def to_polars(self) -> pl.DataFrame:
    """Convert validated assessments to a Polars DataFrame with SDTM names.

    Returns:
        pl.DataFrame: DataFrame with columns named per CDISC SDTM (e.g.
            ``TDORDER``, ``TDANCVAR``, ``TDTGTPAI``).

    Examples:
        Materialise trial disease assessments::

            td = TrialDiseaseAssessments(assessments=[...])
            df = td.to_polars()
    """
    return _rows_to_polars(self.assessments)

TrialMilestones

Bases: BaseModel

Typed collection of TM rows.

Source code in src/fleet/sdtm/tdd.py
class TrialMilestones(BaseModel):
    """Typed collection of TM rows."""

    milestones: list[TrialMilestone]

    @model_validator(mode="after")
    def check_unique_midstype(self) -> TrialMilestones:
        types = [m.midstype for m in self.milestones]
        if len(types) != len(set(types)):
            raise ValueError("Duplicate MIDSTYPE values")
        return self

    def to_polars(self) -> pl.DataFrame:
        """Convert validated milestones to a Polars DataFrame with SDTM names.

        Returns:
            pl.DataFrame: DataFrame with columns named per CDISC SDTM (e.g.
                ``MIDSTYPE``, ``TMDEF``, ``TMRPT``).

        Examples:
            Materialise trial disease milestones::

                tm = TrialMilestones(milestones=[...])
                df = tm.to_polars()
        """
        return _rows_to_polars(self.milestones)

to_polars

to_polars()

Convert validated milestones to a Polars DataFrame with SDTM names.

Returns:

Type Description
DataFrame

pl.DataFrame: DataFrame with columns named per CDISC SDTM (e.g. MIDSTYPE, TMDEF, TMRPT).

Examples:

Materialise trial disease milestones::

tm = TrialMilestones(milestones=[...])
df = tm.to_polars()
Source code in src/fleet/sdtm/tdd.py
def to_polars(self) -> pl.DataFrame:
    """Convert validated milestones to a Polars DataFrame with SDTM names.

    Returns:
        pl.DataFrame: DataFrame with columns named per CDISC SDTM (e.g.
            ``MIDSTYPE``, ``TMDEF``, ``TMRPT``).

    Examples:
        Materialise trial disease milestones::

            tm = TrialMilestones(milestones=[...])
            df = tm.to_polars()
    """
    return _rows_to_polars(self.milestones)

parse_trial_design

parse_trial_design(mermaid_text)

Parse a Mermaid flowchart into TE and TA collections.

Each subgraph ID[TITLE] is an epoch; each node inside it is an element (ETCD["Element name<br/>P14D"]); each path from the start node to an end node is an arm, named by the last |ARMCD| label on its edges. A title that is not a C99079 term is kept, upper case, as a sponsor epoch, with a warning. %% comment lines are skipped.

The diagram carries ETCD, ELEMENT, TEDUR, EPOCH and the arm paths. It does not carry ARM, TESTRL, TEENRL, TABRANCH or TATRANS, and it cannot carry a crossover or an element that repeats in one arm: YAML is the lossless round trip.

Parameters:

Name Type Description Default
mermaid_text str

A Mermaid flowchart TD string.

required

Returns:

Type Description
tuple[TrialElements, TrialArms]

tuple[TrialElements, TrialArms]: Validated collections ready for add_elements() and add_arms().

Raises:

Type Description
ValueError

On an empty diagram, a line of an unknown form, a node outside a subgraph, an unlabelled fork, a cycle, a node with no edge, more than one start node, or two nodes or two arms that give the same code.

Examples:

Parse a simple 3-element design::

te, ta = parse_trial_design('''
    flowchart TD
    subgraph SCR[SCREENING]
        SCRN["Screening<br/>P14D"]
    end
    subgraph TRT[TREATMENT]
        TREAT["Treatment<br/>P84D"]
    end
    subgraph FU[FOLLOW-UP]
        FOLL["Follow-up<br/>P28D"]
    end
    SCRN --> TREAT
    TREAT --> FOLL
''')
Source code in src/fleet/sdtm/tdd.py
def parse_trial_design(
    mermaid_text: str,
) -> tuple[TrialElements, TrialArms]:
    """Parse a Mermaid flowchart into TE and TA collections.

    Each ``subgraph ID[TITLE]`` is an epoch; each node inside it is an
    element (``ETCD["Element name<br/>P14D"]``); each path from the start
    node to an end node is an arm, named by the last ``|ARMCD|`` label on
    its edges.  A title that is not a C99079 term is kept, upper case, as a
    sponsor epoch, with a warning.  ``%%`` comment lines are skipped.

    The diagram carries ETCD, ELEMENT, TEDUR, EPOCH and the arm paths.  It
    does not carry ARM, TESTRL, TEENRL, TABRANCH or TATRANS, and it cannot
    carry a crossover or an element that repeats in one arm: YAML is the
    lossless round trip.

    Args:
        mermaid_text: A Mermaid ``flowchart TD`` string.

    Returns:
        tuple[TrialElements, TrialArms]: Validated collections ready for
            ``add_elements()`` and ``add_arms()``.

    Raises:
        ValueError: On an empty diagram, a line of an unknown form, a node
            outside a subgraph, an unlabelled fork, a cycle, a node with no
            edge, more than one start node, or two nodes or two arms that
            give the same code.

    Examples:
        Parse a simple 3-element design::

            te, ta = parse_trial_design('''
                flowchart TD
                subgraph SCR[SCREENING]
                    SCRN["Screening<br/>P14D"]
                end
                subgraph TRT[TREATMENT]
                    TREAT["Treatment<br/>P84D"]
                end
                subgraph FU[FOLLOW-UP]
                    FOLL["Follow-up<br/>P28D"]
                end
                SCRN --> TREAT
                TREAT --> FOLL
            ''')
    """
    node_epoch: dict[str, EpochLike] = {}
    node_label: dict[str, str] = {}
    node_dur: dict[str, str] = {}
    edges: list[tuple[str, str | None, str]] = []
    current: EpochLike | None = None

    for raw in mermaid_text.splitlines():
        line = raw.strip()
        if not line or line.startswith("%%") or _HEADER_RE.fullmatch(line):
            continue
        if m := _SUBGRAPH_RE.fullmatch(line):
            current = _subgraph_epoch(m.group(2))
        elif _SUBGRAPH_END_RE.fullmatch(line):
            current = None
        elif m := _NODE_RE.fullmatch(line):
            nid = m.group(1)
            if current is None:
                raise ValueError(f"parse_trial_design: node {nid} is outside every subgraph")
            node_epoch[nid] = current
            node_label[nid] = m.group(2).replace("#quot;", '"')
            if m.group(3):
                node_dur[nid] = m.group(3)
        elif m := _EDGE_RE.fullmatch(line):
            label = m.group(2).strip() if m.group(2) else None
            edges.append((m.group(1), label, m.group(3)))
        else:
            raise ValueError(f"parse_trial_design: cannot read the line {line!r}")

    if not node_label:
        raise ValueError("parse_trial_design: the diagram holds no element node")
    unknown = sorted({n for src, _, dst in edges for n in (src, dst)} - set(node_label))
    if unknown:
        raise ValueError(f"parse_trial_design: edge node(s) {unknown} are not declared")
    etcd = {nid: nid.upper()[:8] for nid in node_label}
    if len(set(etcd.values())) != len(etcd):
        raise ValueError(f"parse_trial_design: node ids give the same ETCD: {sorted(etcd)}")

    arm_paths = _arm_paths(list(node_label), edges)
    te_list = [
        TrialElement(
            etcd=etcd[nid],
            element=node_label[nid],
            tedur=node_dur.get(nid, ""),
            epoch=node_epoch[nid],
        )
        for nid in dict.fromkeys(n for path in arm_paths.values() for n in path)
    ]
    ta_list = [
        TrialArm(
            armcd=armcd,
            arm=armcd.replace("_", " ").title(),
            taetord=order,
            etcd=etcd[nid],
            element=node_label[nid],
            epoch=node_epoch[nid],
        )
        for armcd, path in arm_paths.items()
        for order, nid in enumerate(path, 1)
    ]
    return TrialElements(elements=te_list), TrialArms(arms=ta_list)

options: show_source: false heading_level: 2 members_order: source show_root_heading: true

fleet.sdtm._tdd_mixin

Trial Design Domain mixin — adds TDD verbs to SDTMNamespace.

Provides two families of verbs:

Protocol-reference verbs fetch_structure(), study_header(), add_elements(), add_arms(), add_visits(), add_parameters(), add_criteria(), add_disease_assessments(), add_milestones() — follow a fixed stage sequence.

Subject-level verbs visit_map(), element_boundaries(), epoch_assign(), study_day() — freely mixable with any existing SDTM verb.

TrialDesignMixin

Mixin that adds Trial Design Domain verbs to the SDTM namespace.

Stage tracking (_tdd_stage) ensures protocol-reference verbs are called in the correct order. Subject-level verbs ignore the stage.

Source code in src/fleet/sdtm/_tdd_mixin.py
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
class TrialDesignMixin:
    """Mixin that adds Trial Design Domain verbs to the SDTM namespace.

    Stage tracking (``_tdd_stage``) ensures protocol-reference verbs are
    called in the correct order.  Subject-level verbs ignore the stage.
    """

    # These attributes are set lazily; their absence means "not in TDD mode"
    _tdd_stage: int
    _domain_meta: dict[str, Any]
    _reconciliation_report: list[str]

    # ------------------------------------------------------------------ #
    # Stage enforcement                                                    #
    # ------------------------------------------------------------------ #

    def _check_stage(self, verb: str, required: int) -> None:
        """Raise ``ValueError`` if the TDD stage does not match *required*."""
        stage = getattr(self, "_tdd_stage", None)
        if stage is None and required > 0:
            raise ValueError(
                f"Cannot call {verb}() without first calling fetch_structure(). "
                f"Expected sequence: {' → '.join(_STAGE_SEQUENCE)}"
            )
        if stage is not None and stage < required:
            current_label = (
                _STAGE_SEQUENCE[stage] if stage < len(_STAGE_SEQUENCE) else f"stage {stage}"
            )
            raise ValueError(
                f"Cannot call {verb}() at {current_label}. "
                f"Expected sequence: {' → '.join(_STAGE_SEQUENCE)}"
            )

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

    def fetch_structure(
        self,
        domain: str,
        *,
        ig_version: str = "3-4",
        save_to: str | Path | None = None,
        define_path: str | Path | None = None,
    ) -> Self:  # type: ignore[type-var]
        """Query the CDISC Library for *domain*'s IG structure.

        When *define_path* is given the domain variables (including ``core``)
        are read from the define.yaml first; if the domain is not found the
        method falls back to the online CDISC Library.

        When *save_to* is given the fetched metadata is cached as YAML; on
        subsequent calls the cache is read instead of hitting the API.

        SDTMIG 3.4 structures for the nine TDD domains (TE, TA, TV, TS, TI,
        TD, TM, SV, SE) ship with Fleet, so the default flow needs no
        network access and no API key; the CDISC Library is only queried
        for other domains or IG versions.

        Sets ``_domain_meta`` on the namespace for downstream validation
        and performs schema reconciliation against the static Pydantic model.

        Args:
            domain: SDTM domain code (e.g. ``"TE"``, ``"TA"``).
            ig_version: SDTM IG version slug (default ``"3-4"``).
            save_to: Optional path to cache the fetched YAML.
            define_path: Optional path to a ``define.yaml``. When provided,
                domain metadata is extracted from the spec (offline) before
                falling back to the CDISC Library API.

        Returns:
            Self: The namespace at stage 1; call ``study_header()`` next.

        Examples:
            Fetch the TE structure from the CDISC Library::

                te = (
                    pl.DataFrame().sdtm
                    .fetch_structure("TE", ig_version="3-4",
                                     save_to="metadata/te_structure.yaml")
                    .study_header("CDISCPILOT01", "TE")
                    .add_elements(te_rows)
                    .to_frame()
                )
        """
        self._check_stage("fetch_structure", required=0)
        domain = domain.upper()

        # Priority: define_path → save_to cache → packaged IG 3.4 → online
        meta: dict[str, Any] | None = None

        if define_path is not None:
            meta = _extract_domain_from_define(domain, Path(define_path))

        cache_path = Path(save_to) if save_to else None
        if meta is None and cache_path and cache_path.exists():
            meta = yaml.safe_load(cache_path.read_text(encoding="utf-8"))

        if meta is None:
            meta = _load_packaged_structure(domain, ig_version)
            if meta is None:
                try:
                    meta = self._fetch_ig_domain(domain, ig_version)
                except Exception as exc:
                    raise type(exc)(
                        f"Domain '{domain}' not found in SDTM IG {ig_version}. "
                        f"If this is a company-specific domain, provide its structure "
                        f"via define_path= or a cached YAML via save_to=."
                    ) from exc
            if cache_path:
                cache_path.parent.mkdir(parents=True, exist_ok=True)
                cache_path.write_text(
                    yaml.dump(meta, default_flow_style=False, sort_keys=False), encoding="utf-8"
                )

        # Propagate to the new namespace instance
        new = self._chain()  # type: ignore[attr-defined]
        new._domain_meta = meta
        new._tdd_stage = 1
        new._reconciliation_report = _reconcile_schema(domain, meta)
        for msg in new._reconciliation_report:
            warnings.warn(msg, UserWarning, stacklevel=2)
        return new  # type: ignore[return-value]

    def study_header(
        self,
        study_id: str,
        domain: str,
    ) -> Self:  # type: ignore[type-var]
        """Hardcode ``STUDYID`` and ``DOMAIN`` columns.

        Args:
            study_id: The study identifier value.
            domain: The SDTM domain code.

        Returns:
            Self: The namespace at stage 2; call an ``add_*()`` verb next.

        Examples:
            Set the study header for a TE domain::

                te = (
                    pl.DataFrame().sdtm
                    .fetch_structure("TE")
                    .study_header("CDISCPILOT01", "TE")
                    .add_elements(te_rows)
                    .to_frame()
                )
        """
        self._check_stage("study_header", required=1)
        new = self._chain(  # type: ignore[attr-defined]
            pl.lit(study_id).alias("STUDYID"),
            pl.lit(domain.upper()).alias("DOMAIN"),
        )
        new._tdd_stage = 2
        return new  # type: ignore[return-value]

    # ------------------------------------------------------------------ #
    # Protocol-reference add verbs                                         #
    # ------------------------------------------------------------------ #

    def add_elements(self, elements: TrialElements) -> Self:  # type: ignore[type-var]
        """Materialise a validated ``TrialElements`` collection into the pipeline.

        Args:
            elements: A ``TrialElements`` collection (pre-validated by Pydantic).

        Returns:
            Self: The namespace at stage 3 with TE rows loaded.

        Examples:
            Add trial elements to a TE pipeline::

                te = (
                    pl.DataFrame().sdtm
                    .fetch_structure("TE")
                    .study_header("CDISCPILOT01", "TE")
                    .add_elements(te_rows)
                    .to_frame()
                )
        """
        self._check_stage("add_elements", required=2)
        return self._materialise_collection(elements.to_polars())

    def add_arms(
        self,
        arms: TrialArms,
        *,
        te: TrialElements | None = None,
    ) -> Self:  # type: ignore[type-var]
        """Materialise a validated ``TrialArms`` collection into the pipeline.

        Args:
            arms: A ``TrialArms`` collection.
            te: Optional ``TrialElements`` for FK validation (ETCD ∈ TE.ETCD).

        Returns:
            Self: The namespace at stage 3 with TA rows loaded.

        Examples:
            Add trial arms with FK validation::

                ta = (
                    pl.DataFrame().sdtm
                    .fetch_structure("TA")
                    .study_header("CDISCPILOT01", "TA")
                    .add_arms(ta_rows, te=te_rows)
                    .to_frame()
                )
        """
        self._check_stage("add_arms", required=2)
        if te is not None:
            valid_etcds = {e.etcd for e in te.elements}
            for a in arms.arms:
                if a.etcd not in valid_etcds:
                    raise ValueError(
                        f"TA.ETCD '{a.etcd}' not found in TE. Valid: {sorted(valid_etcds)}"
                    )
        return self._materialise_collection(arms.to_polars())

    def add_visits(
        self,
        visits: TrialVisits,
        *,
        ta: TrialArms | None = None,
    ) -> Self:  # type: ignore[type-var]
        """Materialise a validated ``TrialVisits`` collection into the pipeline.

        Args:
            visits: A ``TrialVisits`` collection.
            ta: Optional ``TrialArms`` for FK validation (non-blank
                ARMCD ∈ TA.ARMCD).

        Returns:
            Self: The namespace at stage 3 with TV rows loaded.

        Examples:
            Add trial visits with FK validation::

                tv = (
                    pl.DataFrame().sdtm
                    .fetch_structure("TV")
                    .study_header("CDISCPILOT01", "TV")
                    .add_visits(tv_rows, ta=ta_rows)
                    .to_frame()
                )
        """
        self._check_stage("add_visits", required=2)
        if ta is not None:
            valid_armcds = {a.armcd for a in ta.arms}
            for v in visits.visits:
                if v.armcd and v.armcd not in valid_armcds:
                    raise ValueError(
                        f"TV.ARMCD '{v.armcd}' not found in TA. Valid: {sorted(valid_armcds)}"
                    )
        return self._materialise_collection(visits.to_polars())

    def add_parameters(self, params: TrialParameters) -> Self:  # type: ignore[type-var]
        """Materialise a validated ``TrialParameters`` collection into the pipeline.

        Args:
            params: A ``TrialParameters`` collection.

        Returns:
            Self: The namespace at stage 3 with TS rows loaded.

        Examples:
            Add trial summary parameters::

                ts = (
                    pl.DataFrame().sdtm
                    .fetch_structure("TS")
                    .study_header("CDISCPILOT01", "TS")
                    .add_parameters(ts_rows)
                    .to_frame()
                )
        """
        self._check_stage("add_parameters", required=2)
        return self._materialise_collection(params.to_polars())

    def add_criteria(self, criteria: TrialCriteria) -> Self:  # type: ignore[type-var]
        """Materialise a validated ``TrialCriteria`` collection into the pipeline.

        Args:
            criteria: A ``TrialCriteria`` collection.

        Returns:
            Self: The namespace at stage 3 with TI rows loaded.

        Examples:
            Add inclusion/exclusion criteria::

                ti = (
                    pl.DataFrame().sdtm
                    .fetch_structure("TI")
                    .study_header("CDISCPILOT01", "TI")
                    .add_criteria(ti_rows)
                    .to_frame()
                )
        """
        self._check_stage("add_criteria", required=2)
        return self._materialise_collection(criteria.to_polars())

    def add_disease_assessments(self, assessments: TrialDiseaseAssessments) -> Self:  # type: ignore[type-var]
        """Materialise a validated ``TrialDiseaseAssessments`` collection.

        Args:
            assessments: A ``TrialDiseaseAssessments`` collection.

        Returns:
            Self: The namespace at stage 3 with TD rows loaded.

        Examples:
            Add trial disease assessments::

                td = (
                    pl.DataFrame().sdtm
                    .fetch_structure("TD")
                    .study_header("CDISCPILOT01", "TD")
                    .add_disease_assessments(td_rows)
                    .to_frame()
                )
        """
        self._check_stage("add_disease_assessments", required=2)
        return self._materialise_collection(assessments.to_polars())

    def add_milestones(self, milestones: TrialMilestones) -> Self:  # type: ignore[type-var]
        """Materialise a validated ``TrialMilestones`` collection.

        Args:
            milestones: A ``TrialMilestones`` collection.

        Returns:
            Self: The namespace at stage 3 with TM rows loaded.

        Examples:
            Add trial disease milestones::

                tm = (
                    pl.DataFrame().sdtm
                    .fetch_structure("TM")
                    .study_header("CDISCPILOT01", "TM")
                    .add_milestones(tm_rows)
                    .to_frame()
                )
        """
        self._check_stage("add_milestones", required=2)
        return self._materialise_collection(milestones.to_polars())

    # ------------------------------------------------------------------ #
    # Subject-level derivation verbs                                       #
    # ------------------------------------------------------------------ #

    def visit_map(
        self,
        target_num: str,
        target_name: str,
        *,
        date_col: str,
        planned_visits: TrialVisits | pl.DataFrame,
        ref_date: str | None = None,
        tolerance: dict[str, int] | None = None,
    ) -> Self:  # type: ignore[type-var]
        """Map raw visit dates to planned visits from TV, by nearest study day.

        Use it only when the CRF does not collect the visit: it never
        replaces a collected VISITNUM.  For each row, the verb takes the
        planned visit whose ``VISITDY`` is nearest to the actual study day
        (from *date_col* and *ref_date*), within the optional *tolerance*
        window.  The distance is the difference of the study-day numbers,
        as ``abs(SVSTDY - VISITDY)`` in a SAS program: across the missing
        Day 0, Day -1 is 2 days from ``VISITDY`` 1.  Ties resolve to the
        earlier ``VISITNUM``.  When TV has ``ARMCD`` values, a row only
        takes a visit of its own arm or a visit with a blank ``ARMCD``.

        A dated row outside every window is an unscheduled visit.  It gets
        the ``VISITNUM`` of the last planned visit on or before its study
        day plus .1, .2, ... in date order within the subject, and the
        ``VISIT`` ``UNSCHEDULED <VISITNUM>``.  A row with no study day gets
        a null.  One warning gives both counts.  With ``DOMAIN`` SV, one
        warning gives the ``USUBJID`` + ``VISITNUM`` keys that repeat.

        Args:
            target_num: Name of the output ``VISITNUM`` column.  An
                existing column of that name is replaced.
            target_name: Name of the output ``VISIT`` column.  An existing
                column of that name is replaced.
            date_col: Column containing the actual visit date (ISO 8601 string).
            planned_visits: A ``TrialVisits`` collection or a DataFrame with
                ``VISITNUM``, ``VISIT``, and ``VISITDY`` columns (and
                optionally ``ARMCD``).
            ref_date: Column with the reference date for the study day.
                When it is not a column of the frame, it is read from the
                pinned DM, as ``study_day()`` does.  When ``None``, the
                frame must hold the study day in a ``VISITDY`` column.
            tolerance: Optional ``{"before": n, "after": n}`` window in
                study days, boundaries inclusive: the actual study day may
                precede the planned ``VISITDY`` by up to *before* and
                follow it by up to *after*.

        Returns:
            Self: The namespace with *target_num* and *target_name* appended.

        Raises:
            DerivationError: When *date_col* or *ref_date* cannot be found,
                when TV has arm-specific visits and the frame has no
                ``ARMCD``, or when an unscheduled number would repeat a
                planned ``VISITNUM`` or reach the next whole number.

        References:
            SDTMIG 3.4 SV and TV: ``USUBJID`` + ``VISITNUM`` is the SV key,
            ``VISITNUM`` is Req, a null TV ``ARMCD`` means all arms.  The
            decimal number of an unscheduled visit is a sponsor convention
            (the CDISC pilot uses ``UNSCHEDULED 5.1``); see
            ``docs/adr/0035-visit-map-numbers-an-unscheduled-visit.md``.

        Examples:
            Map subject visits to planned visits::

                sv = (
                    raw_visits.sdtm
                    .assign("DOMAIN", value="SV")
                    .assign("USUBJID", source="subject_id")
                    .date("SVSTDTC", source="visit_date")
                    .pin("DM", dm)
                    .visit_map("VISITNUM", "VISIT",
                               date_col="SVSTDTC",
                               planned_visits=tv_rows,
                               ref_date="RFSTDTC",
                               tolerance={"before": 3, "after": 3})
                    .to_frame()
                )
        """
        tv_df = (
            planned_visits.to_polars()
            if isinstance(planned_visits, TrialVisits)
            else planned_visits
        )
        verb = f"visit_map({target_num})"
        df = self._lazy.collect().with_row_index("__row_idx__")  # type: ignore[attr-defined]
        df = df.drop([c for c in (target_num, target_name) if c in df.columns])
        actual = self._visit_map_study_day(df, verb, date_col, ref_date)
        df = df.with_columns(actual.alias("__actual_dy__"))

        tv_arm = (
            pl.col("ARMCD").cast(pl.String).replace("", None)
            if "ARMCD" in tv_df.columns
            else pl.lit(None, dtype=pl.String)
        )
        tv_slim = tv_df.select(
            pl.col("VISITNUM").alias("__tv_num__"),
            pl.col("VISIT").alias("__tv_name__"),
            pl.col("VISITDY").alias("__tv_dy__"),
            tv_arm.alias("__tv_arm__"),
        )
        arm_specific = tv_slim["__tv_arm__"].is_not_null().any()
        if arm_specific and "ARMCD" not in df.columns:
            raise DerivationError(
                f"{verb}: the planned visits hold arm-specific ARMCD values, and the frame "
                "has no ARMCD column. Add ARMCD so each subject takes only the visits of its arm."
            )

        crossed = df.select("__row_idx__", "__actual_dy__", *(["ARMCD"] if arm_specific else []))
        crossed = crossed.join(tv_slim, how="cross").filter(pl.col("__actual_dy__").is_not_null())
        if arm_specific:
            crossed = crossed.filter(
                pl.col("__tv_arm__").is_null() | (pl.col("__tv_arm__") == pl.col("ARMCD"))
            )
        offset = pl.col("__actual_dy__") - pl.col("__tv_dy__")
        candidates = crossed.filter(offset.is_not_null()).with_columns(
            offset.abs().alias("__diff__")
        )
        if tolerance:
            before = tolerance.get("before", 999999)
            after = tolerance.get("after", 999999)
            candidates = candidates.filter((offset >= -before) & (offset <= after))

        best = (
            candidates.sort("__row_idx__", "__diff__", "__tv_num__")
            .group_by("__row_idx__", maintain_order=True)
            .first()
            .select("__row_idx__", "__tv_num__", "__tv_name__")
        )
        unscheduled = _unscheduled_visits(df, crossed, best, verb, tv_slim)
        best = pl.concat([best, unscheduled], how="vertical_relaxed").rename(
            {"__tv_num__": target_num, "__tv_name__": target_name}
        )

        df = (
            df.join(best, on="__row_idx__", how="left")
            .sort("__row_idx__")
            .drop("__row_idx__", "__actual_dy__")
        )
        _warn_visit_map(df, verb, target_num, unscheduled.height)
        return self._materialise_then(df)  # type: ignore[attr-defined]

    def _visit_map_study_day(
        self, df: pl.DataFrame, verb: str, date_col: str, ref_date: str | None
    ) -> pl.Series:
        """The study day of each row, with no Day 0, from *ref_date* or VISITDY."""
        if ref_date is None:
            if "VISITDY" not in df.columns:
                raise DerivationError(
                    f"{verb}: with ref_date=None the study day is read from a VISITDY column, "
                    "and the frame has none. Pass ref_date= (for example RFSTDTC)."
                )
            return df["VISITDY"]
        if date_col not in df.columns:
            raise DerivationError(f"{verb}: date_col '{date_col}' is not a column of the frame.")
        ref = df
        if ref_date not in df.columns:
            pin = getattr(self, "_STUDY_DAY_REF_PIN", "DM").upper()
            pinned = getattr(self, "_pinned", {})
            if pin not in pinned or ref_date not in pinned[pin][0].columns:
                raise DerivationError(
                    f"{verb}: ref_date '{ref_date}' is not a column of the frame, and no "
                    f'pinned {pin} holds it. Check the name, or add .pin("{pin}", dm).'
                )
            key = self._pin_join_key(pin)  # type: ignore[attr-defined]
            source = self._require_pin(pin, "visit_map", columns=[ref_date])  # type: ignore[attr-defined]
            ref = df.join(
                source.select(*key, ref_date).unique(subset=key, keep="first"),
                on=key,
                how="left",
                nulls_equal=True,
            ).sort("__row_idx__")
        diff = (
            to_day(pl.col(date_col), ref.schema[date_col])
            - to_day(pl.col(ref_date), ref.schema[ref_date])
        ).dt.total_days()
        return ref.select(pl.when(diff >= 0).then(diff + 1).otherwise(diff)).to_series()

    def element_boundaries(
        self,
        target_start: str,
        target_end: str,
        *,
        milestones: dict[str, str],
        element_col: str = "ETCD",
        subject_col: str = "USUBJID",
    ) -> Self:  # type: ignore[type-var]
        """Derive element start/end dates from milestone columns.

        For each *element_col* value, maps the corresponding column from
        *milestones* to produce *target_start*.  The end date is the start
        of the next element by start date within the subject: the verb
        sorts on the ISO 8601 start text (a null start last, then the row
        order), so the input row order does not matter.  The output keeps
        the input row order.  The last element gets a null end.

        Args:
            target_start: Name of the output start-date column (e.g. ``"SESTDTC"``).
            target_end: Name of the output end-date column (e.g. ``"SEENDTC"``).
            milestones: ``{element_code: source_date_column}`` mapping.
            element_col: Column identifying the element (default ``"ETCD"``).
            subject_col: Column identifying the subject (default ``"USUBJID"``).

        Returns:
            Self: The namespace with *target_start* and *target_end* appended.

        Examples:
            Derive SE element boundaries::

                se = (
                    disposition_df.sdtm
                    .element_boundaries("SESTDTC", "SEENDTC",
                                        milestones={"SCRN": "screening_date",
                                                     "TRT": "first_dose_date"})
                    .to_frame()
                )
        """
        # Build a when/then chain mapping element codes to date columns
        cases: list[tuple[str, str]] = list(milestones.items())
        if not cases:
            return self._chain(  # type: ignore[attr-defined]
                pl.lit(None).alias(target_start),
                pl.lit(None).alias(target_end),
            )

        first_code, first_col = cases[0]
        expr = pl.when(pl.col(element_col) == first_code).then(pl.col(first_col))
        for code, col in cases[1:]:
            expr = expr.when(pl.col(element_col) == code).then(pl.col(col))
        start_expr = expr.otherwise(pl.lit(None)).alias(target_start)

        # End = next element's start within the subject, in start-date order
        df = self._lazy.collect().with_row_index("__row_idx__")  # type: ignore[attr-defined]
        df = df.with_columns(start_expr)
        df = (
            df.sort(subject_col, target_start, "__row_idx__", nulls_last=True)
            .with_columns(pl.col(target_start).shift(-1).over(subject_col).alias(target_end))
            .sort("__row_idx__")
            .drop("__row_idx__")
        )

        return self._materialise_then(df)  # type: ignore[attr-defined]

    def epoch_assign(
        self,
        target: str,
        *,
        date_col: str,
        epoch_ranges: list[dict[str, str]] | pl.DataFrame | None = None,
        se: pl.DataFrame | pl.LazyFrame | None = None,
        subject_col: str = "USUBJID",
        same_day: Literal["by_class", "earlier", "later"] = "by_class",
    ) -> Self:  # type: ignore[type-var]
        """Assign ``EPOCH`` based on date ranges or per-subject SE intervals.

        With *epoch_ranges*, each entry maps a study-level date interval to
        an ``Epoch`` value; the first matching range wins.  With *se*, the
        subject's own element intervals drive the assignment: for each row,
        the epoch of the SE record whose ``[SESTDTC, SEENDTC]`` interval
        contains the date (SDTMIG 3.4: EPOCH of the start or collection
        date/time).  A blank or null ``SEENDTC`` is open-ended; an element
        whose dates are partial is skipped, with a warning.

        On a transition date, where one element ends and the next starts,
        the time decides when the record and the boundary both have one.
        When one of them has no time, *same_day* decides, and one warning
        gives the count and the rule:

        - ``"by_class"`` (default): a Findings date (``--DTC``) takes the
          earlier element, an Events or Interventions date (``--STDTC``)
          the later one.  Any other *date_col* name raises.
        - ``"earlier"``: the element that ends on that date.
        - ``"later"``: the element that starts on that date.

        No guidance fixes this case, so state the rule in the SDRG.

        Args:
            target: Name of the output ``EPOCH`` column.
            date_col: Column containing the date to classify.
            epoch_ranges: A list of ``{"start": date, "end": date,
                "epoch": str}`` dicts, or a DataFrame with those columns.
            se: An SE domain frame with ``USUBJID``, ``SESTDTC``,
                ``SEENDTC``, and ``EPOCH`` columns.  Mutually exclusive
                with *epoch_ranges*.
            subject_col: Subject key used to join *se* (default
                ``"USUBJID"``).
            same_day: The rule for a record with no time on a transition
                date (with *se* only).

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

        Raises:
            ValueError: When neither or both of *epoch_ranges* and *se*
                are provided.
            DerivationError: When ``same_day="by_class"`` and *date_col*
                is neither a ``--DTC`` nor a ``--STDTC`` name.

        Examples:
            Stamp EPOCH onto any domain from the subject's SE intervals::

                ae = (
                    ae_raw.sdtm
                    .assign("USUBJID", source="subject_id")
                    .date("AESTDTC", source="ae_start_date")
                    .epoch_assign("EPOCH", date_col="AESTDTC", se=se)
                    .to_frame()
                )
        """
        if (epoch_ranges is None) == (se is None):
            raise ValueError("epoch_assign() takes exactly one of epoch_ranges= or se=")

        if se is not None:
            rule = _same_day_rule(date_col, same_day)
            df = self._lazy.collect().with_row_index("__row_idx__")  # type: ignore[attr-defined]
            best = _epoch_from_se(df, se, target, date_col, subject_col, rule, same_day)
            out = (
                df.drop(target, strict=False)
                .join(best, on="__row_idx__", how="left")
                .drop("__row_idx__")
            )
            return self._materialise_then(out)  # type: ignore[attr-defined]

        if isinstance(epoch_ranges, pl.DataFrame):
            ranges = epoch_ranges.to_dicts()
        else:
            ranges = epoch_ranges

        if not ranges:
            return self._chain(pl.lit(None).alias(target))  # type: ignore[attr-defined]

        day = date_part(pl.col(date_col))
        expr = pl.when(pl.lit(False)).then(pl.lit(None, dtype=pl.String))
        for r in ranges:
            start = date_part(pl.lit(str(r["start"])))
            end = date_part(pl.lit(str(r["end"])))
            expr = expr.when((day >= start) & (day <= end)).then(pl.lit(r["epoch"]))

        final_expr = expr.otherwise(pl.lit(None)).alias(target)
        return self._chain(final_expr)  # type: ignore[attr-defined]

    # ------------------------------------------------------------------ #
    # Internal helpers                                                     #
    # ------------------------------------------------------------------ #

    def _materialise_collection(self, df: pl.DataFrame) -> Self:  # type: ignore[type-var]
        """Replace the lazy plan with *df*, preserving STUDYID/DOMAIN."""
        # Collect current header columns (STUDYID, DOMAIN)
        current = self._lazy.collect()  # type: ignore[attr-defined]
        header_cols = {}
        for col in ("STUDYID", "DOMAIN"):
            if col in current.columns and current.height > 0:
                header_cols[col] = current[col][0]

        # Broadcast header onto the collection rows
        if header_cols:
            df = df.with_columns([pl.lit(v).alias(k) for k, v in header_cols.items()])

        new = self._materialise_then(df)  # type: ignore[attr-defined]
        new._tdd_stage = 3
        return new  # type: ignore[return-value]

    @staticmethod
    def _fetch_ig_domain(domain: str, ig_version: str) -> dict[str, Any]:
        """Fetch domain metadata from the CDISC Library IG."""
        from fleet.ct.api import CDISCClient

        with CDISCClient() as client:
            detail = client._get(f"/mdr/sdtmig/{ig_version}/datasets/{domain}")

        # Parse into a lightweight dict
        variables: list[dict[str, str]] = []
        for var in sorted(
            detail.get("datasetVariables", []),
            key=lambda v: int(v.get("ordinal", 999)),
        ):
            var_info: dict[str, str] = {
                "name": var.get("name", ""),
                "label": var.get("label", ""),
                "type": var.get("simpleDatatype", "Char"),
                "core": var.get("core", "Perm"),
                "role": var.get("role", ""),
            }
            # Extract codelist reference
            for cl in var.get("_links", {}).get("codelist", []):
                import re

                m = re.search(r"codelists/(C\d+)", cl.get("href", ""))
                if m:
                    var_info["codelist"] = m.group(1)
                    break
            variables.append(var_info)

        return {
            "domain": domain,
            "label": detail.get("label", ""),
            "ig_version": ig_version,
            "variables": variables,
        }

fetch_structure

fetch_structure(
    domain,
    *,
    ig_version="3-4",
    save_to=None,
    define_path=None
)

Query the CDISC Library for domain's IG structure.

When define_path is given the domain variables (including core) are read from the define.yaml first; if the domain is not found the method falls back to the online CDISC Library.

When save_to is given the fetched metadata is cached as YAML; on subsequent calls the cache is read instead of hitting the API.

SDTMIG 3.4 structures for the nine TDD domains (TE, TA, TV, TS, TI, TD, TM, SV, SE) ship with Fleet, so the default flow needs no network access and no API key; the CDISC Library is only queried for other domains or IG versions.

Sets _domain_meta on the namespace for downstream validation and performs schema reconciliation against the static Pydantic model.

Parameters:

Name Type Description Default
domain str

SDTM domain code (e.g. "TE", "TA").

required
ig_version str

SDTM IG version slug (default "3-4").

'3-4'
save_to str | Path | None

Optional path to cache the fetched YAML.

None
define_path str | Path | None

Optional path to a define.yaml. When provided, domain metadata is extracted from the spec (offline) before falling back to the CDISC Library API.

None

Returns:

Name Type Description
Self Self

The namespace at stage 1; call study_header() next.

Examples:

Fetch the TE structure from the CDISC Library::

te = (
    pl.DataFrame().sdtm
    .fetch_structure("TE", ig_version="3-4",
                     save_to="metadata/te_structure.yaml")
    .study_header("CDISCPILOT01", "TE")
    .add_elements(te_rows)
    .to_frame()
)
Source code in src/fleet/sdtm/_tdd_mixin.py
def fetch_structure(
    self,
    domain: str,
    *,
    ig_version: str = "3-4",
    save_to: str | Path | None = None,
    define_path: str | Path | None = None,
) -> Self:  # type: ignore[type-var]
    """Query the CDISC Library for *domain*'s IG structure.

    When *define_path* is given the domain variables (including ``core``)
    are read from the define.yaml first; if the domain is not found the
    method falls back to the online CDISC Library.

    When *save_to* is given the fetched metadata is cached as YAML; on
    subsequent calls the cache is read instead of hitting the API.

    SDTMIG 3.4 structures for the nine TDD domains (TE, TA, TV, TS, TI,
    TD, TM, SV, SE) ship with Fleet, so the default flow needs no
    network access and no API key; the CDISC Library is only queried
    for other domains or IG versions.

    Sets ``_domain_meta`` on the namespace for downstream validation
    and performs schema reconciliation against the static Pydantic model.

    Args:
        domain: SDTM domain code (e.g. ``"TE"``, ``"TA"``).
        ig_version: SDTM IG version slug (default ``"3-4"``).
        save_to: Optional path to cache the fetched YAML.
        define_path: Optional path to a ``define.yaml``. When provided,
            domain metadata is extracted from the spec (offline) before
            falling back to the CDISC Library API.

    Returns:
        Self: The namespace at stage 1; call ``study_header()`` next.

    Examples:
        Fetch the TE structure from the CDISC Library::

            te = (
                pl.DataFrame().sdtm
                .fetch_structure("TE", ig_version="3-4",
                                 save_to="metadata/te_structure.yaml")
                .study_header("CDISCPILOT01", "TE")
                .add_elements(te_rows)
                .to_frame()
            )
    """
    self._check_stage("fetch_structure", required=0)
    domain = domain.upper()

    # Priority: define_path → save_to cache → packaged IG 3.4 → online
    meta: dict[str, Any] | None = None

    if define_path is not None:
        meta = _extract_domain_from_define(domain, Path(define_path))

    cache_path = Path(save_to) if save_to else None
    if meta is None and cache_path and cache_path.exists():
        meta = yaml.safe_load(cache_path.read_text(encoding="utf-8"))

    if meta is None:
        meta = _load_packaged_structure(domain, ig_version)
        if meta is None:
            try:
                meta = self._fetch_ig_domain(domain, ig_version)
            except Exception as exc:
                raise type(exc)(
                    f"Domain '{domain}' not found in SDTM IG {ig_version}. "
                    f"If this is a company-specific domain, provide its structure "
                    f"via define_path= or a cached YAML via save_to=."
                ) from exc
        if cache_path:
            cache_path.parent.mkdir(parents=True, exist_ok=True)
            cache_path.write_text(
                yaml.dump(meta, default_flow_style=False, sort_keys=False), encoding="utf-8"
            )

    # Propagate to the new namespace instance
    new = self._chain()  # type: ignore[attr-defined]
    new._domain_meta = meta
    new._tdd_stage = 1
    new._reconciliation_report = _reconcile_schema(domain, meta)
    for msg in new._reconciliation_report:
        warnings.warn(msg, UserWarning, stacklevel=2)
    return new  # type: ignore[return-value]

study_header

study_header(study_id, domain)

Hardcode STUDYID and DOMAIN columns.

Parameters:

Name Type Description Default
study_id str

The study identifier value.

required
domain str

The SDTM domain code.

required

Returns:

Name Type Description
Self Self

The namespace at stage 2; call an add_*() verb next.

Examples:

Set the study header for a TE domain::

te = (
    pl.DataFrame().sdtm
    .fetch_structure("TE")
    .study_header("CDISCPILOT01", "TE")
    .add_elements(te_rows)
    .to_frame()
)
Source code in src/fleet/sdtm/_tdd_mixin.py
def study_header(
    self,
    study_id: str,
    domain: str,
) -> Self:  # type: ignore[type-var]
    """Hardcode ``STUDYID`` and ``DOMAIN`` columns.

    Args:
        study_id: The study identifier value.
        domain: The SDTM domain code.

    Returns:
        Self: The namespace at stage 2; call an ``add_*()`` verb next.

    Examples:
        Set the study header for a TE domain::

            te = (
                pl.DataFrame().sdtm
                .fetch_structure("TE")
                .study_header("CDISCPILOT01", "TE")
                .add_elements(te_rows)
                .to_frame()
            )
    """
    self._check_stage("study_header", required=1)
    new = self._chain(  # type: ignore[attr-defined]
        pl.lit(study_id).alias("STUDYID"),
        pl.lit(domain.upper()).alias("DOMAIN"),
    )
    new._tdd_stage = 2
    return new  # type: ignore[return-value]

add_elements

add_elements(elements)

Materialise a validated TrialElements collection into the pipeline.

Parameters:

Name Type Description Default
elements TrialElements

A TrialElements collection (pre-validated by Pydantic).

required

Returns:

Name Type Description
Self Self

The namespace at stage 3 with TE rows loaded.

Examples:

Add trial elements to a TE pipeline::

te = (
    pl.DataFrame().sdtm
    .fetch_structure("TE")
    .study_header("CDISCPILOT01", "TE")
    .add_elements(te_rows)
    .to_frame()
)
Source code in src/fleet/sdtm/_tdd_mixin.py
def add_elements(self, elements: TrialElements) -> Self:  # type: ignore[type-var]
    """Materialise a validated ``TrialElements`` collection into the pipeline.

    Args:
        elements: A ``TrialElements`` collection (pre-validated by Pydantic).

    Returns:
        Self: The namespace at stage 3 with TE rows loaded.

    Examples:
        Add trial elements to a TE pipeline::

            te = (
                pl.DataFrame().sdtm
                .fetch_structure("TE")
                .study_header("CDISCPILOT01", "TE")
                .add_elements(te_rows)
                .to_frame()
            )
    """
    self._check_stage("add_elements", required=2)
    return self._materialise_collection(elements.to_polars())

add_arms

add_arms(arms, *, te=None)

Materialise a validated TrialArms collection into the pipeline.

Parameters:

Name Type Description Default
arms TrialArms

A TrialArms collection.

required
te TrialElements | None

Optional TrialElements for FK validation (ETCD ∈ TE.ETCD).

None

Returns:

Name Type Description
Self Self

The namespace at stage 3 with TA rows loaded.

Examples:

Add trial arms with FK validation::

ta = (
    pl.DataFrame().sdtm
    .fetch_structure("TA")
    .study_header("CDISCPILOT01", "TA")
    .add_arms(ta_rows, te=te_rows)
    .to_frame()
)
Source code in src/fleet/sdtm/_tdd_mixin.py
def add_arms(
    self,
    arms: TrialArms,
    *,
    te: TrialElements | None = None,
) -> Self:  # type: ignore[type-var]
    """Materialise a validated ``TrialArms`` collection into the pipeline.

    Args:
        arms: A ``TrialArms`` collection.
        te: Optional ``TrialElements`` for FK validation (ETCD ∈ TE.ETCD).

    Returns:
        Self: The namespace at stage 3 with TA rows loaded.

    Examples:
        Add trial arms with FK validation::

            ta = (
                pl.DataFrame().sdtm
                .fetch_structure("TA")
                .study_header("CDISCPILOT01", "TA")
                .add_arms(ta_rows, te=te_rows)
                .to_frame()
            )
    """
    self._check_stage("add_arms", required=2)
    if te is not None:
        valid_etcds = {e.etcd for e in te.elements}
        for a in arms.arms:
            if a.etcd not in valid_etcds:
                raise ValueError(
                    f"TA.ETCD '{a.etcd}' not found in TE. Valid: {sorted(valid_etcds)}"
                )
    return self._materialise_collection(arms.to_polars())

add_visits

add_visits(visits, *, ta=None)

Materialise a validated TrialVisits collection into the pipeline.

Parameters:

Name Type Description Default
visits TrialVisits

A TrialVisits collection.

required
ta TrialArms | None

Optional TrialArms for FK validation (non-blank ARMCD ∈ TA.ARMCD).

None

Returns:

Name Type Description
Self Self

The namespace at stage 3 with TV rows loaded.

Examples:

Add trial visits with FK validation::

tv = (
    pl.DataFrame().sdtm
    .fetch_structure("TV")
    .study_header("CDISCPILOT01", "TV")
    .add_visits(tv_rows, ta=ta_rows)
    .to_frame()
)
Source code in src/fleet/sdtm/_tdd_mixin.py
def add_visits(
    self,
    visits: TrialVisits,
    *,
    ta: TrialArms | None = None,
) -> Self:  # type: ignore[type-var]
    """Materialise a validated ``TrialVisits`` collection into the pipeline.

    Args:
        visits: A ``TrialVisits`` collection.
        ta: Optional ``TrialArms`` for FK validation (non-blank
            ARMCD ∈ TA.ARMCD).

    Returns:
        Self: The namespace at stage 3 with TV rows loaded.

    Examples:
        Add trial visits with FK validation::

            tv = (
                pl.DataFrame().sdtm
                .fetch_structure("TV")
                .study_header("CDISCPILOT01", "TV")
                .add_visits(tv_rows, ta=ta_rows)
                .to_frame()
            )
    """
    self._check_stage("add_visits", required=2)
    if ta is not None:
        valid_armcds = {a.armcd for a in ta.arms}
        for v in visits.visits:
            if v.armcd and v.armcd not in valid_armcds:
                raise ValueError(
                    f"TV.ARMCD '{v.armcd}' not found in TA. Valid: {sorted(valid_armcds)}"
                )
    return self._materialise_collection(visits.to_polars())

add_parameters

add_parameters(params)

Materialise a validated TrialParameters collection into the pipeline.

Parameters:

Name Type Description Default
params TrialParameters

A TrialParameters collection.

required

Returns:

Name Type Description
Self Self

The namespace at stage 3 with TS rows loaded.

Examples:

Add trial summary parameters::

ts = (
    pl.DataFrame().sdtm
    .fetch_structure("TS")
    .study_header("CDISCPILOT01", "TS")
    .add_parameters(ts_rows)
    .to_frame()
)
Source code in src/fleet/sdtm/_tdd_mixin.py
def add_parameters(self, params: TrialParameters) -> Self:  # type: ignore[type-var]
    """Materialise a validated ``TrialParameters`` collection into the pipeline.

    Args:
        params: A ``TrialParameters`` collection.

    Returns:
        Self: The namespace at stage 3 with TS rows loaded.

    Examples:
        Add trial summary parameters::

            ts = (
                pl.DataFrame().sdtm
                .fetch_structure("TS")
                .study_header("CDISCPILOT01", "TS")
                .add_parameters(ts_rows)
                .to_frame()
            )
    """
    self._check_stage("add_parameters", required=2)
    return self._materialise_collection(params.to_polars())

add_criteria

add_criteria(criteria)

Materialise a validated TrialCriteria collection into the pipeline.

Parameters:

Name Type Description Default
criteria TrialCriteria

A TrialCriteria collection.

required

Returns:

Name Type Description
Self Self

The namespace at stage 3 with TI rows loaded.

Examples:

Add inclusion/exclusion criteria::

ti = (
    pl.DataFrame().sdtm
    .fetch_structure("TI")
    .study_header("CDISCPILOT01", "TI")
    .add_criteria(ti_rows)
    .to_frame()
)
Source code in src/fleet/sdtm/_tdd_mixin.py
def add_criteria(self, criteria: TrialCriteria) -> Self:  # type: ignore[type-var]
    """Materialise a validated ``TrialCriteria`` collection into the pipeline.

    Args:
        criteria: A ``TrialCriteria`` collection.

    Returns:
        Self: The namespace at stage 3 with TI rows loaded.

    Examples:
        Add inclusion/exclusion criteria::

            ti = (
                pl.DataFrame().sdtm
                .fetch_structure("TI")
                .study_header("CDISCPILOT01", "TI")
                .add_criteria(ti_rows)
                .to_frame()
            )
    """
    self._check_stage("add_criteria", required=2)
    return self._materialise_collection(criteria.to_polars())

add_disease_assessments

add_disease_assessments(assessments)

Materialise a validated TrialDiseaseAssessments collection.

Parameters:

Name Type Description Default
assessments TrialDiseaseAssessments

A TrialDiseaseAssessments collection.

required

Returns:

Name Type Description
Self Self

The namespace at stage 3 with TD rows loaded.

Examples:

Add trial disease assessments::

td = (
    pl.DataFrame().sdtm
    .fetch_structure("TD")
    .study_header("CDISCPILOT01", "TD")
    .add_disease_assessments(td_rows)
    .to_frame()
)
Source code in src/fleet/sdtm/_tdd_mixin.py
def add_disease_assessments(self, assessments: TrialDiseaseAssessments) -> Self:  # type: ignore[type-var]
    """Materialise a validated ``TrialDiseaseAssessments`` collection.

    Args:
        assessments: A ``TrialDiseaseAssessments`` collection.

    Returns:
        Self: The namespace at stage 3 with TD rows loaded.

    Examples:
        Add trial disease assessments::

            td = (
                pl.DataFrame().sdtm
                .fetch_structure("TD")
                .study_header("CDISCPILOT01", "TD")
                .add_disease_assessments(td_rows)
                .to_frame()
            )
    """
    self._check_stage("add_disease_assessments", required=2)
    return self._materialise_collection(assessments.to_polars())

add_milestones

add_milestones(milestones)

Materialise a validated TrialMilestones collection.

Parameters:

Name Type Description Default
milestones TrialMilestones

A TrialMilestones collection.

required

Returns:

Name Type Description
Self Self

The namespace at stage 3 with TM rows loaded.

Examples:

Add trial disease milestones::

tm = (
    pl.DataFrame().sdtm
    .fetch_structure("TM")
    .study_header("CDISCPILOT01", "TM")
    .add_milestones(tm_rows)
    .to_frame()
)
Source code in src/fleet/sdtm/_tdd_mixin.py
def add_milestones(self, milestones: TrialMilestones) -> Self:  # type: ignore[type-var]
    """Materialise a validated ``TrialMilestones`` collection.

    Args:
        milestones: A ``TrialMilestones`` collection.

    Returns:
        Self: The namespace at stage 3 with TM rows loaded.

    Examples:
        Add trial disease milestones::

            tm = (
                pl.DataFrame().sdtm
                .fetch_structure("TM")
                .study_header("CDISCPILOT01", "TM")
                .add_milestones(tm_rows)
                .to_frame()
            )
    """
    self._check_stage("add_milestones", required=2)
    return self._materialise_collection(milestones.to_polars())

visit_map

visit_map(
    target_num,
    target_name,
    *,
    date_col,
    planned_visits,
    ref_date=None,
    tolerance=None
)

Map raw visit dates to planned visits from TV, by nearest study day.

Use it only when the CRF does not collect the visit: it never replaces a collected VISITNUM. For each row, the verb takes the planned visit whose VISITDY is nearest to the actual study day (from date_col and ref_date), within the optional tolerance window. The distance is the difference of the study-day numbers, as abs(SVSTDY - VISITDY) in a SAS program: across the missing Day 0, Day -1 is 2 days from VISITDY 1. Ties resolve to the earlier VISITNUM. When TV has ARMCD values, a row only takes a visit of its own arm or a visit with a blank ARMCD.

A dated row outside every window is an unscheduled visit. It gets the VISITNUM of the last planned visit on or before its study day plus .1, .2, ... in date order within the subject, and the VISIT UNSCHEDULED <VISITNUM>. A row with no study day gets a null. One warning gives both counts. With DOMAIN SV, one warning gives the USUBJID + VISITNUM keys that repeat.

Parameters:

Name Type Description Default
target_num str

Name of the output VISITNUM column. An existing column of that name is replaced.

required
target_name str

Name of the output VISIT column. An existing column of that name is replaced.

required
date_col str

Column containing the actual visit date (ISO 8601 string).

required
planned_visits TrialVisits | DataFrame

A TrialVisits collection or a DataFrame with VISITNUM, VISIT, and VISITDY columns (and optionally ARMCD).

required
ref_date str | None

Column with the reference date for the study day. When it is not a column of the frame, it is read from the pinned DM, as study_day() does. When None, the frame must hold the study day in a VISITDY column.

None
tolerance dict[str, int] | None

Optional {"before": n, "after": n} window in study days, boundaries inclusive: the actual study day may precede the planned VISITDY by up to before and follow it by up to after.

None

Returns:

Name Type Description
Self Self

The namespace with target_num and target_name appended.

Raises:

Type Description
DerivationError

When date_col or ref_date cannot be found, when TV has arm-specific visits and the frame has no ARMCD, or when an unscheduled number would repeat a planned VISITNUM or reach the next whole number.

References

SDTMIG 3.4 SV and TV: USUBJID + VISITNUM is the SV key, VISITNUM is Req, a null TV ARMCD means all arms. The decimal number of an unscheduled visit is a sponsor convention (the CDISC pilot uses UNSCHEDULED 5.1); see docs/adr/0035-visit-map-numbers-an-unscheduled-visit.md.

Examples:

Map subject visits to planned visits::

sv = (
    raw_visits.sdtm
    .assign("DOMAIN", value="SV")
    .assign("USUBJID", source="subject_id")
    .date("SVSTDTC", source="visit_date")
    .pin("DM", dm)
    .visit_map("VISITNUM", "VISIT",
               date_col="SVSTDTC",
               planned_visits=tv_rows,
               ref_date="RFSTDTC",
               tolerance={"before": 3, "after": 3})
    .to_frame()
)
Source code in src/fleet/sdtm/_tdd_mixin.py
def visit_map(
    self,
    target_num: str,
    target_name: str,
    *,
    date_col: str,
    planned_visits: TrialVisits | pl.DataFrame,
    ref_date: str | None = None,
    tolerance: dict[str, int] | None = None,
) -> Self:  # type: ignore[type-var]
    """Map raw visit dates to planned visits from TV, by nearest study day.

    Use it only when the CRF does not collect the visit: it never
    replaces a collected VISITNUM.  For each row, the verb takes the
    planned visit whose ``VISITDY`` is nearest to the actual study day
    (from *date_col* and *ref_date*), within the optional *tolerance*
    window.  The distance is the difference of the study-day numbers,
    as ``abs(SVSTDY - VISITDY)`` in a SAS program: across the missing
    Day 0, Day -1 is 2 days from ``VISITDY`` 1.  Ties resolve to the
    earlier ``VISITNUM``.  When TV has ``ARMCD`` values, a row only
    takes a visit of its own arm or a visit with a blank ``ARMCD``.

    A dated row outside every window is an unscheduled visit.  It gets
    the ``VISITNUM`` of the last planned visit on or before its study
    day plus .1, .2, ... in date order within the subject, and the
    ``VISIT`` ``UNSCHEDULED <VISITNUM>``.  A row with no study day gets
    a null.  One warning gives both counts.  With ``DOMAIN`` SV, one
    warning gives the ``USUBJID`` + ``VISITNUM`` keys that repeat.

    Args:
        target_num: Name of the output ``VISITNUM`` column.  An
            existing column of that name is replaced.
        target_name: Name of the output ``VISIT`` column.  An existing
            column of that name is replaced.
        date_col: Column containing the actual visit date (ISO 8601 string).
        planned_visits: A ``TrialVisits`` collection or a DataFrame with
            ``VISITNUM``, ``VISIT``, and ``VISITDY`` columns (and
            optionally ``ARMCD``).
        ref_date: Column with the reference date for the study day.
            When it is not a column of the frame, it is read from the
            pinned DM, as ``study_day()`` does.  When ``None``, the
            frame must hold the study day in a ``VISITDY`` column.
        tolerance: Optional ``{"before": n, "after": n}`` window in
            study days, boundaries inclusive: the actual study day may
            precede the planned ``VISITDY`` by up to *before* and
            follow it by up to *after*.

    Returns:
        Self: The namespace with *target_num* and *target_name* appended.

    Raises:
        DerivationError: When *date_col* or *ref_date* cannot be found,
            when TV has arm-specific visits and the frame has no
            ``ARMCD``, or when an unscheduled number would repeat a
            planned ``VISITNUM`` or reach the next whole number.

    References:
        SDTMIG 3.4 SV and TV: ``USUBJID`` + ``VISITNUM`` is the SV key,
        ``VISITNUM`` is Req, a null TV ``ARMCD`` means all arms.  The
        decimal number of an unscheduled visit is a sponsor convention
        (the CDISC pilot uses ``UNSCHEDULED 5.1``); see
        ``docs/adr/0035-visit-map-numbers-an-unscheduled-visit.md``.

    Examples:
        Map subject visits to planned visits::

            sv = (
                raw_visits.sdtm
                .assign("DOMAIN", value="SV")
                .assign("USUBJID", source="subject_id")
                .date("SVSTDTC", source="visit_date")
                .pin("DM", dm)
                .visit_map("VISITNUM", "VISIT",
                           date_col="SVSTDTC",
                           planned_visits=tv_rows,
                           ref_date="RFSTDTC",
                           tolerance={"before": 3, "after": 3})
                .to_frame()
            )
    """
    tv_df = (
        planned_visits.to_polars()
        if isinstance(planned_visits, TrialVisits)
        else planned_visits
    )
    verb = f"visit_map({target_num})"
    df = self._lazy.collect().with_row_index("__row_idx__")  # type: ignore[attr-defined]
    df = df.drop([c for c in (target_num, target_name) if c in df.columns])
    actual = self._visit_map_study_day(df, verb, date_col, ref_date)
    df = df.with_columns(actual.alias("__actual_dy__"))

    tv_arm = (
        pl.col("ARMCD").cast(pl.String).replace("", None)
        if "ARMCD" in tv_df.columns
        else pl.lit(None, dtype=pl.String)
    )
    tv_slim = tv_df.select(
        pl.col("VISITNUM").alias("__tv_num__"),
        pl.col("VISIT").alias("__tv_name__"),
        pl.col("VISITDY").alias("__tv_dy__"),
        tv_arm.alias("__tv_arm__"),
    )
    arm_specific = tv_slim["__tv_arm__"].is_not_null().any()
    if arm_specific and "ARMCD" not in df.columns:
        raise DerivationError(
            f"{verb}: the planned visits hold arm-specific ARMCD values, and the frame "
            "has no ARMCD column. Add ARMCD so each subject takes only the visits of its arm."
        )

    crossed = df.select("__row_idx__", "__actual_dy__", *(["ARMCD"] if arm_specific else []))
    crossed = crossed.join(tv_slim, how="cross").filter(pl.col("__actual_dy__").is_not_null())
    if arm_specific:
        crossed = crossed.filter(
            pl.col("__tv_arm__").is_null() | (pl.col("__tv_arm__") == pl.col("ARMCD"))
        )
    offset = pl.col("__actual_dy__") - pl.col("__tv_dy__")
    candidates = crossed.filter(offset.is_not_null()).with_columns(
        offset.abs().alias("__diff__")
    )
    if tolerance:
        before = tolerance.get("before", 999999)
        after = tolerance.get("after", 999999)
        candidates = candidates.filter((offset >= -before) & (offset <= after))

    best = (
        candidates.sort("__row_idx__", "__diff__", "__tv_num__")
        .group_by("__row_idx__", maintain_order=True)
        .first()
        .select("__row_idx__", "__tv_num__", "__tv_name__")
    )
    unscheduled = _unscheduled_visits(df, crossed, best, verb, tv_slim)
    best = pl.concat([best, unscheduled], how="vertical_relaxed").rename(
        {"__tv_num__": target_num, "__tv_name__": target_name}
    )

    df = (
        df.join(best, on="__row_idx__", how="left")
        .sort("__row_idx__")
        .drop("__row_idx__", "__actual_dy__")
    )
    _warn_visit_map(df, verb, target_num, unscheduled.height)
    return self._materialise_then(df)  # type: ignore[attr-defined]

element_boundaries

element_boundaries(
    target_start,
    target_end,
    *,
    milestones,
    element_col="ETCD",
    subject_col="USUBJID"
)

Derive element start/end dates from milestone columns.

For each element_col value, maps the corresponding column from milestones to produce target_start. The end date is the start of the next element by start date within the subject: the verb sorts on the ISO 8601 start text (a null start last, then the row order), so the input row order does not matter. The output keeps the input row order. The last element gets a null end.

Parameters:

Name Type Description Default
target_start str

Name of the output start-date column (e.g. "SESTDTC").

required
target_end str

Name of the output end-date column (e.g. "SEENDTC").

required
milestones dict[str, str]

{element_code: source_date_column} mapping.

required
element_col str

Column identifying the element (default "ETCD").

'ETCD'
subject_col str

Column identifying the subject (default "USUBJID").

'USUBJID'

Returns:

Name Type Description
Self Self

The namespace with target_start and target_end appended.

Examples:

Derive SE element boundaries::

se = (
    disposition_df.sdtm
    .element_boundaries("SESTDTC", "SEENDTC",
                        milestones={"SCRN": "screening_date",
                                     "TRT": "first_dose_date"})
    .to_frame()
)
Source code in src/fleet/sdtm/_tdd_mixin.py
def element_boundaries(
    self,
    target_start: str,
    target_end: str,
    *,
    milestones: dict[str, str],
    element_col: str = "ETCD",
    subject_col: str = "USUBJID",
) -> Self:  # type: ignore[type-var]
    """Derive element start/end dates from milestone columns.

    For each *element_col* value, maps the corresponding column from
    *milestones* to produce *target_start*.  The end date is the start
    of the next element by start date within the subject: the verb
    sorts on the ISO 8601 start text (a null start last, then the row
    order), so the input row order does not matter.  The output keeps
    the input row order.  The last element gets a null end.

    Args:
        target_start: Name of the output start-date column (e.g. ``"SESTDTC"``).
        target_end: Name of the output end-date column (e.g. ``"SEENDTC"``).
        milestones: ``{element_code: source_date_column}`` mapping.
        element_col: Column identifying the element (default ``"ETCD"``).
        subject_col: Column identifying the subject (default ``"USUBJID"``).

    Returns:
        Self: The namespace with *target_start* and *target_end* appended.

    Examples:
        Derive SE element boundaries::

            se = (
                disposition_df.sdtm
                .element_boundaries("SESTDTC", "SEENDTC",
                                    milestones={"SCRN": "screening_date",
                                                 "TRT": "first_dose_date"})
                .to_frame()
            )
    """
    # Build a when/then chain mapping element codes to date columns
    cases: list[tuple[str, str]] = list(milestones.items())
    if not cases:
        return self._chain(  # type: ignore[attr-defined]
            pl.lit(None).alias(target_start),
            pl.lit(None).alias(target_end),
        )

    first_code, first_col = cases[0]
    expr = pl.when(pl.col(element_col) == first_code).then(pl.col(first_col))
    for code, col in cases[1:]:
        expr = expr.when(pl.col(element_col) == code).then(pl.col(col))
    start_expr = expr.otherwise(pl.lit(None)).alias(target_start)

    # End = next element's start within the subject, in start-date order
    df = self._lazy.collect().with_row_index("__row_idx__")  # type: ignore[attr-defined]
    df = df.with_columns(start_expr)
    df = (
        df.sort(subject_col, target_start, "__row_idx__", nulls_last=True)
        .with_columns(pl.col(target_start).shift(-1).over(subject_col).alias(target_end))
        .sort("__row_idx__")
        .drop("__row_idx__")
    )

    return self._materialise_then(df)  # type: ignore[attr-defined]

epoch_assign

epoch_assign(
    target,
    *,
    date_col,
    epoch_ranges=None,
    se=None,
    subject_col="USUBJID",
    same_day="by_class"
)

Assign EPOCH based on date ranges or per-subject SE intervals.

With epoch_ranges, each entry maps a study-level date interval to an Epoch value; the first matching range wins. With se, the subject's own element intervals drive the assignment: for each row, the epoch of the SE record whose [SESTDTC, SEENDTC] interval contains the date (SDTMIG 3.4: EPOCH of the start or collection date/time). A blank or null SEENDTC is open-ended; an element whose dates are partial is skipped, with a warning.

On a transition date, where one element ends and the next starts, the time decides when the record and the boundary both have one. When one of them has no time, same_day decides, and one warning gives the count and the rule:

  • "by_class" (default): a Findings date (--DTC) takes the earlier element, an Events or Interventions date (--STDTC) the later one. Any other date_col name raises.
  • "earlier": the element that ends on that date.
  • "later": the element that starts on that date.

No guidance fixes this case, so state the rule in the SDRG.

Parameters:

Name Type Description Default
target str

Name of the output EPOCH column.

required
date_col str

Column containing the date to classify.

required
epoch_ranges list[dict[str, str]] | DataFrame | None

A list of {"start": date, "end": date, "epoch": str} dicts, or a DataFrame with those columns.

None
se DataFrame | LazyFrame | None

An SE domain frame with USUBJID, SESTDTC, SEENDTC, and EPOCH columns. Mutually exclusive with epoch_ranges.

None
subject_col str

Subject key used to join se (default "USUBJID").

'USUBJID'
same_day Literal['by_class', 'earlier', 'later']

The rule for a record with no time on a transition date (with se only).

'by_class'

Returns:

Name Type Description
Self Self

The namespace with target appended.

Raises:

Type Description
ValueError

When neither or both of epoch_ranges and se are provided.

DerivationError

When same_day="by_class" and date_col is neither a --DTC nor a --STDTC name.

Examples:

Stamp EPOCH onto any domain from the subject's SE intervals::

ae = (
    ae_raw.sdtm
    .assign("USUBJID", source="subject_id")
    .date("AESTDTC", source="ae_start_date")
    .epoch_assign("EPOCH", date_col="AESTDTC", se=se)
    .to_frame()
)
Source code in src/fleet/sdtm/_tdd_mixin.py
def epoch_assign(
    self,
    target: str,
    *,
    date_col: str,
    epoch_ranges: list[dict[str, str]] | pl.DataFrame | None = None,
    se: pl.DataFrame | pl.LazyFrame | None = None,
    subject_col: str = "USUBJID",
    same_day: Literal["by_class", "earlier", "later"] = "by_class",
) -> Self:  # type: ignore[type-var]
    """Assign ``EPOCH`` based on date ranges or per-subject SE intervals.

    With *epoch_ranges*, each entry maps a study-level date interval to
    an ``Epoch`` value; the first matching range wins.  With *se*, the
    subject's own element intervals drive the assignment: for each row,
    the epoch of the SE record whose ``[SESTDTC, SEENDTC]`` interval
    contains the date (SDTMIG 3.4: EPOCH of the start or collection
    date/time).  A blank or null ``SEENDTC`` is open-ended; an element
    whose dates are partial is skipped, with a warning.

    On a transition date, where one element ends and the next starts,
    the time decides when the record and the boundary both have one.
    When one of them has no time, *same_day* decides, and one warning
    gives the count and the rule:

    - ``"by_class"`` (default): a Findings date (``--DTC``) takes the
      earlier element, an Events or Interventions date (``--STDTC``)
      the later one.  Any other *date_col* name raises.
    - ``"earlier"``: the element that ends on that date.
    - ``"later"``: the element that starts on that date.

    No guidance fixes this case, so state the rule in the SDRG.

    Args:
        target: Name of the output ``EPOCH`` column.
        date_col: Column containing the date to classify.
        epoch_ranges: A list of ``{"start": date, "end": date,
            "epoch": str}`` dicts, or a DataFrame with those columns.
        se: An SE domain frame with ``USUBJID``, ``SESTDTC``,
            ``SEENDTC``, and ``EPOCH`` columns.  Mutually exclusive
            with *epoch_ranges*.
        subject_col: Subject key used to join *se* (default
            ``"USUBJID"``).
        same_day: The rule for a record with no time on a transition
            date (with *se* only).

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

    Raises:
        ValueError: When neither or both of *epoch_ranges* and *se*
            are provided.
        DerivationError: When ``same_day="by_class"`` and *date_col*
            is neither a ``--DTC`` nor a ``--STDTC`` name.

    Examples:
        Stamp EPOCH onto any domain from the subject's SE intervals::

            ae = (
                ae_raw.sdtm
                .assign("USUBJID", source="subject_id")
                .date("AESTDTC", source="ae_start_date")
                .epoch_assign("EPOCH", date_col="AESTDTC", se=se)
                .to_frame()
            )
    """
    if (epoch_ranges is None) == (se is None):
        raise ValueError("epoch_assign() takes exactly one of epoch_ranges= or se=")

    if se is not None:
        rule = _same_day_rule(date_col, same_day)
        df = self._lazy.collect().with_row_index("__row_idx__")  # type: ignore[attr-defined]
        best = _epoch_from_se(df, se, target, date_col, subject_col, rule, same_day)
        out = (
            df.drop(target, strict=False)
            .join(best, on="__row_idx__", how="left")
            .drop("__row_idx__")
        )
        return self._materialise_then(out)  # type: ignore[attr-defined]

    if isinstance(epoch_ranges, pl.DataFrame):
        ranges = epoch_ranges.to_dicts()
    else:
        ranges = epoch_ranges

    if not ranges:
        return self._chain(pl.lit(None).alias(target))  # type: ignore[attr-defined]

    day = date_part(pl.col(date_col))
    expr = pl.when(pl.lit(False)).then(pl.lit(None, dtype=pl.String))
    for r in ranges:
        start = date_part(pl.lit(str(r["start"])))
        end = date_part(pl.lit(str(r["end"])))
        expr = expr.when((day >= start) & (day <= end)).then(pl.lit(r["epoch"]))

    final_expr = expr.otherwise(pl.lit(None)).alias(target)
    return self._chain(final_expr)  # type: ignore[attr-defined]

packaged_structure

packaged_structure(domain)

Return the packaged SDTMIG 3.4 label and variables of a trial design domain.

Source code in src/fleet/sdtm/_tdd_mixin.py
def packaged_structure(domain: str) -> dict[str, Any] | None:
    """Return the packaged SDTMIG 3.4 label and variables of a trial design domain."""
    return _load_packaged_structure(domain.upper(), _PACKAGED_IG_VERSION)

options: show_source: false heading_level: 2 members_order: source show_root_heading: true members: - TrialDesignMixin