Skip to content

Controlled Terminology

Fleet provides three layers for working with CDISC Controlled Terminology:

  1. CDISC Library API client — download CT directly from the authoritative source.
  2. Code generator — turn API responses into typed Python constants with IDE auto-completion.
  3. CT validator — validate values at runtime against loaded codelists.

CDISC Library API Client

The CDISCClient wraps httpx to authenticate against the CDISC Library REST API. It requires an API key set via a .env file or the CDISC_API_KEY environment variable.

fleet.ct.CDISCClient dataclass

HTTP client for the CDISC Library REST API.

Parameters:

Name Type Description Default
config CDISCClientConfig

Optional explicit configuration. When omitted the client auto-discovers credentials from the environment / .env.

CDISCClientConfig()

Examples:

Fetch the SEX codelist::

client = CDISCClient()
terms = client.get_codelist("C66731")
Source code in src/fleet/ct/api.py
@dataclass
class CDISCClient:
    """HTTP client for the CDISC Library REST API.

    Args:
        config: Optional explicit configuration.  When omitted the client
            auto-discovers credentials from the environment / ``.env``.

    Examples:
        Fetch the SEX codelist::

            client = CDISCClient()
            terms = client.get_codelist("C66731")
    """

    config: CDISCClientConfig = field(default_factory=CDISCClientConfig)
    _http: httpx.Client = field(init=False, repr=False)

    def __post_init__(self) -> None:
        if not self.config.api_key:
            raise CTError(
                "CDISC API key is required. Set the CDISC_API_KEY environment "
                "variable, add it to a .env file, or pass it explicitly via "
                "CDISCClientConfig(api_key=...)."
            )
        self._http = httpx.Client(
            base_url=self.config.base_url,
            headers={
                "api-key": self.config.api_key,
                "Accept": "application/json",
            },
            timeout=30.0,
            follow_redirects=True,
        )

    # -- public helpers ------------------------------------------------- #

    def get_packages(self, product: str = "sdtmct") -> list[dict[str, Any]]:
        """List available CT packages for a product.

        Args:
            product: Product key recognised by the CDISC Library
                (e.g. ``"sdtmct"``, ``"adamct"``).

        Returns:
            List of package metadata dicts (keys vary by CDISC version).

        Raises:
            CTError: On network or authentication failure.
        """
        data = self._get(f"/mdr/ct/packages?type={product}")
        packages: list[dict[str, Any]] = data.get("_links", {}).get("packages", [])
        return packages

    def get_codelist(
        self,
        concept_id: str,
        *,
        package: str = "sdtmct-2023-12-15",
    ) -> dict[str, Any]:
        """Download a single codelist by NCI concept ID.

        Args:
            concept_id: NCI concept identifier (e.g. ``"C66731"``).
            package: CT package version string.

        Returns:
            Raw JSON dict from the CDISC Library containing
            ``submissionValue``, ``conceptId``, ``terms``, etc.

        Raises:
            CTError: On network, authentication, or 404 errors.
        """
        return self._get(f"/mdr/ct/packages/{package}/codelists/{concept_id}")

    # -- internals ------------------------------------------------------ #

    def _get(self, path: str) -> dict[str, Any]:
        """Perform an authenticated GET and return the JSON payload."""
        try:
            response = self._http.get(path)
            response.raise_for_status()
            return response.json()  # type: ignore[no-any-return]
        except httpx.HTTPStatusError as exc:
            status = exc.response.status_code
            if status == 401:
                raise CTError(
                    "CDISC API authentication failed (401). Check your CDISC_API_KEY."
                ) from exc
            if status == 404:
                raise CTNotFoundError(f"Resource not found on CDISC Library: {path}") from exc
            raise CTError(f"CDISC API request failed ({status}): {exc}") from exc
        except httpx.HTTPError as exc:
            raise CTError(f"Network error contacting CDISC Library: {exc}") from exc

    def close(self) -> None:
        """Close the underlying HTTP transport."""
        self._http.close()

    def __enter__(self) -> CDISCClient:
        return self

    def __exit__(self, *_: object) -> None:
        self.close()

get_packages

get_packages(product='sdtmct')

List available CT packages for a product.

Parameters:

Name Type Description Default
product str

Product key recognised by the CDISC Library (e.g. "sdtmct", "adamct").

'sdtmct'

Returns:

Type Description
list[dict[str, Any]]

List of package metadata dicts (keys vary by CDISC version).

Raises:

Type Description
CTError

On network or authentication failure.

Source code in src/fleet/ct/api.py
def get_packages(self, product: str = "sdtmct") -> list[dict[str, Any]]:
    """List available CT packages for a product.

    Args:
        product: Product key recognised by the CDISC Library
            (e.g. ``"sdtmct"``, ``"adamct"``).

    Returns:
        List of package metadata dicts (keys vary by CDISC version).

    Raises:
        CTError: On network or authentication failure.
    """
    data = self._get(f"/mdr/ct/packages?type={product}")
    packages: list[dict[str, Any]] = data.get("_links", {}).get("packages", [])
    return packages

get_codelist

get_codelist(concept_id, *, package='sdtmct-2023-12-15')

Download a single codelist by NCI concept ID.

Parameters:

Name Type Description Default
concept_id str

NCI concept identifier (e.g. "C66731").

required
package str

CT package version string.

'sdtmct-2023-12-15'

Returns:

Type Description
dict[str, Any]

Raw JSON dict from the CDISC Library containing

dict[str, Any]

submissionValue, conceptId, terms, etc.

Raises:

Type Description
CTError

On network, authentication, or 404 errors.

Source code in src/fleet/ct/api.py
def get_codelist(
    self,
    concept_id: str,
    *,
    package: str = "sdtmct-2023-12-15",
) -> dict[str, Any]:
    """Download a single codelist by NCI concept ID.

    Args:
        concept_id: NCI concept identifier (e.g. ``"C66731"``).
        package: CT package version string.

    Returns:
        Raw JSON dict from the CDISC Library containing
        ``submissionValue``, ``conceptId``, ``terms``, etc.

    Raises:
        CTError: On network, authentication, or 404 errors.
    """
    return self._get(f"/mdr/ct/packages/{package}/codelists/{concept_id}")

close

close()

Close the underlying HTTP transport.

Source code in src/fleet/ct/api.py
def close(self) -> None:
    """Close the underlying HTTP transport."""
    self._http.close()

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

fleet.ct.CDISCClientConfig dataclass

Configuration for the CDISC Library API client.

Values are resolved in order: 1. Explicit constructor arguments. 2. Environment variables (CDISC_API_KEY, CDISC_BASE_URL). 3. For the key only: a .env file in the working directory or a parent (see :func:try_load_dotenv).

Parameters:

Name Type Description Default
api_key str

CDISC Library API key.

''
base_url str

Root URL for the CDISC Library API.

_DEFAULT_BASE_URL
Source code in src/fleet/ct/api.py
@dataclass
class CDISCClientConfig:
    """Configuration for the CDISC Library API client.

    Values are resolved in order:
    1. Explicit constructor arguments.
    2. Environment variables (``CDISC_API_KEY``, ``CDISC_BASE_URL``).
    3. For the key only: a ``.env`` file in the working directory or a
       parent (see :func:`try_load_dotenv`).

    Args:
        api_key: CDISC Library API key.
        base_url: Root URL for the CDISC Library API.
    """

    api_key: str = ""
    base_url: str = _DEFAULT_BASE_URL

    def __post_init__(self) -> None:
        if not self.api_key:
            try_load_dotenv()
            self.api_key = os.environ.get("CDISC_API_KEY", "")
        if self.base_url == _DEFAULT_BASE_URL:
            env_url = os.environ.get("CDISC_BASE_URL", "")
            if env_url:
                self.base_url = env_url.rstrip("/")

options: show_root_heading: true heading_level: 3


Codelist Code Generator

The CodelistGenerator converts CDISC Library JSON responses into a Python module containing typed classes — one per codelist — with human-readable aliases and IDE auto-completion support.

