Controlled Terminology¶
Fleet provides three layers for working with CDISC Controlled Terminology:
- CDISC Library API client — download CT directly from the authoritative source.
- Code generator — turn API responses into typed Python constants with IDE auto-completion.
- 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 / |
CDISCClientConfig()
|
Examples:
Fetch the SEX codelist::
client = CDISCClient()
terms = client.get_codelist("C66731")
Source code in src/fleet/ct/api.py
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 | |
get_packages
¶
List available CT packages for a product.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
product
|
str
|
Product key recognised by the CDISC Library
(e.g. |
'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
get_codelist
¶
Download a single codelist by NCI concept ID.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
concept_id
|
str
|
NCI concept identifier (e.g. |
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]
|
|
Raises:
| Type | Description |
|---|---|
CTError
|
On network, authentication, or 404 errors. |
Source code in src/fleet/ct/api.py
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
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.
Recommended workflow¶
# 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:
__all__for clean wildcard imports:
__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 withct.packageandct.adam_packageinstudy_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:
study_config.yamlin CWD or the nearest parent folder (git-style, as the CLI does) → readspaths.metadata_sdtm→ appends/codelists.py- 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:
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
|
cdisc_url_template
|
str
|
URL template used to build the
|
'https://library.cdisc.org/browser/#/mdr/ct/{date}/packages/{package}/codelists/{concept_id}'
|
Source code in src/fleet/ct/generator.py
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 | |
add_codelist
¶
Register a raw CDISC Library codelist JSON response.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
codelist_json
|
dict[str, Any]
|
Dict returned by |
required |
package
|
str | None
|
Optional CT package the codelist was fetched from
(e.g. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If required keys are missing. |
Source code in src/fleet/ct/generator.py
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 |
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
|
include_docs
|
bool
|
Whether to include definitions in generated output. |
True
|
Returns:
| Type | Description |
|---|---|
CodelistGenerator
|
A |
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
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 |
required |
domains
|
list[str]
|
List of SDTM domain abbreviations to include
(e.g. |
required |
ig_version
|
str
|
SDTM IG version (default |
'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 |
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
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
write
¶
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 |
Source code in src/fleet/ct/generator.py
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]]: |
Source code in src/fleet/ct/generator.py
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
¶
Dynamically import a generated codelists.py module.
Resolves the codelist module location using these strategies (in order):
- If path is given explicitly, use it directly.
- Look for
study_config.yamlin 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 inprograms/sdtmfinds the study at the root. - Fall back to
metadata/sdtm/codelists.pyrelative 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 |
None
|
module_name
|
str
|
Name to register the module under in |
'codelists'
|
Returns:
| Type | Description |
|---|---|
ModuleType
|
The imported codelists module. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If no |
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
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
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 | |
get_instance
classmethod
¶
load_ct_file
¶
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
load_codelist
¶
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
register_alias
¶
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
validate_value
¶
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
has_codelist
¶
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
get_valid_values
¶
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
get_cache_info
¶
Return diagnostic information about the current cache state.
Source code in src/fleet/ct/validator.py
apply_ct_mapping
¶
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
get_decode_map
¶
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
options: show_root_heading: true heading_level: 3 filters: ["!^_"]
load_controlled_terminology¶
fleet.ct.load_controlled_terminology
¶
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
options: show_root_heading: true heading_level: 3
get_validator¶
fleet.ct.get_validator
¶
options: show_root_heading: true heading_level: 3