# Bootstrap from the SDTM IG (source of truth)
fleet add-ct --domains DM,AE,VS,EX --output specs/my_study/sdtm/codelists.py

# Add domains later (preserves existing codelists)
fleet add-ct --domains LB,CM --output specs/my_study/sdtm/codelists.py

Programmatic usage

from fleet.ct.api import CDISCClient
from fleet.ct.generator import CodelistGenerator

with CDISCClient() as client:
    # Recommended: derive codelists from the SDTM IG
    gen = CodelistGenerator.from_sdtm_ig(
        client,
        domains=["DM", "AE", "VS", "EX"],
        package="sdtmct-2025-09-26",
    )
    gen.write("specs/my_study/sdtm/codelists.py")

Generated output

The generated codelists.py contains:

  • One class per codelist with _concept_id, _cdisc_url, and submission-value constants:
class C66731:
    """SEX (C66731).

    The assemblage of physical properties or qualities by which male is
    distinguished from female.

    See: https://library.cdisc.org/browser/#/codelist/C66731
    """

    _concept_id = "C66731"
    _cdisc_url = "https://library.cdisc.org/browser/#/codelist/C66731"
    F = "F"
    M = "M"
    U = "U"

!!! tip "Direct line to the source of truth" The _cdisc_url attribute and the See: line in each docstring point to the codelist's entry in the CDISC Library Browser. When a reviewer or auditor reads pipeline code, hovering SEX in an IDE shows the URL; clicking the link in the docs site takes them straight to the authoritative CDISC definition. There is no separate lookup table to maintain — the URL is constructed from the NCI concept ID at generation time.

  • Human-readable aliases derived from the CDISC submission value:
SEX = C66731
RACE = C74457
  • __all__ for clean wildcard imports:
from codelists import SEX, RACE

# or
from codelists import *
  • __ct_package__ at the top, naming the CT package every class came from (__ct_package__ = "sdtmct-2025-09-26"). A file with codelists from an SDTM and an ADaM package has __ct_packages__ instead (("adamct-2023-06-30", "sdtmct-2023-12-15")). The stale checks compare them with ct.package and ct.adam_package in study_config.yaml.

Importing codelists in standalone study projects

When your study lives in its own directory (not inside the Fleet repo), the generated codelists.py isn't on the Python path by default. Use import_codelists() to load it dynamically:

from fleet.ct import import_codelists

# Strategy 1: auto-discover via study_config.yaml in CWD or a parent folder
ct = import_codelists()
SEX = ct.SEX

# Strategy 2: register in sys.modules so bare imports work
import_codelists()  # one-time call
from codelists import SEX, RACE  # works for the rest of the session

# Strategy 3: explicit path (non-standard locations)
ct = import_codelists("/absolute/path/to/codelists.py")

Resolution order

When called without arguments, import_codelists() resolves the file as follows:

  1. study_config.yaml in CWD or the nearest parent folder (git-style, as the CLI does) → reads paths.metadata_sdtm → appends /codelists.py
  2. Falls back to <CWD>/metadata/sdtm/codelists.py

So a script in programs/sdtm finds the codelists of its study with no path.

Editor auto-completion

import_codelists() loads the module at run time, so the editor does not see from codelists import SEX by itself. Add the metadata folder to the analysis paths in .vscode/settings.json at the study root:

{"python.analysis.extraPaths": ["metadata/sdtm"]}

Using generated codelists in pipelines

from fleet.ct import import_codelists

ct = import_codelists()

dm = (
    raw_df.sdtm.assign("SEX", source="sex", ct=ct.SEX)
    .assign("RACE", source="race", ct=ct.RACE)
    .to_frame()
)

assign(ct=...) accepts either a codelist class (SEX) or a raw NCI concept ID string ("C66731"). The class form is preferred for readability and auto-completion.

fleet.ct.CodelistGenerator dataclass

Accumulates CDISC codelist JSON responses and renders them as Python.

Parameters:

Name Type Description Default
include_docs bool

If True (default), inject definition and preferredTerm from the CDISC JSON into class/attribute docstrings for richer AI context.

True
cdisc_url_template str

URL template used to build the _cdisc_url class attribute and the See: reference in each codelist's docstring. Substitution fields available: {concept_id}, {package} (e.g. sdtmct-2024-12-13), and {date} (the package date suffix). Defaults to the CDISC Library Browser deep link, which requires all three.

'https://library.cdisc.org/browser/#/mdr/ct/{date}/packages/{package}/codelists/{concept_id}'
Source code in src/fleet/ct/generator.py
@dataclass
class CodelistGenerator:
    """Accumulates CDISC codelist JSON responses and renders them as Python.

    Args:
        include_docs: If ``True`` (default), inject ``definition`` and
            ``preferredTerm`` from the CDISC JSON into class/attribute
            docstrings for richer AI context.
        cdisc_url_template: URL template used to build the
            ``_cdisc_url`` class attribute and the ``See:`` reference in
            each codelist's docstring.  Substitution fields available:
            ``{concept_id}``, ``{package}`` (e.g. ``sdtmct-2024-12-13``),
            and ``{date}`` (the package date suffix).  Defaults to the
            CDISC Library Browser deep link, which requires all three.
    """

    include_docs: bool = True
    cdisc_url_template: str = (
        "https://library.cdisc.org/browser/#/mdr/ct/{date}/packages/"
        "{package}/codelists/{concept_id}"
    )
    _codelists: list[dict[str, Any]] = field(default_factory=list, init=False)

    def add_codelist(
        self,
        codelist_json: dict[str, Any],
        *,
        package: str | None = None,
    ) -> None:
        """Register a raw CDISC Library codelist JSON response.

        Args:
            codelist_json: Dict returned by ``CDISCClient.get_codelist``.
                Must contain at least ``conceptId`` and ``terms``.
            package: Optional CT package the codelist was fetched from
                (e.g. ``"sdtmct-2024-12-13"``).  Stored on the codelist
                dict as ``_package`` so the rendered ``_cdisc_url`` can
                include the correct package + date context required by
                the CDISC Library Browser.

        Raises:
            ValueError: If required keys are missing.
        """
        if "conceptId" not in codelist_json:
            raise ValueError("codelist JSON must contain 'conceptId'")
        if package is not None:
            codelist_json = {**codelist_json, "_package": package}
        self._codelists.append(codelist_json)

    @property
    def concept_ids(self) -> set[str]:
        """Return the set of concept IDs already loaded."""
        return {cl["conceptId"] for cl in self._codelists}

    @property
    def codelist_count(self) -> int:
        """Return the number of codelists registered so far."""
        return len(self._codelists)

    @classmethod
    def from_concept_ids(
        cls,
        client: CDISCClient,
        concept_ids: set[str],
        *,
        package: str = "sdtmct-2023-12-15",
        adam_package: str | None = None,
        include_docs: bool = True,
    ) -> CodelistGenerator:
        """Build a generator from an explicit set of NCI concept IDs.

        Each codelist comes from the first package that holds it: *package*
        (SDTM CT), then *adam_package* (ADaM CT, for codelists such as
        DTYPE that only ADaM CT publishes).

        Args:
            client: An authenticated ``CDISCClient`` instance.
            concept_ids: Set of NCI concept ID strings to download.
            package: SDTM CT package version to download from.
            adam_package: ADaM CT package asked second; ``None`` for SDTM only.
            include_docs: Whether to include definitions in generated output.

        Returns:
            A ``CodelistGenerator`` populated with the requested codelists.

        Raises:
            CTError: When no pinned package holds a codelist (each ID is
                named), or on an authentication or network error.

        Examples:
            Generate codelists for specific concept IDs::

                from fleet.ct.api import CDISCClient
                from fleet.ct.generator import CodelistGenerator

                with CDISCClient() as client:
                    gen = CodelistGenerator.from_concept_ids(
                        client,
                        {"C66731", "C81224"},
                        adam_package="adamct-2023-06-30",
                    )
                    gen.write("codelists.py")
        """
        from fleet.core.exceptions import CTError, CTNotFoundError

        pins = [p for p in (package, adam_package) if p]
        gen = cls(include_docs=include_docs)
        missing: list[str] = []
        for cid in sorted(concept_ids):
            for pin in pins:
                try:
                    gen.add_codelist(client.get_codelist(cid, package=pin), package=pin)
                    break
                except CTNotFoundError:
                    continue
            else:
                missing.append(cid)
        if missing:
            raise CTError(
                f"{len(missing)} codelist(s) are in no pinned CT package "
                f"({', '.join(pins)}): {', '.join(missing)}. Correct the codelist id in "
                "define.yaml, or pin the package that holds it in study_config.yaml "
                "(ct.package, ct.adam_package)."
            )
        return gen

    @classmethod
    def from_sdtm_ig(
        cls,
        client: CDISCClient,
        domains: list[str],
        *,
        ig_version: str = "3-4",
        package: str = "sdtmct-2023-12-15",
        include_docs: bool = True,
    ) -> CodelistGenerator:
        """Build a generator from the SDTM IG — the authoritative source of truth.

        Queries the CDISC Library for the specified SDTM IG version,
        extracts every codelist referenced by variables in the requested
        domains, and downloads the corresponding CT definitions.

        Args:
            client: An authenticated ``CDISCClient`` instance.
            domains: List of SDTM domain abbreviations to include
                (e.g. ``["DM", "AE", "VS", "EX"]``).
            ig_version: SDTM IG version (default ``"3-4"``).
            package: CT package version to download terms from.
            include_docs: Whether to include definitions in generated output.

        Returns:
            A ``CodelistGenerator`` populated with all referenced codelists.

        Examples:
            Generate codelists for DM and AE from SDTM IG 3.4::

                from fleet.ct.api import CDISCClient
                from fleet.ct.generator import CodelistGenerator

                with CDISCClient() as client:
                    gen = CodelistGenerator.from_sdtm_ig(
                        client,
                        domains=["DM", "AE", "VS", "EX"],
                    )
                    gen.write("examples/cdiscpilot01/sdtm/codelists.py")
        """
        concept_ids = extract_ig_concept_ids(client, ig_version, domains)
        return cls.from_concept_ids(
            client,
            concept_ids,
            package=package,
            include_docs=include_docs,
        )

    def render(self) -> str:
        """Render accumulated codelists as a Python module string.

        Returns:
            A complete, syntactically valid Python source string.
        """
        sorted_cls = sorted(self._codelists, key=lambda c: c["conceptId"])

        lines: list[str] = [
            '"""Auto-generated CDISC Controlled Terminology constants.',
            "",
            "Do not edit manually — regenerate with ``fleet.ct.generator``.",
            '"""',
            "",
        ]
        # Marker for the stale checks of fleet.ct.study_codelists; two dates of one
        # product (two SDTM CT packages) get none, so check b reports the mix.
        packages = {cl.get("_package") for cl in sorted_cls}
        products = {str(p).split("-", 1)[0] for p in packages}
        if len(packages) == 1 and None not in packages:
            lines += [f"__ct_package__ = {packages.pop()!r}", "", ""]
        elif None not in packages and len(products) == len(packages) > 1:
            lines += [f"__ct_packages__ = {tuple(sorted(packages))!r}", "", ""]

        # Class definitions
        for cl in sorted_cls:
            lines.extend(self._render_class(cl))
            lines.append("")

        # Human-readable aliases  (e.g.  SEX = C66731)
        aliases: list[tuple[str, str]] = []
        for cl in sorted_cls:
            concept_id = cl["conceptId"]
            class_name = _safe_identifier(concept_id)
            alias = self._alias_for(cl)
            if alias and alias != class_name:
                aliases.append((alias, class_name))

        if aliases:
            lines.append("")
            lines.append("# Human-readable aliases")
            for alias, class_name in sorted(aliases):
                lines.append(f"{alias} = {class_name}")
            lines.append("")

        # __all__
        all_names: list[str] = [_safe_identifier(cl["conceptId"]) for cl in sorted_cls]
        all_names.extend(alias for alias, _ in sorted(aliases))
        all_names.sort()
        all_repr = ", ".join(f'"{n}"' for n in all_names)
        lines.append(f"__all__ = [{all_repr}]")
        lines.append("")

        return "\n".join(lines) + "\n"

    def write(self, path: str | Path) -> Path:
        """Render and write the module to *path*.

        Parent directories are created if they do not exist.

        Args:
            path: Destination file path.

        Returns:
            Resolved ``Path`` of the written file.
        """
        dest = Path(path)
        dest.parent.mkdir(parents=True, exist_ok=True)
        dest.write_text(self.render(), encoding="utf-8")
        return dest.resolve()

    def define_terms(self) -> dict[str, dict[str, Any]]:
        """The ``codelists:`` entry of ``define.yaml`` for each loaded codelist, by concept ID.

        Returns:
            dict[str, dict[str, Any]]: ``{"name": ..., "items": [{"coded_value": ...,
                "decode": ...}]}``; the decode is the NCI preferred term.
        """
        return {
            cl["conceptId"]: {
                "name": cl.get("name") or cl.get("submissionValue") or cl["conceptId"],
                "items": [
                    {
                        "coded_value": t["submissionValue"],
                        "decode": t.get("preferredTerm") or t["submissionValue"],
                    }
                    for t in cl.get("terms", [])
                ],
            }
            for cl in self._codelists
        }

    # -- private -------------------------------------------------------- #

    def _render_class(self, cl: dict[str, Any]) -> list[str]:
        concept_id: str = cl["conceptId"]
        class_name = _safe_identifier(concept_id)
        submission_value: str = cl.get("submissionValue", concept_id)
        preferred_term: str = cl.get("preferredTerm", "")
        definition: str = cl.get("definition", "")
        cdisc_url: str | None = self._build_cdisc_url(cl)

        # Class docstring
        doc_parts = [f"{submission_value} ({concept_id})."]
        if self.include_docs and definition:
            doc_parts.append("")
            doc_parts.append(textwrap.fill(definition, width=76))
        # Always add the CDISC Library reference so reviewers can jump from
        # generated code to the authoritative source-of-truth definition.
        if cdisc_url:
            doc_parts.append("")
            doc_parts.append(f"See: {cdisc_url}")

        class_doc = "\n    ".join(doc_parts)
        lines = [
            f"class {class_name}:",
            f'    """{class_doc}"""',
            "",
            f"    _concept_id = {concept_id!r}",
        ]
        if cdisc_url:
            lines.append(f"    _cdisc_url = {cdisc_url!r}")

        if self.include_docs and preferred_term:
            lines.append(f"    _preferred_term = {preferred_term!r}")
        lines.append("")

        terms: list[dict[str, Any]] = cl.get("terms", [])
        if not terms:
            lines.append("    pass")
            return lines

        submission_values = sorted({t.get("submissionValue", "") for t in terms} - {""})
        # Two terms can share one attribute name (2 and 3 TIMES PER WEEK).
        lines.append(f"    _terms = {tuple(submission_values)!r}")
        lines.append("")

        for term in sorted(terms, key=lambda t: t.get("submissionValue", "")):
            sv: str = term.get("submissionValue", "")
            if not sv:
                continue
            attr = _safe_identifier(sv)
            lines.append(f"    {attr} = {sv!r}")

            if self.include_docs:
                term_def = term.get("definition", "")
                if term_def:
                    comment = textwrap.shorten(term_def, width=72)
                    lines.append(f"    # {comment}")

        return lines

    def _build_cdisc_url(self, cl: dict[str, Any]) -> str | None:
        """Format the CDISC Library Browser URL for *cl*.

        Returns ``None`` when the template requires a ``{package}`` or
        ``{date}`` field but no package was recorded for this codelist
        (e.g. when ``add_codelist`` was called without ``package=``).
        """
        concept_id: str = cl["conceptId"]
        package: str | None = cl.get("_package")
        date: str | None = None
        if package and "-" in package:
            # e.g. "sdtmct-2024-12-13" -> "2024-12-13"
            _, _, date = package.partition("-")
        # If the template needs package/date context but none was
        # recorded, skip the URL rather than emit a broken link.
        needs_package = "{package}" in self.cdisc_url_template
        needs_date = "{date}" in self.cdisc_url_template
        if (needs_package and not package) or (needs_date and not date):
            return None
        try:
            return self.cdisc_url_template.format(
                concept_id=concept_id,
                package=package or "",
                date=date or "",
            )
        except KeyError:
            return None

    @staticmethod
    def _alias_for(cl: dict[str, Any]) -> str | None:
        """Derive a human-readable alias from the codelist submission value.

        Returns a valid Python identifier (e.g. ``"SEX"``, ``"RACE"``,
        ``"ETHNIC"``) or ``None`` when no usable name can be derived.
        """
        sv: str = cl.get("submissionValue", "")
        if not sv:
            return None
        return _safe_identifier(sv)

concept_ids property

concept_ids

Return the set of concept IDs already loaded.

codelist_count property

codelist_count

Return the number of codelists registered so far.

add_codelist

add_codelist(codelist_json, *, package=None)

Register a raw CDISC Library codelist JSON response.

Parameters:

Name Type Description Default
codelist_json dict[str, Any]

Dict returned by CDISCClient.get_codelist. Must contain at least conceptId and terms.

required
package str | None

Optional CT package the codelist was fetched from (e.g. "sdtmct-2024-12-13"). Stored on the codelist dict as _package so the rendered _cdisc_url can include the correct package + date context required by the CDISC Library Browser.

None

Raises:

Type Description
ValueError

If required keys are missing.

Source code in src/fleet/ct/generator.py
def add_codelist(
    self,
    codelist_json: dict[str, Any],
    *,
    package: str | None = None,
) -> None:
    """Register a raw CDISC Library codelist JSON response.

    Args:
        codelist_json: Dict returned by ``CDISCClient.get_codelist``.
            Must contain at least ``conceptId`` and ``terms``.
        package: Optional CT package the codelist was fetched from
            (e.g. ``"sdtmct-2024-12-13"``).  Stored on the codelist
            dict as ``_package`` so the rendered ``_cdisc_url`` can
            include the correct package + date context required by
            the CDISC Library Browser.

    Raises:
        ValueError: If required keys are missing.
    """
    if "conceptId" not in codelist_json:
        raise ValueError("codelist JSON must contain 'conceptId'")
    if package is not None:
        codelist_json = {**codelist_json, "_package": package}
    self._codelists.append(codelist_json)

from_concept_ids classmethod

from_concept_ids(
    client,
    concept_ids,
    *,
    package="sdtmct-2023-12-15",
    adam_package=None,
    include_docs=True
)

Build a generator from an explicit set of NCI concept IDs.

Each codelist comes from the first package that holds it: package (SDTM CT), then adam_package (ADaM CT, for codelists such as DTYPE that only ADaM CT publishes).

Parameters:

Name Type Description Default
client CDISCClient

An authenticated CDISCClient instance.

required
concept_ids set[str]

Set of NCI concept ID strings to download.

required
package str

SDTM CT package version to download from.

'sdtmct-2023-12-15'
adam_package str | None

ADaM CT package asked second; None for SDTM only.

None
include_docs bool

Whether to include definitions in generated output.

True

Returns:

Type Description
CodelistGenerator

A CodelistGenerator populated with the requested codelists.

Raises:

Type Description
CTError

When no pinned package holds a codelist (each ID is named), or on an authentication or network error.

Examples:

Generate codelists for specific concept IDs::

from fleet.ct.api import CDISCClient
from fleet.ct.generator import CodelistGenerator

with CDISCClient() as client:
    gen = CodelistGenerator.from_concept_ids(
        client,
        {"C66731", "C81224"},
        adam_package="adamct-2023-06-30",
    )
    gen.write("codelists.py")
Source code in src/fleet/ct/generator.py
@classmethod
def from_concept_ids(
    cls,
    client: CDISCClient,
    concept_ids: set[str],
    *,
    package: str = "sdtmct-2023-12-15",
    adam_package: str | None = None,
    include_docs: bool = True,
) -> CodelistGenerator:
    """Build a generator from an explicit set of NCI concept IDs.

    Each codelist comes from the first package that holds it: *package*
    (SDTM CT), then *adam_package* (ADaM CT, for codelists such as
    DTYPE that only ADaM CT publishes).

    Args:
        client: An authenticated ``CDISCClient`` instance.
        concept_ids: Set of NCI concept ID strings to download.
        package: SDTM CT package version to download from.
        adam_package: ADaM CT package asked second; ``None`` for SDTM only.
        include_docs: Whether to include definitions in generated output.

    Returns:
        A ``CodelistGenerator`` populated with the requested codelists.

    Raises:
        CTError: When no pinned package holds a codelist (each ID is
            named), or on an authentication or network error.

    Examples:
        Generate codelists for specific concept IDs::

            from fleet.ct.api import CDISCClient
            from fleet.ct.generator import CodelistGenerator

            with CDISCClient() as client:
                gen = CodelistGenerator.from_concept_ids(
                    client,
                    {"C66731", "C81224"},
                    adam_package="adamct-2023-06-30",
                )
                gen.write("codelists.py")
    """
    from fleet.core.exceptions import CTError, CTNotFoundError

    pins = [p for p in (package, adam_package) if p]
    gen = cls(include_docs=include_docs)
    missing: list[str] = []
    for cid in sorted(concept_ids):
        for pin in pins:
            try:
                gen.add_codelist(client.get_codelist(cid, package=pin), package=pin)
                break
            except CTNotFoundError:
                continue
        else:
            missing.append(cid)
    if missing:
        raise CTError(
            f"{len(missing)} codelist(s) are in no pinned CT package "
            f"({', '.join(pins)}): {', '.join(missing)}. Correct the codelist id in "
            "define.yaml, or pin the package that holds it in study_config.yaml "
            "(ct.package, ct.adam_package)."
        )
    return gen

from_sdtm_ig classmethod

from_sdtm_ig(
    client,
    domains,
    *,
    ig_version="3-4",
    package="sdtmct-2023-12-15",
    include_docs=True
)

Build a generator from the SDTM IG — the authoritative source of truth.

Queries the CDISC Library for the specified SDTM IG version, extracts every codelist referenced by variables in the requested domains, and downloads the corresponding CT definitions.

Parameters:

Name Type Description Default
client CDISCClient

An authenticated CDISCClient instance.

required
domains list[str]

List of SDTM domain abbreviations to include (e.g. ["DM", "AE", "VS", "EX"]).

required
ig_version str

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

'3-4'
package str

CT package version to download terms from.

'sdtmct-2023-12-15'
include_docs bool

Whether to include definitions in generated output.

True

Returns:

Type Description
CodelistGenerator

A CodelistGenerator populated with all referenced codelists.

Examples:

Generate codelists for DM and AE from SDTM IG 3.4::

from fleet.ct.api import CDISCClient
from fleet.ct.generator import CodelistGenerator

with CDISCClient() as client:
    gen = CodelistGenerator.from_sdtm_ig(
        client,
        domains=["DM", "AE", "VS", "EX"],
    )
    gen.write("examples/cdiscpilot01/sdtm/codelists.py")
Source code in src/fleet/ct/generator.py
@classmethod
def from_sdtm_ig(
    cls,
    client: CDISCClient,
    domains: list[str],
    *,
    ig_version: str = "3-4",
    package: str = "sdtmct-2023-12-15",
    include_docs: bool = True,
) -> CodelistGenerator:
    """Build a generator from the SDTM IG — the authoritative source of truth.

    Queries the CDISC Library for the specified SDTM IG version,
    extracts every codelist referenced by variables in the requested
    domains, and downloads the corresponding CT definitions.

    Args:
        client: An authenticated ``CDISCClient`` instance.
        domains: List of SDTM domain abbreviations to include
            (e.g. ``["DM", "AE", "VS", "EX"]``).
        ig_version: SDTM IG version (default ``"3-4"``).
        package: CT package version to download terms from.
        include_docs: Whether to include definitions in generated output.

    Returns:
        A ``CodelistGenerator`` populated with all referenced codelists.

    Examples:
        Generate codelists for DM and AE from SDTM IG 3.4::

            from fleet.ct.api import CDISCClient
            from fleet.ct.generator import CodelistGenerator

            with CDISCClient() as client:
                gen = CodelistGenerator.from_sdtm_ig(
                    client,
                    domains=["DM", "AE", "VS", "EX"],
                )
                gen.write("examples/cdiscpilot01/sdtm/codelists.py")
    """
    concept_ids = extract_ig_concept_ids(client, ig_version, domains)
    return cls.from_concept_ids(
        client,
        concept_ids,
        package=package,
        include_docs=include_docs,
    )

render

render()

Render accumulated codelists as a Python module string.

Returns:

Type Description
str

A complete, syntactically valid Python source string.

Source code in src/fleet/ct/generator.py
def render(self) -> str:
    """Render accumulated codelists as a Python module string.

    Returns:
        A complete, syntactically valid Python source string.
    """
    sorted_cls = sorted(self._codelists, key=lambda c: c["conceptId"])

    lines: list[str] = [
        '"""Auto-generated CDISC Controlled Terminology constants.',
        "",
        "Do not edit manually — regenerate with ``fleet.ct.generator``.",
        '"""',
        "",
    ]
    # Marker for the stale checks of fleet.ct.study_codelists; two dates of one
    # product (two SDTM CT packages) get none, so check b reports the mix.
    packages = {cl.get("_package") for cl in sorted_cls}
    products = {str(p).split("-", 1)[0] for p in packages}
    if len(packages) == 1 and None not in packages:
        lines += [f"__ct_package__ = {packages.pop()!r}", "", ""]
    elif None not in packages and len(products) == len(packages) > 1:
        lines += [f"__ct_packages__ = {tuple(sorted(packages))!r}", "", ""]

    # Class definitions
    for cl in sorted_cls:
        lines.extend(self._render_class(cl))
        lines.append("")

    # Human-readable aliases  (e.g.  SEX = C66731)
    aliases: list[tuple[str, str]] = []
    for cl in sorted_cls:
        concept_id = cl["conceptId"]
        class_name = _safe_identifier(concept_id)
        alias = self._alias_for(cl)
        if alias and alias != class_name:
            aliases.append((alias, class_name))

    if aliases:
        lines.append("")
        lines.append("# Human-readable aliases")
        for alias, class_name in sorted(aliases):
            lines.append(f"{alias} = {class_name}")
        lines.append("")

    # __all__
    all_names: list[str] = [_safe_identifier(cl["conceptId"]) for cl in sorted_cls]
    all_names.extend(alias for alias, _ in sorted(aliases))
    all_names.sort()
    all_repr = ", ".join(f'"{n}"' for n in all_names)
    lines.append(f"__all__ = [{all_repr}]")
    lines.append("")

    return "\n".join(lines) + "\n"

write

write(path)

Render and write the module to path.

Parent directories are created if they do not exist.

Parameters:

Name Type Description Default
path str | Path

Destination file path.

required

Returns:

Type Description
Path

Resolved Path of the written file.

Source code in src/fleet/ct/generator.py
def write(self, path: str | Path) -> Path:
    """Render and write the module to *path*.

    Parent directories are created if they do not exist.

    Args:
        path: Destination file path.

    Returns:
        Resolved ``Path`` of the written file.
    """
    dest = Path(path)
    dest.parent.mkdir(parents=True, exist_ok=True)
    dest.write_text(self.render(), encoding="utf-8")
    return dest.resolve()

define_terms

define_terms()

The codelists: entry of define.yaml for each loaded codelist, by concept ID.

Returns:

Type Description
dict[str, dict[str, Any]]

dict[str, dict[str, Any]]: {"name": ..., "items": [{"coded_value": ..., "decode": ...}]}; the decode is the NCI preferred term.

Source code in src/fleet/ct/generator.py
def define_terms(self) -> dict[str, dict[str, Any]]:
    """The ``codelists:`` entry of ``define.yaml`` for each loaded codelist, by concept ID.

    Returns:
        dict[str, dict[str, Any]]: ``{"name": ..., "items": [{"coded_value": ...,
            "decode": ...}]}``; the decode is the NCI preferred term.
    """
    return {
        cl["conceptId"]: {
            "name": cl.get("name") or cl.get("submissionValue") or cl["conceptId"],
            "items": [
                {
                    "coded_value": t["submissionValue"],
                    "decode": t.get("preferredTerm") or t["submissionValue"],
                }
                for t in cl.get("terms", [])
            ],
        }
        for cl in self._codelists
    }

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


Codelist Importer

The import_codelists() function dynamically loads a generated codelists.py from your study workspace, removing the need for sys.path manipulation or package-relative imports.

fleet.ct.import_codelists

import_codelists(path=None, *, module_name='codelists')

Dynamically import a generated codelists.py module.

Resolves the codelist module location using these strategies (in order):

  1. If path is given explicitly, use it directly.
  2. Look for study_config.yaml in the current working directory or in a parent folder (git-style, as the CLI does), and resolve the SDTM metadata path from it. A program in programs/sdtm finds the study at the root.
  3. Fall back to metadata/sdtm/codelists.py relative to CWD.

The module is registered in sys.modules under module_name so that subsequent from codelists import SEX statements work as expected throughout the session.

Parameters:

Name Type Description Default
path str | Path | None

Explicit path to the codelists.py file. When None, auto-discovery is attempted.

None
module_name str

Name to register the module under in sys.modules. Defaults to "codelists".

'codelists'

Returns:

Type Description
ModuleType

The imported codelists module.

Raises:

Type Description
FileNotFoundError

If no codelists.py could be located.

Examples:

Auto-discover from study config::

from fleet.ct import import_codelists

ct = import_codelists()
SEX = ct.SEX

Or register so bare imports work::

from fleet.ct import import_codelists

import_codelists()  # registers as 'codelists' in sys.modules
from codelists import SEX, RACE  # now works anywhere
Source code in src/fleet/ct/__init__.py
def import_codelists(
    path: str | Path | None = None,
    *,
    module_name: str = "codelists",
) -> ModuleType:
    """Dynamically import a generated ``codelists.py`` module.

    Resolves the codelist module location using these strategies (in order):

    1. If *path* is given explicitly, use it directly.
    2. Look for ``study_config.yaml`` in the current working directory or in
       a parent folder (git-style, as the CLI does), and resolve the SDTM
       metadata path from it. A program in ``programs/sdtm`` finds the
       study at the root.
    3. Fall back to ``metadata/sdtm/codelists.py`` relative to CWD.

    The module is registered in ``sys.modules`` under *module_name* so that
    subsequent ``from codelists import SEX`` statements work as expected
    throughout the session.

    Args:
        path: Explicit path to the ``codelists.py`` file.  When ``None``,
            auto-discovery is attempted.
        module_name: Name to register the module under in ``sys.modules``.
            Defaults to ``"codelists"``.

    Returns:
        The imported codelists module.

    Raises:
        FileNotFoundError: If no ``codelists.py`` could be located.

    Examples:
        Auto-discover from study config::

            from fleet.ct import import_codelists

            ct = import_codelists()
            SEX = ct.SEX

        Or register so bare imports work::

            from fleet.ct import import_codelists

            import_codelists()  # registers as 'codelists' in sys.modules
            from codelists import SEX, RACE  # now works anywhere
    """
    resolved = _resolve_codelists_path(path)
    if not resolved.is_file():
        raise FileNotFoundError(
            f"Codelists module not found at: {resolved}\n"
            "Run `fleet init ct` to generate it, or pass an explicit path."
        )

    spec = importlib.util.spec_from_file_location(module_name, resolved)
    if spec is None or spec.loader is None:
        raise ImportError(f"Cannot create module spec for: {resolved}")

    module = importlib.util.module_from_spec(spec)
    sys.modules[module_name] = module
    spec.loader.exec_module(module)
    return module

options: show_root_heading: true heading_level: 3


CT Validator

The singleton CTValidator provides runtime validation of values against loaded codelists.

How CT validation works

Validation fires at pipeline-build time — when you call .assign(ct=...) in Python, not when you call .to_frame(). The check happens during the method call itself, before any data is processed.

The validator is opt-in via initialization. Fleet ships a module-level singleton that starts empty. You must load CT data into it before using ct= parameters. If the singleton has no data loaded, validation is silently skipped and the value is assigned as-is — no error, no warning.

Failures warn, they do not block. If a value is not a valid CDISC submission term, a Python UserWarning is emitted via warnings.warn(). The pipeline continues and the value is still written to the output. This design keeps pipelines runnable during development even before CT packages are fully loaded.

Step-by-step — enabling CT validation

import warnings
from fleet import load_controlled_terminology, get_validator

# 1. Load the CT package once, at script/session start.
#    The file is a YAML or CSV produced by `fleet init ct` or `fleet add-ct`.
load_controlled_terminology("examples/cdiscpilot01/sdtm/ct_package.yaml")

# 2. Import the generated codelist classes.
from fleet.ct import import_codelists

ct = import_codelists()
AGEU = ct.AGEU
SEX = ct.SEX

# 3. Build your pipeline — validation fires here on each verb call.
import warnings

with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    dm = (
        raw_df.sdtm.assign("AGEU", value="YEARS", ct=AGEU)  # OK — valid term
        .assign("AGEU", value="YRS", ct=AGEU)  # Warns immediately
        .to_frame()
    )

# Any invalid values produce a warning at the .assign(ct=...) call site,
# not when .to_frame() runs.
for w in caught:
    print(w.message)
# UserWarning: Value 'YRS' not in codelist 'C66781'. Valid values: DAYS, HOURS, MINUTES, MONTHS, WEEKS, YEARS

Inspecting the validator state

from fleet import get_validator

v = get_validator()
print(v.get_cache_info())
# {'codelists_loaded': ['C66781', 'C66731', ...], 'aliases': {'AGEU': 'C66781', ...},
#  'ct_path': 'specs/.../ct_package.yaml', 'initialized': True}

# Check all valid terms for a codelist
print(v.get_valid_values("C66781"))  # ['DAYS', 'HOURS', 'MINUTES', 'MONTHS', 'WEEKS', 'YEARS']

ADaM namespaces

ADaM pipelines typically skip build-time CT validation (assign without ct=) — ADaM CT compliance is validated post-hoc via the CDISC Rules Engine rather than inline. Passing ct= still works on any namespace since assign is shared.


fleet.ct.CTValidator

Validator for CDISC Controlled Terminology.

Provides caching, lazy loading, and validation of SDTM/ADaM values against CDISC controlled terminology codelists. Aliases are resolved at load time: registering {"SEX": "C66731"} rekeys a cache entry loaded under SEX to its NCI concept ID, so every lookup path (assign-family verbs, DatasetChecker, direct API) reaches the same codelist by OID (C66731) or registered name (SEX) interchangeably — see :meth:_resolve for the resolution order.

Usage

from fleet import get_validator validator = get_validator() validator.load_ct_file("ct/cdisc_ct.yaml", aliases={"SEX": "C66731"}) validator.validate_value("SEX", "M") (True, "Value 'M' is valid for codelist 'C66731'")

Source code in src/fleet/ct/validator.py
class CTValidator:
    """Validator for CDISC Controlled Terminology.

    Provides caching, lazy loading, and validation of SDTM/ADaM values
    against CDISC controlled terminology codelists.  Aliases are
    resolved **at load time**: registering ``{"SEX": "C66731"}`` rekeys
    a cache entry loaded under ``SEX`` to its NCI concept ID, so every
    lookup path (assign-family verbs, ``DatasetChecker``, direct API)
    reaches the same codelist by OID (``C66731``) or registered name
    (``SEX``) interchangeably — see :meth:`_resolve` for the resolution
    order.

    Usage:
        >>> from fleet import get_validator
        >>> validator = get_validator()
        >>> validator.load_ct_file("ct/cdisc_ct.yaml", aliases={"SEX": "C66731"})
        >>> validator.validate_value("SEX", "M")
        (True, "Value 'M' is valid for codelist 'C66731'")
    """

    def __init__(self) -> None:
        self._lock = Lock()
        self._ct_cache: dict[str, dict[str, str]] = {}
        self._codelist_aliases: dict[str, str] = {}
        self._ct_path: Path | None = None
        self._initialized: bool = False

    @classmethod
    def get_instance(cls) -> CTValidator:
        """Return the module-level singleton. Kept for backward compatibility."""
        return _validator

    def load_ct_file(
        self,
        ct_path: Path | str,
        aliases: dict[str, str] | None = None,
    ) -> None:
        """Load all codelists from a YAML or CSV file into the cache.

        Args:
            ct_path: Path or URL to the CT file (.yaml, .yml, .csv).
            aliases: Optional mapping of human-readable names to codelist codes,
                     e.g., {"SEX": "C66731", "RACE": "C74457"}.

        Raises:
            CTError: If the file cannot be loaded.
        """
        with self._lock:
            try:
                logger.info("Loading CT file from: %s", ct_path)
                self._ct_cache = load_controlled_terminology(ct_path)
                self._ct_path = Path(ct_path) if isinstance(ct_path, str) else ct_path
                self._initialized = True
                if aliases:
                    self._codelist_aliases.update(aliases)
                for alias, canonical in self._codelist_aliases.items():
                    self._normalise_alias(alias, canonical)
                logger.info("Loaded %d codelists from %s", len(self._ct_cache), ct_path)
            except CTError:
                raise

    def load_codelist(
        self,
        ct_path: Path | str,
        codelist_name: str,
        alias: str | None = None,
    ) -> None:
        """Lazy-load a single codelist from a file (skips if already cached).

        Args:
            ct_path: Path or URL to the CT file.
            codelist_name: Name or NCI code of codelist to load.
            alias: Optional human-readable name to register for this codelist.
        """
        with self._lock:
            if codelist_name in self._ct_cache:
                logger.debug("Codelist %s already cached", codelist_name)
                return
            try:
                data = load_controlled_terminology(ct_path, codelist_name)
                self._ct_cache.update(data)
                if alias:
                    self._codelist_aliases[alias] = codelist_name
                    self._normalise_alias(alias, codelist_name)
                logger.info("Lazy-loaded codelist: %s", codelist_name)
            except CTError as e:
                logger.warning(
                    "Could not load codelist '%s': %s. Validation will pass by default.",
                    codelist_name,
                    e,
                )

    def register_alias(self, alias: str, codelist_name: str) -> None:
        """Register a human-readable alias for a codelist code.

        Resolves immediately: when the cache was loaded keyed by the
        alias (e.g. a CT file using ``SEX:`` as the top-level key), the
        entry is rekeyed to the canonical concept ID so both spellings
        hit the same codelist.

        Args:
            alias: Human-readable name, e.g., "SEX".
            codelist_name: NCI codelist code, e.g., "C66731".
        """
        with self._lock:
            self._codelist_aliases[alias] = codelist_name
            self._normalise_alias(alias, codelist_name)

    def _normalise_alias(self, alias: str, canonical: str) -> None:
        """Rekey a cache entry stored under *alias* to *canonical*.

        Callers must hold ``self._lock``.  No-op when the canonical key
        already exists (the alias mapping alone then suffices).
        """
        if alias in self._ct_cache and canonical not in self._ct_cache:
            self._ct_cache[canonical] = self._ct_cache.pop(alias)

    def _resolve(self, codelist_name: str) -> str:
        """Resolve a codelist reference to its cache key.

        Resolution order (documented contract for both the verb path
        and the define/checker path):

        1. **Exact cache key** — the name as stored by the loaded CT
           file (post load-time normalisation this is the concept ID
           whenever an alias declared one).
        2. **Registered alias** — ``SEX`` → ``C66731`` via
           :meth:`register_alias` / the ``aliases=`` load parameter.
        3. **Reverse alias** — the name is the canonical target of a
           registered alias whose cache entry was never rekeyed
           (defensive; load-time normalisation makes this rare).

        Unresolvable names are returned unchanged so callers report the
        original spelling.
        """
        if codelist_name in self._ct_cache:
            return codelist_name
        canonical = self._codelist_aliases.get(codelist_name)
        if canonical is not None and canonical in self._ct_cache:
            return canonical
        for alias, target in self._codelist_aliases.items():
            if target == codelist_name and alias in self._ct_cache:
                return alias
        return codelist_name

    def validate_value(
        self,
        codelist_name: str,
        value: str | None,
        allow_null: bool = False,
    ) -> tuple[bool, str]:
        """Validate a single value against a codelist.

        Args:
            codelist_name: Codelist name or alias (e.g., "SEX" or "C66731").
            value: The value to validate (None is handled by allow_null).
            allow_null: Whether None is considered valid.

        Returns:
            Tuple (is_valid, message).
        """
        if value is None:
            if allow_null:
                return (True, f"Null value allowed for codelist '{codelist_name}'")
            return (False, f"Null value not allowed for codelist '{codelist_name}'")

        actual_cl = self._resolve(codelist_name)

        if actual_cl not in self._ct_cache:
            logger.warning(
                "Codelist '%s' not loaded — validation skipped for value '%s'",
                actual_cl,
                value,
            )
            return (True, f"Codelist '{actual_cl}' not loaded - validation skipped")

        codelist = self._ct_cache[actual_cl]
        if value in codelist:
            return (True, f"Value '{value}' is valid for codelist '{actual_cl}'")

        valid_str = ", ".join(sorted(codelist.keys()))
        return (
            False,
            f"Value '{value}' not in codelist '{actual_cl}'. Valid values: {valid_str}",
        )

    def has_codelist(self, codelist_name: str) -> bool:
        """Return True when a codelist (or alias) is loaded in the cache.

        Args:
            codelist_name: Codelist name, alias, or NCI concept ID.

        Returns:
            True if the codelist is available for validation.
        """
        actual_cl = self._resolve(codelist_name)
        return actual_cl in self._ct_cache

    def get_valid_values(self, codelist_name: str) -> list[str]:
        """Return all valid codes for a codelist.

        Args:
            codelist_name: Codelist name or alias.

        Returns:
            Sorted list of valid code strings, empty if codelist not loaded.
        """
        actual_cl = self._resolve(codelist_name)
        codelist = self._ct_cache.get(actual_cl, {})
        return sorted(codelist.keys())

    def get_cache_info(self) -> dict[str, object]:
        """Return diagnostic information about the current cache state."""
        return {
            "codelists_loaded": list(self._ct_cache.keys()),
            "aliases": dict(self._codelist_aliases),
            "ct_path": str(self._ct_path) if self._ct_path else None,
            "initialized": self._initialized,
        }

    def apply_ct_mapping(self, codelist_name: str, value: str | None) -> str | None:
        """Map an SDTM code to its decoded CT value (e.g., "M" → "Male").

        Returns the original value if the codelist is not loaded or value not found.
        """
        if value is None:
            return None
        actual_cl = self._resolve(codelist_name)
        codelist = self._ct_cache.get(actual_cl, {})
        return codelist.get(value, value)

    def get_decode_map(self, codelist_name: str) -> dict[str, str]:
        """Return a code-to-preferred-term mapping for a codelist.

        Each key is the submission value (e.g. ``"M"``) and the value is
        the preferred term / decode (e.g. ``"Male"``).  Returns an empty
        dict if the codelist is not loaded.

        Args:
            codelist_name: Codelist name, alias, or NCI concept ID.

        Returns:
            Dictionary mapping coded values to their preferred terms.
        """
        actual_cl = self._resolve(codelist_name)
        codelist = self._ct_cache.get(actual_cl, {})
        return {
            coded: info.get("preferred_term", coded) if isinstance(info, dict) else coded
            for coded, info in codelist.items()
        }

get_instance classmethod

get_instance()

Return the module-level singleton. Kept for backward compatibility.

Source code in src/fleet/ct/validator.py
@classmethod
def get_instance(cls) -> CTValidator:
    """Return the module-level singleton. Kept for backward compatibility."""
    return _validator

load_ct_file

load_ct_file(ct_path, aliases=None)

Load all codelists from a YAML or CSV file into the cache.

Parameters:

Name Type Description Default
ct_path Path | str

Path or URL to the CT file (.yaml, .yml, .csv).

required
aliases dict[str, str] | None

Optional mapping of human-readable names to codelist codes, e.g., {"SEX": "C66731", "RACE": "C74457"}.

None

Raises:

Type Description
CTError

If the file cannot be loaded.

Source code in src/fleet/ct/validator.py
def load_ct_file(
    self,
    ct_path: Path | str,
    aliases: dict[str, str] | None = None,
) -> None:
    """Load all codelists from a YAML or CSV file into the cache.

    Args:
        ct_path: Path or URL to the CT file (.yaml, .yml, .csv).
        aliases: Optional mapping of human-readable names to codelist codes,
                 e.g., {"SEX": "C66731", "RACE": "C74457"}.

    Raises:
        CTError: If the file cannot be loaded.
    """
    with self._lock:
        try:
            logger.info("Loading CT file from: %s", ct_path)
            self._ct_cache = load_controlled_terminology(ct_path)
            self._ct_path = Path(ct_path) if isinstance(ct_path, str) else ct_path
            self._initialized = True
            if aliases:
                self._codelist_aliases.update(aliases)
            for alias, canonical in self._codelist_aliases.items():
                self._normalise_alias(alias, canonical)
            logger.info("Loaded %d codelists from %s", len(self._ct_cache), ct_path)
        except CTError:
            raise

load_codelist

load_codelist(ct_path, codelist_name, alias=None)

Lazy-load a single codelist from a file (skips if already cached).

Parameters:

Name Type Description Default
ct_path Path | str

Path or URL to the CT file.

required
codelist_name str

Name or NCI code of codelist to load.

required
alias str | None

Optional human-readable name to register for this codelist.

None
Source code in src/fleet/ct/validator.py
def load_codelist(
    self,
    ct_path: Path | str,
    codelist_name: str,
    alias: str | None = None,
) -> None:
    """Lazy-load a single codelist from a file (skips if already cached).

    Args:
        ct_path: Path or URL to the CT file.
        codelist_name: Name or NCI code of codelist to load.
        alias: Optional human-readable name to register for this codelist.
    """
    with self._lock:
        if codelist_name in self._ct_cache:
            logger.debug("Codelist %s already cached", codelist_name)
            return
        try:
            data = load_controlled_terminology(ct_path, codelist_name)
            self._ct_cache.update(data)
            if alias:
                self._codelist_aliases[alias] = codelist_name
                self._normalise_alias(alias, codelist_name)
            logger.info("Lazy-loaded codelist: %s", codelist_name)
        except CTError as e:
            logger.warning(
                "Could not load codelist '%s': %s. Validation will pass by default.",
                codelist_name,
                e,
            )

register_alias

register_alias(alias, codelist_name)

Register a human-readable alias for a codelist code.

Resolves immediately: when the cache was loaded keyed by the alias (e.g. a CT file using SEX: as the top-level key), the entry is rekeyed to the canonical concept ID so both spellings hit the same codelist.

Parameters:

Name Type Description Default
alias str

Human-readable name, e.g., "SEX".

required
codelist_name str

NCI codelist code, e.g., "C66731".

required
Source code in src/fleet/ct/validator.py
def register_alias(self, alias: str, codelist_name: str) -> None:
    """Register a human-readable alias for a codelist code.

    Resolves immediately: when the cache was loaded keyed by the
    alias (e.g. a CT file using ``SEX:`` as the top-level key), the
    entry is rekeyed to the canonical concept ID so both spellings
    hit the same codelist.

    Args:
        alias: Human-readable name, e.g., "SEX".
        codelist_name: NCI codelist code, e.g., "C66731".
    """
    with self._lock:
        self._codelist_aliases[alias] = codelist_name
        self._normalise_alias(alias, codelist_name)

validate_value

validate_value(codelist_name, value, allow_null=False)

Validate a single value against a codelist.

Parameters:

Name Type Description Default
codelist_name str

Codelist name or alias (e.g., "SEX" or "C66731").

required
value str | None

The value to validate (None is handled by allow_null).

required
allow_null bool

Whether None is considered valid.

False

Returns:

Type Description
tuple[bool, str]

Tuple (is_valid, message).

Source code in src/fleet/ct/validator.py
def validate_value(
    self,
    codelist_name: str,
    value: str | None,
    allow_null: bool = False,
) -> tuple[bool, str]:
    """Validate a single value against a codelist.

    Args:
        codelist_name: Codelist name or alias (e.g., "SEX" or "C66731").
        value: The value to validate (None is handled by allow_null).
        allow_null: Whether None is considered valid.

    Returns:
        Tuple (is_valid, message).
    """
    if value is None:
        if allow_null:
            return (True, f"Null value allowed for codelist '{codelist_name}'")
        return (False, f"Null value not allowed for codelist '{codelist_name}'")

    actual_cl = self._resolve(codelist_name)

    if actual_cl not in self._ct_cache:
        logger.warning(
            "Codelist '%s' not loaded — validation skipped for value '%s'",
            actual_cl,
            value,
        )
        return (True, f"Codelist '{actual_cl}' not loaded - validation skipped")

    codelist = self._ct_cache[actual_cl]
    if value in codelist:
        return (True, f"Value '{value}' is valid for codelist '{actual_cl}'")

    valid_str = ", ".join(sorted(codelist.keys()))
    return (
        False,
        f"Value '{value}' not in codelist '{actual_cl}'. Valid values: {valid_str}",
    )

has_codelist

has_codelist(codelist_name)

Return True when a codelist (or alias) is loaded in the cache.

Parameters:

Name Type Description Default
codelist_name str

Codelist name, alias, or NCI concept ID.

required

Returns:

Type Description
bool

True if the codelist is available for validation.

Source code in src/fleet/ct/validator.py
def has_codelist(self, codelist_name: str) -> bool:
    """Return True when a codelist (or alias) is loaded in the cache.

    Args:
        codelist_name: Codelist name, alias, or NCI concept ID.

    Returns:
        True if the codelist is available for validation.
    """
    actual_cl = self._resolve(codelist_name)
    return actual_cl in self._ct_cache

get_valid_values

get_valid_values(codelist_name)

Return all valid codes for a codelist.

Parameters:

Name Type Description Default
codelist_name str

Codelist name or alias.

required

Returns:

Type Description
list[str]

Sorted list of valid code strings, empty if codelist not loaded.

Source code in src/fleet/ct/validator.py
def get_valid_values(self, codelist_name: str) -> list[str]:
    """Return all valid codes for a codelist.

    Args:
        codelist_name: Codelist name or alias.

    Returns:
        Sorted list of valid code strings, empty if codelist not loaded.
    """
    actual_cl = self._resolve(codelist_name)
    codelist = self._ct_cache.get(actual_cl, {})
    return sorted(codelist.keys())

get_cache_info

get_cache_info()

Return diagnostic information about the current cache state.

Source code in src/fleet/ct/validator.py
def get_cache_info(self) -> dict[str, object]:
    """Return diagnostic information about the current cache state."""
    return {
        "codelists_loaded": list(self._ct_cache.keys()),
        "aliases": dict(self._codelist_aliases),
        "ct_path": str(self._ct_path) if self._ct_path else None,
        "initialized": self._initialized,
    }

apply_ct_mapping

apply_ct_mapping(codelist_name, value)

Map an SDTM code to its decoded CT value (e.g., "M" → "Male").

Returns the original value if the codelist is not loaded or value not found.

Source code in src/fleet/ct/validator.py
def apply_ct_mapping(self, codelist_name: str, value: str | None) -> str | None:
    """Map an SDTM code to its decoded CT value (e.g., "M" → "Male").

    Returns the original value if the codelist is not loaded or value not found.
    """
    if value is None:
        return None
    actual_cl = self._resolve(codelist_name)
    codelist = self._ct_cache.get(actual_cl, {})
    return codelist.get(value, value)

get_decode_map

get_decode_map(codelist_name)

Return a code-to-preferred-term mapping for a codelist.

Each key is the submission value (e.g. "M") and the value is the preferred term / decode (e.g. "Male"). Returns an empty dict if the codelist is not loaded.

Parameters:

Name Type Description Default
codelist_name str

Codelist name, alias, or NCI concept ID.

required

Returns:

Type Description
dict[str, str]

Dictionary mapping coded values to their preferred terms.

Source code in src/fleet/ct/validator.py
def get_decode_map(self, codelist_name: str) -> dict[str, str]:
    """Return a code-to-preferred-term mapping for a codelist.

    Each key is the submission value (e.g. ``"M"``) and the value is
    the preferred term / decode (e.g. ``"Male"``).  Returns an empty
    dict if the codelist is not loaded.

    Args:
        codelist_name: Codelist name, alias, or NCI concept ID.

    Returns:
        Dictionary mapping coded values to their preferred terms.
    """
    actual_cl = self._resolve(codelist_name)
    codelist = self._ct_cache.get(actual_cl, {})
    return {
        coded: info.get("preferred_term", coded) if isinstance(info, dict) else coded
        for coded, info in codelist.items()
    }

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

load_controlled_terminology

fleet.ct.load_controlled_terminology

load_controlled_terminology(ct_path, codelist_name=None)

Load CDISC controlled terminology from a YAML or CSV file (or URL).

Parameters:

Name Type Description Default
ct_path Path | str

Path or URL to CT file. Supported formats: .yaml, .yml, .csv.

required
codelist_name str | None

If given, only load this specific codelist.

None

Returns:

Type Description
dict[str, dict[str, str]]

Nested dict mapping codelist_name -> {code: decoded_value}.

Raises:

Type Description
CTError

If the file cannot be found, read, or is in an unsupported format.

Source code in src/fleet/ct/loader.py
def load_controlled_terminology(
    ct_path: Path | str,
    codelist_name: str | None = None,
) -> dict[str, dict[str, str]]:
    """Load CDISC controlled terminology from a YAML or CSV file (or URL).

    Args:
        ct_path: Path or URL to CT file. Supported formats: .yaml, .yml, .csv.
        codelist_name: If given, only load this specific codelist.

    Returns:
        Nested dict mapping codelist_name -> {code: decoded_value}.

    Raises:
        CTError: If the file cannot be found, read, or is in an unsupported format.
    """
    if isinstance(ct_path, str):
        if ct_path.startswith("http"):
            ct_path = _download_ct(ct_path)
        else:
            ct_path = Path(ct_path)

    if not ct_path.exists():
        raise CTError(f"CT file not found: {ct_path}")

    suffix = ct_path.suffix.lower()
    if suffix in (".yaml", ".yml"):
        return _load_ct_yaml(ct_path, codelist_name)
    elif suffix == ".csv":
        return _load_ct_csv(ct_path, codelist_name)
    else:
        raise CTError(f"Unsupported CT file type: {suffix}. Use .yaml or .csv")

options: show_root_heading: true heading_level: 3

get_validator

fleet.ct.get_validator

get_validator()

Return the module-level singleton CTValidator.

Source code in src/fleet/ct/validator.py
def get_validator() -> CTValidator:
    """Return the module-level singleton CTValidator."""
    return _validator

options: show_root_heading: true heading_level: 3