Skip to content

Utilities API Reference

Utility classes and helpers.

Code Systems

CodeSystemRegistry

Central registry for code systems with metadata.

This class provides utilities for working with healthcare code systems, including OID lookup, reverse lookup, format validation, and metadata retrieval.

Functions

get_oid(name) staticmethod

Get OID for code system name.

Parameters:

Name Type Description Default
name str

Code system name (e.g., "LOINC", "SNOMED")

required

Returns:

Type Description
Optional[str]

OID string if found, None otherwise

Example

CodeSystemRegistry.get_oid("LOINC") '2.16.840.1.113883.6.1'

get_name(oid) staticmethod

Get code system name from OID.

Parameters:

Name Type Description Default
oid str

OID string (e.g., "2.16.840.1.113883.6.1")

required

Returns:

Type Description
Optional[str]

Code system name if found, None otherwise

Example

CodeSystemRegistry.get_name("2.16.840.1.113883.6.1") 'LOINC'

validate_code_format(code, system) staticmethod

Validate code format for specific system.

Parameters:

Name Type Description Default
code str

Code value to validate

required
system str

Code system name

required

Returns:

Type Description
bool

True if code matches expected format, False otherwise

bool

Returns True if no format pattern is defined for the system

Example

CodeSystemRegistry.validate_code_format("12345-6", "LOINC") True CodeSystemRegistry.validate_code_format("invalid", "LOINC") False

get_system_info(system) staticmethod

Get metadata about a code system.

Parameters:

Name Type Description Default
system str

Code system name

required

Returns:

Type Description
Optional[dict]

Dictionary with system metadata (oid, name, description, url, format_pattern)

Optional[dict]

Returns None if system not found

Example

info = CodeSystemRegistry.get_system_info("LOINC") info["description"] 'International standard for identifying medical laboratory observations'

list_systems() staticmethod

Get list of all supported code system names.

Returns:

Type Description
list[str]

List of code system names

Example

systems = CodeSystemRegistry.list_systems() "LOINC" in systems True

get_systems_by_category() staticmethod

Get code systems grouped by category.

Returns:

Type Description
dict[str, list[str]]

Dictionary mapping category names to lists of system names

Example

categories = CodeSystemRegistry.get_systems_by_category() "LOINC" in categories["Clinical terminology systems"] True

Value Sets

ValueSetRegistry

Central registry for C-CDA value sets with validation and lookup capabilities.

This class provides utilities for working with healthcare value sets, including validation, display name lookup, and value set management. Value sets define the allowed codes for specific clinical concepts.

Source code in ccdakit/utils/value_sets.py
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
class ValueSetRegistry:
    """
    Central registry for C-CDA value sets with validation and lookup capabilities.

    This class provides utilities for working with healthcare value sets,
    including validation, display name lookup, and value set management.
    Value sets define the allowed codes for specific clinical concepts.
    """

    # Common C-CDA value sets with codes and display names
    # Based on HL7 C-CDA R2.1 specification and companion guides

    # Problem/Condition Status - ActStatus value set (2.16.840.1.113883.1.11.15933)
    PROBLEM_STATUS = {
        "55561003": {"display": "Active", "system": "SNOMED"},
        "73425007": {"display": "Inactive", "system": "SNOMED"},
        "413322009": {"display": "Resolved", "system": "SNOMED"},
    }

    # Allergy Status - AllergyIntoleranceStatusValue Set (2.16.840.1.113883.3.88.12.3221.6.2)
    ALLERGY_STATUS = {
        "55561003": {"display": "Active", "system": "SNOMED"},
        "73425007": {"display": "Resolved", "system": "SNOMED"},
        "inactive": {"display": "Inactive", "system": "ActStatus"},
    }

    # Medication Status - Medication Clinical Drug (2.16.840.1.113883.3.88.12.80.20)
    MEDICATION_STATUS = {
        "55561003": {"display": "Active", "system": "SNOMED"},
        "completed": {"display": "Completed", "system": "ActStatus"},
        "aborted": {"display": "Discontinued", "system": "ActStatus"},
        "suspended": {"display": "On hold", "system": "ActStatus"},
    }

    # Observation Interpretation - ObservationInterpretation (2.16.840.1.113883.5.83)
    OBSERVATION_INTERPRETATION = {
        "N": {"display": "Normal", "system": "ObservationInterpretation"},
        "L": {"display": "Low", "system": "ObservationInterpretation"},
        "H": {"display": "High", "system": "ObservationInterpretation"},
        "LL": {"display": "Critical low", "system": "ObservationInterpretation"},
        "HH": {"display": "Critical high", "system": "ObservationInterpretation"},
        "A": {"display": "Abnormal", "system": "ObservationInterpretation"},
        "<": {"display": "Off scale low", "system": "ObservationInterpretation"},
        ">": {"display": "Off scale high", "system": "ObservationInterpretation"},
    }

    # Problem Type - Problem Type Value Set (2.16.840.1.113883.3.88.12.3221.7.2)
    PROBLEM_TYPE = {
        "55607006": {"display": "Problem", "system": "SNOMED"},
        "404684003": {"display": "Clinical finding", "system": "SNOMED"},
        "409586006": {"display": "Complaint", "system": "SNOMED"},
        "282291009": {"display": "Diagnosis", "system": "SNOMED"},
        "64572001": {"display": "Condition", "system": "SNOMED"},
    }

    # Allergy Severity - AllergyIntoleranceSeverity (2.16.840.1.113883.3.88.12.3221.6.8)
    ALLERGY_SEVERITY = {
        "255604002": {"display": "Mild", "system": "SNOMED"},
        "6736007": {"display": "Moderate", "system": "SNOMED"},
        "24484000": {"display": "Severe", "system": "SNOMED"},
        "399166001": {"display": "Fatal", "system": "SNOMED"},
    }

    # Allergy Reaction Type - AllergyIntoleranceType (2.16.840.1.113883.3.88.12.3221.6.2)
    ALLERGY_REACTION_TYPE = {
        "419511003": {"display": "Propensity to adverse reactions to drug", "system": "SNOMED"},
        "418038007": {
            "display": "Propensity to adverse reactions to substance",
            "system": "SNOMED",
        },
        "419199007": {"display": "Allergy to substance", "system": "SNOMED"},
        "418471000": {"display": "Propensity to adverse reactions to food", "system": "SNOMED"},
    }

    # Smoking Status - Smoking Status Value Set (2.16.840.1.113883.11.20.9.38)
    SMOKING_STATUS = {
        "449868002": {"display": "Current every day smoker", "system": "SNOMED"},
        "428041000124106": {"display": "Current some day smoker", "system": "SNOMED"},
        "8517006": {"display": "Former smoker", "system": "SNOMED"},
        "266919005": {"display": "Never smoker", "system": "SNOMED"},
        "77176002": {"display": "Smoker, current status unknown", "system": "SNOMED"},
        "266927001": {"display": "Unknown if ever smoked", "system": "SNOMED"},
        "428071000124103": {"display": "Current Heavy tobacco smoker", "system": "SNOMED"},
        "428061000124105": {"display": "Current Light tobacco smoker", "system": "SNOMED"},
    }

    # Encounter Type - Encounter Type Value Set (2.16.840.1.113883.3.88.12.80.32)
    ENCOUNTER_TYPE = {
        "AMB": {"display": "Ambulatory", "system": "ActCode"},
        "EMER": {"display": "Emergency", "system": "ActCode"},
        "FLD": {"display": "Field", "system": "ActCode"},
        "HH": {"display": "Home health", "system": "ActCode"},
        "IMP": {"display": "Inpatient encounter", "system": "ActCode"},
        "ACUTE": {"display": "Inpatient acute", "system": "ActCode"},
        "NONAC": {"display": "Inpatient non-acute", "system": "ActCode"},
        "OBSENC": {"display": "Observation encounter", "system": "ActCode"},
        "PRENC": {"display": "Pre-admission", "system": "ActCode"},
        "SS": {"display": "Short stay", "system": "ActCode"},
        "VR": {"display": "Virtual", "system": "ActCode"},
    }

    # Lab Result Status - ResultStatus (2.16.840.1.113883.11.20.9.39)
    LAB_RESULT_STATUS = {
        "completed": {"display": "Completed", "system": "ActStatus"},
        "active": {"display": "Active", "system": "ActStatus"},
        "aborted": {"display": "Aborted", "system": "ActStatus"},
        "held": {"display": "Held", "system": "ActStatus"},
    }

    # Procedure Status - ProcedureActStatus (2.16.840.1.113883.11.20.9.22)
    PROCEDURE_STATUS = {
        "completed": {"display": "Completed", "system": "ActStatus"},
        "active": {"display": "Active", "system": "ActStatus"},
        "aborted": {"display": "Aborted", "system": "ActStatus"},
        "held": {"display": "Held", "system": "ActStatus"},
        "new": {"display": "New", "system": "ActStatus"},
        "suspended": {"display": "Suspended", "system": "ActStatus"},
        "cancelled": {"display": "Cancelled", "system": "ActStatus"},
        "obsolete": {"display": "Obsolete", "system": "ActStatus"},
    }

    # Immunization Status - ImmunizationStatus (2.16.840.1.113883.11.20.9.41)
    IMMUNIZATION_STATUS = {
        "completed": {"display": "Completed", "system": "ActStatus"},
        "active": {"display": "Active", "system": "ActStatus"},
        "aborted": {"display": "Aborted", "system": "ActStatus"},
        "held": {"display": "Held", "system": "ActStatus"},
    }

    # Vital Sign Result Type - Vital Sign Result Type (2.16.840.1.113883.3.88.12.80.62)
    VITAL_SIGN_RESULT_TYPE = {
        "8310-5": {"display": "Body temperature", "system": "LOINC"},
        "8867-4": {"display": "Heart rate", "system": "LOINC"},
        "9279-1": {"display": "Respiratory rate", "system": "LOINC"},
        "8480-6": {"display": "Systolic blood pressure", "system": "LOINC"},
        "8462-4": {"display": "Diastolic blood pressure", "system": "LOINC"},
        "8287-5": {"display": "Head circumference", "system": "LOINC"},
        "8302-2": {"display": "Body height", "system": "LOINC"},
        "8306-3": {"display": "Body height (lying)", "system": "LOINC"},
        "29463-7": {"display": "Body weight", "system": "LOINC"},
        "39156-5": {"display": "Body mass index", "system": "LOINC"},
        "2710-2": {"display": "Oxygen saturation", "system": "LOINC"},
    }

    # Administrative Gender - AdministrativeGender (2.16.840.1.113883.5.1)
    ADMINISTRATIVE_GENDER = {
        "M": {"display": "Male", "system": "AdministrativeGender"},
        "F": {"display": "Female", "system": "AdministrativeGender"},
        "UN": {"display": "Undifferentiated", "system": "AdministrativeGender"},
    }

    # Marital Status - MaritalStatus (2.16.840.1.113883.5.2)
    MARITAL_STATUS = {
        "A": {"display": "Annulled", "system": "MaritalStatus"},
        "D": {"display": "Divorced", "system": "MaritalStatus"},
        "I": {"display": "Interlocutory", "system": "MaritalStatus"},
        "L": {"display": "Legally Separated", "system": "MaritalStatus"},
        "M": {"display": "Married", "system": "MaritalStatus"},
        "P": {"display": "Polygamous", "system": "MaritalStatus"},
        "S": {"display": "Never Married", "system": "MaritalStatus"},
        "T": {"display": "Domestic partner", "system": "MaritalStatus"},
        "W": {"display": "Widowed", "system": "MaritalStatus"},
    }

    # Null Flavor - NullFlavor (2.16.840.1.113883.5.1008)
    NULL_FLAVOR = {
        "NI": {"display": "No information", "system": "NullFlavor"},
        "NA": {"display": "Not applicable", "system": "NullFlavor"},
        "UNK": {"display": "Unknown", "system": "NullFlavor"},
        "ASKU": {"display": "Asked but unknown", "system": "NullFlavor"},
        "NAV": {"display": "Temporarily unavailable", "system": "NullFlavor"},
        "NASK": {"display": "Not asked", "system": "NullFlavor"},
        "MSK": {"display": "Masked", "system": "NullFlavor"},
        "OTH": {"display": "Other", "system": "NullFlavor"},
        "NINF": {"display": "Negative infinity", "system": "NullFlavor"},
        "PINF": {"display": "Positive infinity", "system": "NullFlavor"},
    }

    # Route of Administration - RouteOfAdministration (2.16.840.1.113883.5.112)
    ROUTE_OF_ADMINISTRATION = {
        "C38216": {"display": "Auricular (otic)", "system": "NCI"},
        "C38193": {"display": "Buccal", "system": "NCI"},
        "C38633": {"display": "Cutaneous", "system": "NCI"},
        "C38205": {"display": "Dental", "system": "NCI"},
        "C38238": {"display": "Inhalation", "system": "NCI"},
        "C38276": {"display": "Intramuscular injection", "system": "NCI"},
        "C38279": {"display": "Intravenous", "system": "NCI"},
        "C38288": {"display": "Nasal", "system": "NCI"},
        "C38289": {"display": "Nasogastric", "system": "NCI"},
        "C38299": {"display": "Ophthalmic", "system": "NCI"},
        "C38304": {"display": "Oral", "system": "NCI"},
        "C38676": {"display": "Rectal", "system": "NCI"},
        "C38308": {"display": "Subcutaneous", "system": "NCI"},
        "C38300": {"display": "Sublingual", "system": "NCI"},
        "C38305": {"display": "Topical", "system": "NCI"},
        "C38273": {"display": "Transdermal", "system": "NCI"},
    }

    # Discharge Disposition - DischargeDisposition (2.16.840.1.113883.12.112)
    DISCHARGE_DISPOSITION = {
        "01": {"display": "Discharged to home or self care", "system": "DischargeDisposition"},
        "02": {
            "display": "Discharged/transferred to a short-term general hospital",
            "system": "DischargeDisposition",
        },
        "03": {
            "display": "Discharged/transferred to skilled nursing facility",
            "system": "DischargeDisposition",
        },
        "04": {
            "display": "Discharged/transferred to an intermediate care facility",
            "system": "DischargeDisposition",
        },
        "05": {
            "display": "Discharged/transferred to another type of institution",
            "system": "DischargeDisposition",
        },
        "06": {
            "display": "Discharged/transferred to home under care of organized home health service",
            "system": "DischargeDisposition",
        },
        "07": {"display": "Left against medical advice", "system": "DischargeDisposition"},
        "20": {"display": "Expired", "system": "DischargeDisposition"},
        "21": {
            "display": "Discharged/transferred to court/law enforcement",
            "system": "DischargeDisposition",
        },
    }

    # Registry mapping value set names to their definitions
    VALUE_SETS = {
        "PROBLEM_STATUS": {
            "oid": "2.16.840.1.113883.1.11.15933",
            "name": "Problem Status",
            "description": "Status of a problem or condition (active, inactive, resolved)",
            "codes": PROBLEM_STATUS,
        },
        "ALLERGY_STATUS": {
            "oid": "2.16.840.1.113883.3.88.12.3221.6.2",
            "name": "Allergy Status",
            "description": "Status of an allergy or intolerance",
            "codes": ALLERGY_STATUS,
        },
        "MEDICATION_STATUS": {
            "oid": "2.16.840.1.113883.3.88.12.80.20",
            "name": "Medication Status",
            "description": "Status of a medication (active, completed, discontinued)",
            "codes": MEDICATION_STATUS,
        },
        "OBSERVATION_INTERPRETATION": {
            "oid": "2.16.840.1.113883.5.83",
            "name": "Observation Interpretation",
            "description": "Interpretation of an observation result (normal, high, low, critical)",
            "codes": OBSERVATION_INTERPRETATION,
        },
        "PROBLEM_TYPE": {
            "oid": "2.16.840.1.113883.3.88.12.3221.7.2",
            "name": "Problem Type",
            "description": "Type of problem (problem, diagnosis, complaint, etc.)",
            "codes": PROBLEM_TYPE,
        },
        "ALLERGY_SEVERITY": {
            "oid": "2.16.840.1.113883.3.88.12.3221.6.8",
            "name": "Allergy Severity",
            "description": "Severity of an allergic reaction (mild, moderate, severe, fatal)",
            "codes": ALLERGY_SEVERITY,
        },
        "ALLERGY_REACTION_TYPE": {
            "oid": "2.16.840.1.113883.3.88.12.3221.6.2",
            "name": "Allergy Reaction Type",
            "description": "Type of allergic reaction or intolerance",
            "codes": ALLERGY_REACTION_TYPE,
        },
        "SMOKING_STATUS": {
            "oid": "2.16.840.1.113883.11.20.9.38",
            "name": "Smoking Status",
            "description": "Patient's smoking status",
            "codes": SMOKING_STATUS,
        },
        "ENCOUNTER_TYPE": {
            "oid": "2.16.840.1.113883.3.88.12.80.32",
            "name": "Encounter Type",
            "description": "Type of healthcare encounter",
            "codes": ENCOUNTER_TYPE,
        },
        "LAB_RESULT_STATUS": {
            "oid": "2.16.840.1.113883.11.20.9.39",
            "name": "Lab Result Status",
            "description": "Status of a laboratory result",
            "codes": LAB_RESULT_STATUS,
        },
        "PROCEDURE_STATUS": {
            "oid": "2.16.840.1.113883.11.20.9.22",
            "name": "Procedure Status",
            "description": "Status of a procedure",
            "codes": PROCEDURE_STATUS,
        },
        "IMMUNIZATION_STATUS": {
            "oid": "2.16.840.1.113883.11.20.9.41",
            "name": "Immunization Status",
            "description": "Status of an immunization",
            "codes": IMMUNIZATION_STATUS,
        },
        "VITAL_SIGN_RESULT_TYPE": {
            "oid": "2.16.840.1.113883.3.88.12.80.62",
            "name": "Vital Sign Result Type",
            "description": "Types of vital sign measurements",
            "codes": VITAL_SIGN_RESULT_TYPE,
        },
        "ADMINISTRATIVE_GENDER": {
            "oid": "2.16.840.1.113883.5.1",
            "name": "Administrative Gender",
            "description": "Administrative gender (M, F, UN)",
            "codes": ADMINISTRATIVE_GENDER,
        },
        "MARITAL_STATUS": {
            "oid": "2.16.840.1.113883.5.2",
            "name": "Marital Status",
            "description": "Marital status",
            "codes": MARITAL_STATUS,
        },
        "NULL_FLAVOR": {
            "oid": "2.16.840.1.113883.5.1008",
            "name": "Null Flavor",
            "description": "Reasons for missing information",
            "codes": NULL_FLAVOR,
        },
        "ROUTE_OF_ADMINISTRATION": {
            "oid": "2.16.840.1.113883.5.112",
            "name": "Route of Administration",
            "description": "Routes for medication administration",
            "codes": ROUTE_OF_ADMINISTRATION,
        },
        "DISCHARGE_DISPOSITION": {
            "oid": "2.16.840.1.113883.12.112",
            "name": "Discharge Disposition",
            "description": "Patient discharge disposition",
            "codes": DISCHARGE_DISPOSITION,
        },
    }

    @staticmethod
    def validate_code(value_set: str, code: str) -> bool:
        """
        Validate that a code exists in a specific value set.

        Args:
            value_set: Name of the value set (e.g., "PROBLEM_STATUS")
            code: Code to validate

        Returns:
            True if code is valid for the value set, False otherwise

        Example:
            >>> ValueSetRegistry.validate_code("PROBLEM_STATUS", "55561003")
            True
            >>> ValueSetRegistry.validate_code("PROBLEM_STATUS", "invalid")
            False
        """
        vs = ValueSetRegistry.VALUE_SETS.get(value_set)
        if not vs:
            return False

        codes = vs.get("codes", {})
        return code in codes

    @staticmethod
    def get_display_name(value_set: str, code: str) -> Optional[str]:
        """
        Get the display name for a code in a value set.

        Args:
            value_set: Name of the value set
            code: Code to look up

        Returns:
            Display name string if found, None otherwise

        Example:
            >>> ValueSetRegistry.get_display_name("PROBLEM_STATUS", "55561003")
            'Active'
            >>> ValueSetRegistry.get_display_name("PROBLEM_STATUS", "invalid")
            None
        """
        vs = ValueSetRegistry.VALUE_SETS.get(value_set)
        if not vs:
            return None

        codes = vs.get("codes", {})
        code_info = codes.get(code)
        if code_info:
            return code_info.get("display")
        return None

    @staticmethod
    def get_code_system(value_set: str, code: str) -> Optional[str]:
        """
        Get the code system for a code in a value set.

        Args:
            value_set: Name of the value set
            code: Code to look up

        Returns:
            Code system name if found, None otherwise

        Example:
            >>> ValueSetRegistry.get_code_system("PROBLEM_STATUS", "55561003")
            'SNOMED'
        """
        vs = ValueSetRegistry.VALUE_SETS.get(value_set)
        if not vs:
            return None

        codes = vs.get("codes", {})
        code_info = codes.get(code)
        if code_info:
            return code_info.get("system")
        return None

    @staticmethod
    def get_code_info(value_set: str, code: str) -> Optional[dict]:
        """
        Get complete information for a code in a value set.

        Args:
            value_set: Name of the value set
            code: Code to look up

        Returns:
            Dictionary with 'display' and 'system' keys if found, None otherwise

        Example:
            >>> info = ValueSetRegistry.get_code_info("PROBLEM_STATUS", "55561003")
            >>> info["display"]
            'Active'
            >>> info["system"]
            'SNOMED'
        """
        vs = ValueSetRegistry.VALUE_SETS.get(value_set)
        if not vs:
            return None

        codes = vs.get("codes", {})
        return codes.get(code)

    @staticmethod
    def get_value_set(name: str) -> Optional["dict[str, Any]"]:
        """
        Get complete value set definition.

        Args:
            name: Value set name

        Returns:
            Dictionary with value set metadata and codes if found, None otherwise

        Example:
            >>> vs = ValueSetRegistry.get_value_set("PROBLEM_STATUS")
            >>> vs["oid"]
            '2.16.840.1.113883.1.11.15933'
            >>> len(vs["codes"])
            3
        """
        return ValueSetRegistry.VALUE_SETS.get(name)

    @staticmethod
    def get_value_set_by_oid(oid: str) -> Optional["dict[str, Any]"]:
        """
        Get value set definition by OID.

        Args:
            oid: Value set OID

        Returns:
            Dictionary with value set metadata and codes if found, None otherwise

        Example:
            >>> vs = ValueSetRegistry.get_value_set_by_oid("2.16.840.1.113883.1.11.15933")
            >>> vs["name"]
            'Problem Status'
        """
        for _name, vs in ValueSetRegistry.VALUE_SETS.items():
            if vs.get("oid") == oid:
                return vs
        return None

    @staticmethod
    def list_value_sets() -> "list[str]":
        """
        Get list of all available value set names.

        Returns:
            List of value set names

        Example:
            >>> value_sets = ValueSetRegistry.list_value_sets()
            >>> "PROBLEM_STATUS" in value_sets
            True
            >>> len(value_sets)
            18
        """
        return list(ValueSetRegistry.VALUE_SETS.keys())

    @staticmethod
    def get_codes(value_set: str) -> "list[str]":
        """
        Get all valid codes for a value set.

        Args:
            value_set: Name of the value set

        Returns:
            List of valid codes, empty list if value set not found

        Example:
            >>> codes = ValueSetRegistry.get_codes("ADMINISTRATIVE_GENDER")
            >>> "M" in codes
            True
            >>> "F" in codes
            True
        """
        vs = ValueSetRegistry.VALUE_SETS.get(value_set)
        if not vs:
            return []

        codes = vs.get("codes", {})
        return list(codes.keys())

    @staticmethod
    def search_by_display(
        value_set: str, display_text: str, case_sensitive: bool = False
    ) -> "list[str]":
        """
        Search for codes by display name.

        Args:
            value_set: Name of the value set
            display_text: Display text to search for (partial match supported)
            case_sensitive: Whether search is case-sensitive (default: False)

        Returns:
            List of matching codes

        Example:
            >>> codes = ValueSetRegistry.search_by_display("PROBLEM_STATUS", "active")
            >>> "55561003" in codes
            True
        """
        vs = ValueSetRegistry.VALUE_SETS.get(value_set)
        if not vs:
            return []

        codes = vs.get("codes", {})
        matching_codes = []

        search_text = display_text if case_sensitive else display_text.lower()

        for code, info in codes.items():
            display = info.get("display", "")
            compare_display = display if case_sensitive else display.lower()

            if search_text in compare_display:
                matching_codes.append(code)

        return matching_codes

    @staticmethod
    def load_from_json(file_path: str) -> dict:
        """
        Load value set from JSON file.

        Args:
            file_path: Path to JSON file

        Returns:
            Dictionary with value set data

        Example JSON format:
            {
                "oid": "2.16.840.1.113883.1.11.15933",
                "name": "Custom Value Set",
                "description": "Description of the value set",
                "codes": {
                    "code1": {"display": "Display 1", "system": "SNOMED"},
                    "code2": {"display": "Display 2", "system": "LOINC"}
                }
            }
        """
        path = Path(file_path)
        if not path.exists():
            raise FileNotFoundError(f"Value set file not found: {file_path}")

        with open(path, encoding="utf-8") as f:
            return json.load(f)

    @staticmethod
    def save_to_json(value_set_name: str, file_path: str) -> None:
        """
        Save value set to JSON file.

        Args:
            value_set_name: Name of the value set to save
            file_path: Path where JSON file should be saved

        Raises:
            ValueError: If value set not found
        """
        vs = ValueSetRegistry.VALUE_SETS.get(value_set_name)
        if not vs:
            raise ValueError(f"Value set not found: {value_set_name}")

        path = Path(file_path)
        path.parent.mkdir(parents=True, exist_ok=True)

        with open(path, "w", encoding="utf-8") as f:
            json.dump(vs, f, indent=2)

Functions

validate_code(value_set, code) staticmethod

Validate that a code exists in a specific value set.

Parameters:

Name Type Description Default
value_set str

Name of the value set (e.g., "PROBLEM_STATUS")

required
code str

Code to validate

required

Returns:

Type Description
bool

True if code is valid for the value set, False otherwise

Example

ValueSetRegistry.validate_code("PROBLEM_STATUS", "55561003") True ValueSetRegistry.validate_code("PROBLEM_STATUS", "invalid") False

Source code in ccdakit/utils/value_sets.py
@staticmethod
def validate_code(value_set: str, code: str) -> bool:
    """
    Validate that a code exists in a specific value set.

    Args:
        value_set: Name of the value set (e.g., "PROBLEM_STATUS")
        code: Code to validate

    Returns:
        True if code is valid for the value set, False otherwise

    Example:
        >>> ValueSetRegistry.validate_code("PROBLEM_STATUS", "55561003")
        True
        >>> ValueSetRegistry.validate_code("PROBLEM_STATUS", "invalid")
        False
    """
    vs = ValueSetRegistry.VALUE_SETS.get(value_set)
    if not vs:
        return False

    codes = vs.get("codes", {})
    return code in codes

get_display_name(value_set, code) staticmethod

Get the display name for a code in a value set.

Parameters:

Name Type Description Default
value_set str

Name of the value set

required
code str

Code to look up

required

Returns:

Type Description
Optional[str]

Display name string if found, None otherwise

Example

ValueSetRegistry.get_display_name("PROBLEM_STATUS", "55561003") 'Active' ValueSetRegistry.get_display_name("PROBLEM_STATUS", "invalid") None

Source code in ccdakit/utils/value_sets.py
@staticmethod
def get_display_name(value_set: str, code: str) -> Optional[str]:
    """
    Get the display name for a code in a value set.

    Args:
        value_set: Name of the value set
        code: Code to look up

    Returns:
        Display name string if found, None otherwise

    Example:
        >>> ValueSetRegistry.get_display_name("PROBLEM_STATUS", "55561003")
        'Active'
        >>> ValueSetRegistry.get_display_name("PROBLEM_STATUS", "invalid")
        None
    """
    vs = ValueSetRegistry.VALUE_SETS.get(value_set)
    if not vs:
        return None

    codes = vs.get("codes", {})
    code_info = codes.get(code)
    if code_info:
        return code_info.get("display")
    return None

get_code_system(value_set, code) staticmethod

Get the code system for a code in a value set.

Parameters:

Name Type Description Default
value_set str

Name of the value set

required
code str

Code to look up

required

Returns:

Type Description
Optional[str]

Code system name if found, None otherwise

Example

ValueSetRegistry.get_code_system("PROBLEM_STATUS", "55561003") 'SNOMED'

Source code in ccdakit/utils/value_sets.py
@staticmethod
def get_code_system(value_set: str, code: str) -> Optional[str]:
    """
    Get the code system for a code in a value set.

    Args:
        value_set: Name of the value set
        code: Code to look up

    Returns:
        Code system name if found, None otherwise

    Example:
        >>> ValueSetRegistry.get_code_system("PROBLEM_STATUS", "55561003")
        'SNOMED'
    """
    vs = ValueSetRegistry.VALUE_SETS.get(value_set)
    if not vs:
        return None

    codes = vs.get("codes", {})
    code_info = codes.get(code)
    if code_info:
        return code_info.get("system")
    return None

get_code_info(value_set, code) staticmethod

Get complete information for a code in a value set.

Parameters:

Name Type Description Default
value_set str

Name of the value set

required
code str

Code to look up

required

Returns:

Type Description
Optional[dict]

Dictionary with 'display' and 'system' keys if found, None otherwise

Example

info = ValueSetRegistry.get_code_info("PROBLEM_STATUS", "55561003") info["display"] 'Active' info["system"] 'SNOMED'

Source code in ccdakit/utils/value_sets.py
@staticmethod
def get_code_info(value_set: str, code: str) -> Optional[dict]:
    """
    Get complete information for a code in a value set.

    Args:
        value_set: Name of the value set
        code: Code to look up

    Returns:
        Dictionary with 'display' and 'system' keys if found, None otherwise

    Example:
        >>> info = ValueSetRegistry.get_code_info("PROBLEM_STATUS", "55561003")
        >>> info["display"]
        'Active'
        >>> info["system"]
        'SNOMED'
    """
    vs = ValueSetRegistry.VALUE_SETS.get(value_set)
    if not vs:
        return None

    codes = vs.get("codes", {})
    return codes.get(code)

get_value_set(name) staticmethod

Get complete value set definition.

Parameters:

Name Type Description Default
name str

Value set name

required

Returns:

Type Description
Optional[dict[str, Any]]

Dictionary with value set metadata and codes if found, None otherwise

Example

vs = ValueSetRegistry.get_value_set("PROBLEM_STATUS") vs["oid"] '2.16.840.1.113883.1.11.15933' len(vs["codes"]) 3

Source code in ccdakit/utils/value_sets.py
@staticmethod
def get_value_set(name: str) -> Optional["dict[str, Any]"]:
    """
    Get complete value set definition.

    Args:
        name: Value set name

    Returns:
        Dictionary with value set metadata and codes if found, None otherwise

    Example:
        >>> vs = ValueSetRegistry.get_value_set("PROBLEM_STATUS")
        >>> vs["oid"]
        '2.16.840.1.113883.1.11.15933'
        >>> len(vs["codes"])
        3
    """
    return ValueSetRegistry.VALUE_SETS.get(name)

get_value_set_by_oid(oid) staticmethod

Get value set definition by OID.

Parameters:

Name Type Description Default
oid str

Value set OID

required

Returns:

Type Description
Optional[dict[str, Any]]

Dictionary with value set metadata and codes if found, None otherwise

Example

vs = ValueSetRegistry.get_value_set_by_oid("2.16.840.1.113883.1.11.15933") vs["name"] 'Problem Status'

Source code in ccdakit/utils/value_sets.py
@staticmethod
def get_value_set_by_oid(oid: str) -> Optional["dict[str, Any]"]:
    """
    Get value set definition by OID.

    Args:
        oid: Value set OID

    Returns:
        Dictionary with value set metadata and codes if found, None otherwise

    Example:
        >>> vs = ValueSetRegistry.get_value_set_by_oid("2.16.840.1.113883.1.11.15933")
        >>> vs["name"]
        'Problem Status'
    """
    for _name, vs in ValueSetRegistry.VALUE_SETS.items():
        if vs.get("oid") == oid:
            return vs
    return None

list_value_sets() staticmethod

Get list of all available value set names.

Returns:

Type Description
list[str]

List of value set names

Example

value_sets = ValueSetRegistry.list_value_sets() "PROBLEM_STATUS" in value_sets True len(value_sets) 18

Source code in ccdakit/utils/value_sets.py
@staticmethod
def list_value_sets() -> "list[str]":
    """
    Get list of all available value set names.

    Returns:
        List of value set names

    Example:
        >>> value_sets = ValueSetRegistry.list_value_sets()
        >>> "PROBLEM_STATUS" in value_sets
        True
        >>> len(value_sets)
        18
    """
    return list(ValueSetRegistry.VALUE_SETS.keys())

get_codes(value_set) staticmethod

Get all valid codes for a value set.

Parameters:

Name Type Description Default
value_set str

Name of the value set

required

Returns:

Type Description
list[str]

List of valid codes, empty list if value set not found

Example

codes = ValueSetRegistry.get_codes("ADMINISTRATIVE_GENDER") "M" in codes True "F" in codes True

Source code in ccdakit/utils/value_sets.py
@staticmethod
def get_codes(value_set: str) -> "list[str]":
    """
    Get all valid codes for a value set.

    Args:
        value_set: Name of the value set

    Returns:
        List of valid codes, empty list if value set not found

    Example:
        >>> codes = ValueSetRegistry.get_codes("ADMINISTRATIVE_GENDER")
        >>> "M" in codes
        True
        >>> "F" in codes
        True
    """
    vs = ValueSetRegistry.VALUE_SETS.get(value_set)
    if not vs:
        return []

    codes = vs.get("codes", {})
    return list(codes.keys())

search_by_display(value_set, display_text, case_sensitive=False) staticmethod

Search for codes by display name.

Parameters:

Name Type Description Default
value_set str

Name of the value set

required
display_text str

Display text to search for (partial match supported)

required
case_sensitive bool

Whether search is case-sensitive (default: False)

False

Returns:

Type Description
list[str]

List of matching codes

Example

codes = ValueSetRegistry.search_by_display("PROBLEM_STATUS", "active") "55561003" in codes True

Source code in ccdakit/utils/value_sets.py
@staticmethod
def search_by_display(
    value_set: str, display_text: str, case_sensitive: bool = False
) -> "list[str]":
    """
    Search for codes by display name.

    Args:
        value_set: Name of the value set
        display_text: Display text to search for (partial match supported)
        case_sensitive: Whether search is case-sensitive (default: False)

    Returns:
        List of matching codes

    Example:
        >>> codes = ValueSetRegistry.search_by_display("PROBLEM_STATUS", "active")
        >>> "55561003" in codes
        True
    """
    vs = ValueSetRegistry.VALUE_SETS.get(value_set)
    if not vs:
        return []

    codes = vs.get("codes", {})
    matching_codes = []

    search_text = display_text if case_sensitive else display_text.lower()

    for code, info in codes.items():
        display = info.get("display", "")
        compare_display = display if case_sensitive else display.lower()

        if search_text in compare_display:
            matching_codes.append(code)

    return matching_codes

load_from_json(file_path) staticmethod

Load value set from JSON file.

Parameters:

Name Type Description Default
file_path str

Path to JSON file

required

Returns:

Type Description
dict

Dictionary with value set data

Example JSON format

{ "oid": "2.16.840.1.113883.1.11.15933", "name": "Custom Value Set", "description": "Description of the value set", "codes": { "code1": {"display": "Display 1", "system": "SNOMED"}, "code2": {"display": "Display 2", "system": "LOINC"} } }

Source code in ccdakit/utils/value_sets.py
@staticmethod
def load_from_json(file_path: str) -> dict:
    """
    Load value set from JSON file.

    Args:
        file_path: Path to JSON file

    Returns:
        Dictionary with value set data

    Example JSON format:
        {
            "oid": "2.16.840.1.113883.1.11.15933",
            "name": "Custom Value Set",
            "description": "Description of the value set",
            "codes": {
                "code1": {"display": "Display 1", "system": "SNOMED"},
                "code2": {"display": "Display 2", "system": "LOINC"}
            }
        }
    """
    path = Path(file_path)
    if not path.exists():
        raise FileNotFoundError(f"Value set file not found: {file_path}")

    with open(path, encoding="utf-8") as f:
        return json.load(f)

save_to_json(value_set_name, file_path) staticmethod

Save value set to JSON file.

Parameters:

Name Type Description Default
value_set_name str

Name of the value set to save

required
file_path str

Path where JSON file should be saved

required

Raises:

Type Description
ValueError

If value set not found

Source code in ccdakit/utils/value_sets.py
@staticmethod
def save_to_json(value_set_name: str, file_path: str) -> None:
    """
    Save value set to JSON file.

    Args:
        value_set_name: Name of the value set to save
        file_path: Path where JSON file should be saved

    Raises:
        ValueError: If value set not found
    """
    vs = ValueSetRegistry.VALUE_SETS.get(value_set_name)
    if not vs:
        raise ValueError(f"Value set not found: {value_set_name}")

    path = Path(file_path)
    path.parent.mkdir(parents=True, exist_ok=True)

    with open(path, "w", encoding="utf-8") as f:
        json.dump(vs, f, indent=2)

Sample Data Generator

SampleDataGenerator

Generate realistic sample data for C-CDA documents.

This class provides methods to generate various types of clinical data including patient demographics, problems, medications, allergies, vital signs, and immunizations. All generated data includes appropriate medical terminology codes (SNOMED CT, RxNorm, CVX, LOINC, etc.).

Attributes:

Name Type Description
faker

Faker instance for generating realistic data

seed

Random seed for reproducibility (optional)

Example

Generate reproducible sample data

gen = SampleDataGenerator(seed=42) patient = gen.generate_patient() print(f"Patient: {patient['first_name']} {patient['last_name']}")

Generate a complete patient record

record = gen.generate_complete_patient_record() print(f"Generated {len(record['problems'])} problems")

Source code in ccdakit/utils/test_data.py
 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
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
class SampleDataGenerator:
    """Generate realistic sample data for C-CDA documents.

    This class provides methods to generate various types of clinical data
    including patient demographics, problems, medications, allergies, vital signs,
    and immunizations. All generated data includes appropriate medical terminology
    codes (SNOMED CT, RxNorm, CVX, LOINC, etc.).

    Attributes:
        faker: Faker instance for generating realistic data
        seed: Random seed for reproducibility (optional)

    Example:
        # Generate reproducible sample data
        gen = SampleDataGenerator(seed=42)
        patient = gen.generate_patient()
        print(f"Patient: {patient['first_name']} {patient['last_name']}")

        # Generate a complete patient record
        record = gen.generate_complete_patient_record()
        print(f"Generated {len(record['problems'])} problems")
    """

    # Common clinical problems with SNOMED CT codes
    COMMON_PROBLEMS = [
        ("Essential Hypertension", "59621000", "SNOMED"),
        ("Type 2 Diabetes Mellitus", "44054006", "SNOMED"),
        ("Hyperlipidemia", "55822004", "SNOMED"),
        ("Gastroesophageal Reflux Disease", "235595009", "SNOMED"),
        ("Asthma", "195967001", "SNOMED"),
        ("Chronic Obstructive Pulmonary Disease", "13645005", "SNOMED"),
        ("Coronary Artery Disease", "53741008", "SNOMED"),
        ("Atrial Fibrillation", "49436004", "SNOMED"),
        ("Hypothyroidism", "40930008", "SNOMED"),
        ("Osteoarthritis", "396275006", "SNOMED"),
        ("Major Depressive Disorder", "370143000", "SNOMED"),
        ("Generalized Anxiety Disorder", "21897009", "SNOMED"),
        ("Chronic Kidney Disease", "709044004", "SNOMED"),
        ("Benign Prostatic Hyperplasia", "266569009", "SNOMED"),
        ("Sleep Apnea", "78275009", "SNOMED"),
        ("Migraine", "37796009", "SNOMED"),
        ("Obesity", "414915002", "SNOMED"),
        ("Anemia", "271737000", "SNOMED"),
        ("Osteoporosis", "64859006", "SNOMED"),
        ("Peripheral Neuropathy", "42658009", "SNOMED"),
    ]

    # Common medications with RxNorm codes
    COMMON_MEDICATIONS = [
        ("Lisinopril 10 MG Oral Tablet", "314076", "RxNorm", "10 mg", "oral", "once daily"),
        ("Metformin 500 MG Oral Tablet", "860975", "RxNorm", "500 mg", "oral", "twice daily"),
        ("Atorvastatin 20 MG Oral Tablet", "617318", "RxNorm", "20 mg", "oral", "once daily"),
        ("Amlodipine 5 MG Oral Tablet", "197361", "RxNorm", "5 mg", "oral", "once daily"),
        (
            "Omeprazole 20 MG Delayed Release Oral Capsule",
            "198014",
            "RxNorm",
            "20 mg",
            "oral",
            "once daily",
        ),
        (
            "Levothyroxine Sodium 0.1 MG Oral Tablet",
            "966224",
            "RxNorm",
            "0.1 mg",
            "oral",
            "once daily",
        ),
        (
            "Metoprolol Succinate 50 MG Extended Release Oral Tablet",
            "866436",
            "RxNorm",
            "50 mg",
            "oral",
            "once daily",
        ),
        ("Sertraline 50 MG Oral Tablet", "312940", "RxNorm", "50 mg", "oral", "once daily"),
        (
            "Albuterol 0.09 MG/ACTUAT Metered Dose Inhaler",
            "745752",
            "RxNorm",
            "2 puffs",
            "inhaled",
            "as needed",
        ),
        (
            "Gabapentin 300 MG Oral Capsule",
            "105029",
            "RxNorm",
            "300 mg",
            "oral",
            "three times daily",
        ),
        ("Warfarin Sodium 5 MG Oral Tablet", "855333", "RxNorm", "5 mg", "oral", "once daily"),
        ("Furosemide 40 MG Oral Tablet", "310429", "RxNorm", "40 mg", "oral", "once daily"),
        (
            "Aspirin 81 MG Delayed Release Oral Tablet",
            "243670",
            "RxNorm",
            "81 mg",
            "oral",
            "once daily",
        ),
        (
            "Insulin Glargine 100 UNT/ML Injectable Solution",
            "261551",
            "RxNorm",
            "20 units",
            "subcutaneous",
            "once daily at bedtime",
        ),
    ]

    # Common allergens with codes
    COMMON_ALLERGENS = [
        ("Penicillin", "7980", "RxNorm", "allergy", "Rash", "moderate"),
        ("Sulfonamides", "10180", "RxNorm", "allergy", "Hives", "mild"),
        ("Shellfish", "227037002", "SNOMED", "allergy", "Anaphylaxis", "severe"),
        ("Peanuts", "256349002", "SNOMED", "allergy", "Swelling", "moderate"),
        ("Latex", "111088007", "SNOMED", "allergy", "Contact dermatitis", "mild"),
        ("Bee venom", "288328004", "SNOMED", "allergy", "Anaphylaxis", "severe"),
        ("Eggs", "102263004", "SNOMED", "allergy", "Nausea", "mild"),
        ("Codeine", "2670", "RxNorm", "intolerance", "Nausea", "moderate"),
        ("Aspirin", "1191", "RxNorm", "intolerance", "Stomach upset", "mild"),
        ("Ibuprofen", "5640", "RxNorm", "intolerance", "Rash", "mild"),
    ]

    # Common vaccines with CVX codes
    COMMON_VACCINES = [
        ("Influenza vaccine", "141", "Seasonal flu vaccine", "Intramuscular", "Left deltoid"),
        ("Pneumococcal conjugate vaccine", "133", "Prevnar 13", "Intramuscular", "Left deltoid"),
        ("Tetanus and diphtheria toxoids", "139", "Td vaccine", "Intramuscular", "Right deltoid"),
        ("Zoster vaccine live", "121", "Shingles vaccine", "Subcutaneous", "Upper arm"),
        ("Hepatitis B vaccine", "08", "Hep B vaccine", "Intramuscular", "Left deltoid"),
        (
            "Measles, mumps and rubella virus vaccine",
            "03",
            "MMR vaccine",
            "Subcutaneous",
            "Upper arm",
        ),
        ("COVID-19 vaccine, mRNA", "208", "COVID-19 vaccine", "Intramuscular", "Left deltoid"),
        ("Hepatitis A vaccine", "83", "Hep A vaccine", "Intramuscular", "Right deltoid"),
    ]

    # Vital signs with LOINC codes
    VITAL_SIGNS_TYPES = [
        ("Blood Pressure Systolic", "8480-6", "mm[Hg]", 110, 140),
        ("Blood Pressure Diastolic", "8462-4", "mm[Hg]", 70, 90),
        ("Heart Rate", "8867-4", "bpm", 60, 100),
        ("Respiratory Rate", "9279-1", "breaths/min", 12, 20),
        ("Body Temperature", "8310-5", "Cel", 36.5, 37.2),
        ("Oxygen Saturation", "2708-6", "%", 95, 100),
        ("Body Height", "8302-2", "cm", 150, 190),
        ("Body Weight", "29463-7", "kg", 50, 100),
        ("Body Mass Index", "39156-5", "kg/m2", 18.5, 30),
    ]

    def __init__(self, seed: Optional[int] = None):
        """Initialize test data generator.

        Args:
            seed: Optional random seed for reproducible data generation.
                  If provided, all generated data will be deterministic.
        """
        self.seed = seed
        if seed is not None:
            Faker.seed(seed)
            random.seed(seed)
        self.faker = Faker()

    def generate_address(self) -> "dict[str, Any]":
        """Generate a realistic address.

        Returns:
            Dictionary containing address fields compatible with AddressProtocol:
            - street_lines: List of street address lines
            - city: City name
            - state: State code (e.g., 'CA', 'NY')
            - postal_code: ZIP code
            - country: Country code (always 'US')
            - use: Address use code ('HP' for home, 'WP' for work)
        """
        return {
            "street_lines": [self.faker.street_address()],
            "city": self.faker.city(),
            "state": self.faker.state_abbr(),
            "postal_code": self.faker.zipcode(),
            "country": "US",
            "use": random.choice(["HP", "WP"]),  # Home or Work
        }

    def generate_telecom(self) -> "dict[str, Any]":
        """Generate a realistic telecom (contact method).

        Returns:
            Dictionary containing telecom fields compatible with TelecomProtocol:
            - type: Type of contact ('phone', 'email')
            - value: Contact value (phone number or email)
            - use: Use code ('HP', 'WP', 'MC')
        """
        contact_type = random.choice(["phone", "email"])
        if contact_type == "phone":
            return {
                "type": "phone",
                "value": f"tel:{self.faker.phone_number()}",
                "use": random.choice(["HP", "WP", "MC"]),  # Home, Work, Mobile
            }
        else:
            return {
                "type": "email",
                "value": f"mailto:{self.faker.email()}",
                "use": random.choice(["HP", "WP"]),
            }

    def generate_patient(self) -> "dict[str, Any]":
        """Generate realistic patient demographics.

        Returns:
            Dictionary containing patient demographic data compatible with PatientProtocol:
            - first_name: Patient's first name
            - last_name: Patient's last name
            - middle_name: Optional middle name
            - date_of_birth: Date of birth
            - sex: Administrative sex code ('M', 'F', or 'UN')
            - race: Optional race code (CDC Race and Ethnicity)
            - ethnicity: Optional ethnicity code
            - language: Optional language code (ISO 639-2)
            - ssn: Optional Social Security Number
            - addresses: List of addresses
            - telecoms: List of contact methods
            - marital_status: Optional marital status code
        """
        sex = random.choice(["M", "F"])
        min_age = 18
        max_age = 90

        # Generate age-appropriate first name
        if sex == "M":
            first_name = self.faker.first_name_male()
        else:
            first_name = self.faker.first_name_female()

        return {
            "first_name": first_name,
            "last_name": self.faker.last_name(),
            "middle_name": random.choice([self.faker.first_name()[:1], None]),
            "date_of_birth": self.faker.date_of_birth(minimum_age=min_age, maximum_age=max_age),
            "sex": sex,
            "race": random.choice(
                [
                    "2106-3",  # White
                    "2054-5",  # Black or African American
                    "2028-9",  # Asian
                    "1002-5",  # American Indian or Alaska Native
                    None,
                ]
            ),
            "ethnicity": random.choice(
                [
                    "2135-2",  # Hispanic or Latino
                    "2186-5",  # Not Hispanic or Latino
                    None,
                ]
            ),
            "language": random.choice(["en", "es", "fr", None]),
            "ssn": self.faker.ssn() if random.random() > 0.3 else None,
            "addresses": [self.generate_address()],
            "telecoms": [self.generate_telecom() for _ in range(random.randint(1, 3))],
            "marital_status": random.choice(
                ["M", "S", "D", "W", None]
            ),  # Married, Single, Divorced, Widowed
        }

    def generate_problem(self) -> "dict[str, Any]":
        """Generate a realistic clinical problem/condition.

        Returns:
            Dictionary containing problem data compatible with ProblemProtocol:
            - name: Human-readable problem name
            - code: Clinical code (SNOMED CT or ICD-10)
            - code_system: Code system name
            - status: Problem status ('active', 'inactive', or 'resolved')
            - onset_date: Date problem was identified
            - resolved_date: Optional date problem was resolved
            - persistent_id: None (can be added if needed)
        """
        problem = random.choice(self.COMMON_PROBLEMS)
        status = random.choice(
            ["active", "active", "active", "resolved"]
        )  # More likely to be active

        onset_date = self.faker.date_between(start_date="-5y", end_date="today")
        resolved_date = None
        if status == "resolved":
            resolved_date = self.faker.date_between(start_date=onset_date, end_date="today")

        return {
            "name": problem[0],
            "code": problem[1],
            "code_system": problem[2],
            "status": status,
            "onset_date": onset_date,
            "resolved_date": resolved_date,
            "persistent_id": None,
        }

    def generate_medication(self) -> "dict[str, Any]":
        """Generate a realistic medication.

        Returns:
            Dictionary containing medication data compatible with MedicationProtocol:
            - name: Medication name with strength and form
            - code: RxNorm code
            - dosage: Dosage amount
            - route: Route of administration
            - frequency: Frequency of administration
            - start_date: Date medication was started
            - end_date: Optional date medication was stopped
            - status: Medication status ('active', 'completed', or 'discontinued')
            - instructions: Optional patient instructions
        """
        med = random.choice(self.COMMON_MEDICATIONS)
        status = random.choice(["active", "active", "completed"])  # More likely to be active

        start_date = self.faker.date_between(start_date="-2y", end_date="today")
        end_date = None
        if status in ["completed", "discontinued"]:
            end_date = self.faker.date_between(start_date=start_date, end_date="today")

        return {
            "name": med[0],
            "code": med[1],
            "dosage": med[3],
            "route": med[4],
            "frequency": med[5],
            "start_date": start_date,
            "end_date": end_date,
            "status": status,
            "instructions": f"Take {med[3]} by {med[4]} route {med[5]}"
            if random.random() > 0.5
            else None,
        }

    def generate_allergy(self) -> "dict[str, Any]":
        """Generate a realistic allergy.

        Returns:
            Dictionary containing allergy data compatible with AllergyProtocol:
            - allergen: Allergen name
            - allergen_code: Code for the allergen
            - allergen_code_system: Code system (RxNorm or SNOMED)
            - allergy_type: Type ('allergy' or 'intolerance')
            - reaction: Optional reaction description
            - severity: Optional severity level
            - status: Status ('active' or 'resolved')
            - onset_date: Optional date allergy was identified
        """
        allergy = random.choice(self.COMMON_ALLERGENS)
        status = random.choice(
            ["active", "active", "active", "resolved"]
        )  # More likely to be active

        onset_date = None
        if random.random() > 0.3:
            onset_date = self.faker.date_between(start_date="-10y", end_date="today")

        return {
            "allergen": allergy[0],
            "allergen_code": allergy[1],
            "allergen_code_system": allergy[2],
            "allergy_type": allergy[3],
            "reaction": allergy[4],
            "severity": allergy[5],
            "status": status,
            "onset_date": onset_date,
        }

    def generate_vital_signs(self, count: Optional[int] = None) -> "dict[str, Any]":
        """Generate realistic vital signs readings.

        Args:
            count: Number of vital signs to generate. If None, generates 3-6 signs.

        Returns:
            Dictionary containing vital signs data compatible with VitalSignsOrganizerProtocol:
            - date: Date and time vital signs were taken
            - vital_signs: List of vital sign observations, each containing:
                - type: Type of vital sign
                - code: LOINC code
                - value: Measured value
                - unit: Unit of measurement
                - date: Same as organizer date
                - interpretation: Optional interpretation
        """
        if count is None:
            count = random.randint(3, 6)

        observation_date = self.faker.date_time_between(start_date="-1y", end_date="now")
        vital_signs_list = []

        # Select random vital signs
        selected_vitals = random.sample(
            self.VITAL_SIGNS_TYPES, min(count, len(self.VITAL_SIGNS_TYPES))
        )

        for vital in selected_vitals:
            name, loinc_code, unit, min_val, max_val = vital

            # Generate realistic value within range
            if unit in ["mm[Hg]", "bpm", "breaths/min", "cm", "kg"]:
                value = str(random.randint(int(min_val), int(max_val)))
            else:
                value = f"{random.uniform(min_val, max_val):.1f}"

            interpretation = None
            if random.random() > 0.7:
                interpretation = random.choice(["Normal", "High", "Low"])

            vital_signs_list.append(
                {
                    "type": name,
                    "code": loinc_code,
                    "value": value,
                    "unit": unit,
                    "date": observation_date,
                    "interpretation": interpretation,
                }
            )

        return {
            "date": observation_date,
            "vital_signs": vital_signs_list,
        }

    def generate_immunization(self) -> "dict[str, Any]":
        """Generate a realistic immunization record.

        Returns:
            Dictionary containing immunization data compatible with ImmunizationProtocol:
            - vaccine_name: Name of the vaccine
            - cvx_code: CVX code (CDC vaccine code)
            - administration_date: Date vaccine was administered
            - status: Status ('completed' or 'refused')
            - lot_number: Optional vaccine lot number
            - manufacturer: Optional manufacturer name
            - route: Route of administration
            - site: Body site where administered
            - dose_quantity: Optional dose quantity
        """
        vaccine = random.choice(self.COMMON_VACCINES)
        status = random.choice(
            ["completed", "completed", "completed", "refused"]
        )  # More likely completed

        admin_date = self.faker.date_between(start_date="-3y", end_date="today")

        lot_number = None
        manufacturer = None
        dose_quantity = None

        if status == "completed" and random.random() > 0.3:
            lot_number = self.faker.bothify(text="LOT###??##")
            manufacturer = random.choice(
                [
                    "Pfizer",
                    "Moderna",
                    "Merck",
                    "GlaxoSmithKline",
                    "Sanofi Pasteur",
                    "AstraZeneca",
                ]
            )
            dose_quantity = "0.5 mL" if random.random() > 0.5 else "1.0 mL"

        return {
            "vaccine_name": vaccine[0],
            "cvx_code": vaccine[1],
            "administration_date": admin_date,
            "status": status,
            "lot_number": lot_number,
            "manufacturer": manufacturer,
            "route": vaccine[3],
            "site": vaccine[4],
            "dose_quantity": dose_quantity,
        }

    def generate_complete_patient_record(
        self,
        num_problems: int = 3,
        num_medications: int = 2,
        num_allergies: int = 2,
        num_vital_signs_sets: int = 1,
        num_immunizations: int = 3,
    ) -> "dict[str, Any]":
        """Generate a complete patient record with all clinical data.

        This method generates a comprehensive patient record including demographics
        and all major clinical sections: problems, medications, allergies, vital signs,
        and immunizations.

        Args:
            num_problems: Number of problems to generate (default: 3)
            num_medications: Number of medications to generate (default: 2)
            num_allergies: Number of allergies to generate (default: 2)
            num_vital_signs_sets: Number of vital signs observation sets (default: 1)
            num_immunizations: Number of immunizations to generate (default: 3)

        Returns:
            Dictionary containing complete patient record:
            - patient: Patient demographic data
            - problems: List of clinical problems
            - medications: List of medications
            - allergies: List of allergies
            - vital_signs: List of vital signs observation sets
            - immunizations: List of immunizations
        """
        return {
            "patient": self.generate_patient(),
            "problems": [self.generate_problem() for _ in range(num_problems)],
            "medications": [self.generate_medication() for _ in range(num_medications)],
            "allergies": [self.generate_allergy() for _ in range(num_allergies)],
            "vital_signs": [self.generate_vital_signs() for _ in range(num_vital_signs_sets)],
            "immunizations": [self.generate_immunization() for _ in range(num_immunizations)],
        }

Functions

__init__(seed=None)

Initialize test data generator.

Parameters:

Name Type Description Default
seed Optional[int]

Optional random seed for reproducible data generation. If provided, all generated data will be deterministic.

None
Source code in ccdakit/utils/test_data.py
def __init__(self, seed: Optional[int] = None):
    """Initialize test data generator.

    Args:
        seed: Optional random seed for reproducible data generation.
              If provided, all generated data will be deterministic.
    """
    self.seed = seed
    if seed is not None:
        Faker.seed(seed)
        random.seed(seed)
    self.faker = Faker()

generate_address()

Generate a realistic address.

Returns:

Type Description
dict[str, Any]

Dictionary containing address fields compatible with AddressProtocol:

dict[str, Any]
  • street_lines: List of street address lines
dict[str, Any]
  • city: City name
dict[str, Any]
  • state: State code (e.g., 'CA', 'NY')
dict[str, Any]
  • postal_code: ZIP code
dict[str, Any]
  • country: Country code (always 'US')
dict[str, Any]
  • use: Address use code ('HP' for home, 'WP' for work)
Source code in ccdakit/utils/test_data.py
def generate_address(self) -> "dict[str, Any]":
    """Generate a realistic address.

    Returns:
        Dictionary containing address fields compatible with AddressProtocol:
        - street_lines: List of street address lines
        - city: City name
        - state: State code (e.g., 'CA', 'NY')
        - postal_code: ZIP code
        - country: Country code (always 'US')
        - use: Address use code ('HP' for home, 'WP' for work)
    """
    return {
        "street_lines": [self.faker.street_address()],
        "city": self.faker.city(),
        "state": self.faker.state_abbr(),
        "postal_code": self.faker.zipcode(),
        "country": "US",
        "use": random.choice(["HP", "WP"]),  # Home or Work
    }

generate_telecom()

Generate a realistic telecom (contact method).

Returns:

Type Description
dict[str, Any]

Dictionary containing telecom fields compatible with TelecomProtocol:

dict[str, Any]
  • type: Type of contact ('phone', 'email')
dict[str, Any]
  • value: Contact value (phone number or email)
dict[str, Any]
  • use: Use code ('HP', 'WP', 'MC')
Source code in ccdakit/utils/test_data.py
def generate_telecom(self) -> "dict[str, Any]":
    """Generate a realistic telecom (contact method).

    Returns:
        Dictionary containing telecom fields compatible with TelecomProtocol:
        - type: Type of contact ('phone', 'email')
        - value: Contact value (phone number or email)
        - use: Use code ('HP', 'WP', 'MC')
    """
    contact_type = random.choice(["phone", "email"])
    if contact_type == "phone":
        return {
            "type": "phone",
            "value": f"tel:{self.faker.phone_number()}",
            "use": random.choice(["HP", "WP", "MC"]),  # Home, Work, Mobile
        }
    else:
        return {
            "type": "email",
            "value": f"mailto:{self.faker.email()}",
            "use": random.choice(["HP", "WP"]),
        }

generate_patient()

Generate realistic patient demographics.

Returns:

Type Description
dict[str, Any]

Dictionary containing patient demographic data compatible with PatientProtocol:

dict[str, Any]
  • first_name: Patient's first name
dict[str, Any]
  • last_name: Patient's last name
dict[str, Any]
  • middle_name: Optional middle name
dict[str, Any]
  • date_of_birth: Date of birth
dict[str, Any]
  • sex: Administrative sex code ('M', 'F', or 'UN')
dict[str, Any]
  • race: Optional race code (CDC Race and Ethnicity)
dict[str, Any]
  • ethnicity: Optional ethnicity code
dict[str, Any]
  • language: Optional language code (ISO 639-2)
dict[str, Any]
  • ssn: Optional Social Security Number
dict[str, Any]
  • addresses: List of addresses
dict[str, Any]
  • telecoms: List of contact methods
dict[str, Any]
  • marital_status: Optional marital status code
Source code in ccdakit/utils/test_data.py
def generate_patient(self) -> "dict[str, Any]":
    """Generate realistic patient demographics.

    Returns:
        Dictionary containing patient demographic data compatible with PatientProtocol:
        - first_name: Patient's first name
        - last_name: Patient's last name
        - middle_name: Optional middle name
        - date_of_birth: Date of birth
        - sex: Administrative sex code ('M', 'F', or 'UN')
        - race: Optional race code (CDC Race and Ethnicity)
        - ethnicity: Optional ethnicity code
        - language: Optional language code (ISO 639-2)
        - ssn: Optional Social Security Number
        - addresses: List of addresses
        - telecoms: List of contact methods
        - marital_status: Optional marital status code
    """
    sex = random.choice(["M", "F"])
    min_age = 18
    max_age = 90

    # Generate age-appropriate first name
    if sex == "M":
        first_name = self.faker.first_name_male()
    else:
        first_name = self.faker.first_name_female()

    return {
        "first_name": first_name,
        "last_name": self.faker.last_name(),
        "middle_name": random.choice([self.faker.first_name()[:1], None]),
        "date_of_birth": self.faker.date_of_birth(minimum_age=min_age, maximum_age=max_age),
        "sex": sex,
        "race": random.choice(
            [
                "2106-3",  # White
                "2054-5",  # Black or African American
                "2028-9",  # Asian
                "1002-5",  # American Indian or Alaska Native
                None,
            ]
        ),
        "ethnicity": random.choice(
            [
                "2135-2",  # Hispanic or Latino
                "2186-5",  # Not Hispanic or Latino
                None,
            ]
        ),
        "language": random.choice(["en", "es", "fr", None]),
        "ssn": self.faker.ssn() if random.random() > 0.3 else None,
        "addresses": [self.generate_address()],
        "telecoms": [self.generate_telecom() for _ in range(random.randint(1, 3))],
        "marital_status": random.choice(
            ["M", "S", "D", "W", None]
        ),  # Married, Single, Divorced, Widowed
    }

generate_problem()

Generate a realistic clinical problem/condition.

Returns:

Type Description
dict[str, Any]

Dictionary containing problem data compatible with ProblemProtocol:

dict[str, Any]
  • name: Human-readable problem name
dict[str, Any]
  • code: Clinical code (SNOMED CT or ICD-10)
dict[str, Any]
  • code_system: Code system name
dict[str, Any]
  • status: Problem status ('active', 'inactive', or 'resolved')
dict[str, Any]
  • onset_date: Date problem was identified
dict[str, Any]
  • resolved_date: Optional date problem was resolved
dict[str, Any]
  • persistent_id: None (can be added if needed)
Source code in ccdakit/utils/test_data.py
def generate_problem(self) -> "dict[str, Any]":
    """Generate a realistic clinical problem/condition.

    Returns:
        Dictionary containing problem data compatible with ProblemProtocol:
        - name: Human-readable problem name
        - code: Clinical code (SNOMED CT or ICD-10)
        - code_system: Code system name
        - status: Problem status ('active', 'inactive', or 'resolved')
        - onset_date: Date problem was identified
        - resolved_date: Optional date problem was resolved
        - persistent_id: None (can be added if needed)
    """
    problem = random.choice(self.COMMON_PROBLEMS)
    status = random.choice(
        ["active", "active", "active", "resolved"]
    )  # More likely to be active

    onset_date = self.faker.date_between(start_date="-5y", end_date="today")
    resolved_date = None
    if status == "resolved":
        resolved_date = self.faker.date_between(start_date=onset_date, end_date="today")

    return {
        "name": problem[0],
        "code": problem[1],
        "code_system": problem[2],
        "status": status,
        "onset_date": onset_date,
        "resolved_date": resolved_date,
        "persistent_id": None,
    }

generate_medication()

Generate a realistic medication.

Returns:

Type Description
dict[str, Any]

Dictionary containing medication data compatible with MedicationProtocol:

dict[str, Any]
  • name: Medication name with strength and form
dict[str, Any]
  • code: RxNorm code
dict[str, Any]
  • dosage: Dosage amount
dict[str, Any]
  • route: Route of administration
dict[str, Any]
  • frequency: Frequency of administration
dict[str, Any]
  • start_date: Date medication was started
dict[str, Any]
  • end_date: Optional date medication was stopped
dict[str, Any]
  • status: Medication status ('active', 'completed', or 'discontinued')
dict[str, Any]
  • instructions: Optional patient instructions
Source code in ccdakit/utils/test_data.py
def generate_medication(self) -> "dict[str, Any]":
    """Generate a realistic medication.

    Returns:
        Dictionary containing medication data compatible with MedicationProtocol:
        - name: Medication name with strength and form
        - code: RxNorm code
        - dosage: Dosage amount
        - route: Route of administration
        - frequency: Frequency of administration
        - start_date: Date medication was started
        - end_date: Optional date medication was stopped
        - status: Medication status ('active', 'completed', or 'discontinued')
        - instructions: Optional patient instructions
    """
    med = random.choice(self.COMMON_MEDICATIONS)
    status = random.choice(["active", "active", "completed"])  # More likely to be active

    start_date = self.faker.date_between(start_date="-2y", end_date="today")
    end_date = None
    if status in ["completed", "discontinued"]:
        end_date = self.faker.date_between(start_date=start_date, end_date="today")

    return {
        "name": med[0],
        "code": med[1],
        "dosage": med[3],
        "route": med[4],
        "frequency": med[5],
        "start_date": start_date,
        "end_date": end_date,
        "status": status,
        "instructions": f"Take {med[3]} by {med[4]} route {med[5]}"
        if random.random() > 0.5
        else None,
    }

generate_allergy()

Generate a realistic allergy.

Returns:

Type Description
dict[str, Any]

Dictionary containing allergy data compatible with AllergyProtocol:

dict[str, Any]
  • allergen: Allergen name
dict[str, Any]
  • allergen_code: Code for the allergen
dict[str, Any]
  • allergen_code_system: Code system (RxNorm or SNOMED)
dict[str, Any]
  • allergy_type: Type ('allergy' or 'intolerance')
dict[str, Any]
  • reaction: Optional reaction description
dict[str, Any]
  • severity: Optional severity level
dict[str, Any]
  • status: Status ('active' or 'resolved')
dict[str, Any]
  • onset_date: Optional date allergy was identified
Source code in ccdakit/utils/test_data.py
def generate_allergy(self) -> "dict[str, Any]":
    """Generate a realistic allergy.

    Returns:
        Dictionary containing allergy data compatible with AllergyProtocol:
        - allergen: Allergen name
        - allergen_code: Code for the allergen
        - allergen_code_system: Code system (RxNorm or SNOMED)
        - allergy_type: Type ('allergy' or 'intolerance')
        - reaction: Optional reaction description
        - severity: Optional severity level
        - status: Status ('active' or 'resolved')
        - onset_date: Optional date allergy was identified
    """
    allergy = random.choice(self.COMMON_ALLERGENS)
    status = random.choice(
        ["active", "active", "active", "resolved"]
    )  # More likely to be active

    onset_date = None
    if random.random() > 0.3:
        onset_date = self.faker.date_between(start_date="-10y", end_date="today")

    return {
        "allergen": allergy[0],
        "allergen_code": allergy[1],
        "allergen_code_system": allergy[2],
        "allergy_type": allergy[3],
        "reaction": allergy[4],
        "severity": allergy[5],
        "status": status,
        "onset_date": onset_date,
    }

generate_vital_signs(count=None)

Generate realistic vital signs readings.

Parameters:

Name Type Description Default
count Optional[int]

Number of vital signs to generate. If None, generates 3-6 signs.

None

Returns:

Type Description
dict[str, Any]

Dictionary containing vital signs data compatible with VitalSignsOrganizerProtocol:

dict[str, Any]
  • date: Date and time vital signs were taken
dict[str, Any]
  • vital_signs: List of vital sign observations, each containing:
  • type: Type of vital sign
  • code: LOINC code
  • value: Measured value
  • unit: Unit of measurement
  • date: Same as organizer date
  • interpretation: Optional interpretation
Source code in ccdakit/utils/test_data.py
def generate_vital_signs(self, count: Optional[int] = None) -> "dict[str, Any]":
    """Generate realistic vital signs readings.

    Args:
        count: Number of vital signs to generate. If None, generates 3-6 signs.

    Returns:
        Dictionary containing vital signs data compatible with VitalSignsOrganizerProtocol:
        - date: Date and time vital signs were taken
        - vital_signs: List of vital sign observations, each containing:
            - type: Type of vital sign
            - code: LOINC code
            - value: Measured value
            - unit: Unit of measurement
            - date: Same as organizer date
            - interpretation: Optional interpretation
    """
    if count is None:
        count = random.randint(3, 6)

    observation_date = self.faker.date_time_between(start_date="-1y", end_date="now")
    vital_signs_list = []

    # Select random vital signs
    selected_vitals = random.sample(
        self.VITAL_SIGNS_TYPES, min(count, len(self.VITAL_SIGNS_TYPES))
    )

    for vital in selected_vitals:
        name, loinc_code, unit, min_val, max_val = vital

        # Generate realistic value within range
        if unit in ["mm[Hg]", "bpm", "breaths/min", "cm", "kg"]:
            value = str(random.randint(int(min_val), int(max_val)))
        else:
            value = f"{random.uniform(min_val, max_val):.1f}"

        interpretation = None
        if random.random() > 0.7:
            interpretation = random.choice(["Normal", "High", "Low"])

        vital_signs_list.append(
            {
                "type": name,
                "code": loinc_code,
                "value": value,
                "unit": unit,
                "date": observation_date,
                "interpretation": interpretation,
            }
        )

    return {
        "date": observation_date,
        "vital_signs": vital_signs_list,
    }

generate_immunization()

Generate a realistic immunization record.

Returns:

Type Description
dict[str, Any]

Dictionary containing immunization data compatible with ImmunizationProtocol:

dict[str, Any]
  • vaccine_name: Name of the vaccine
dict[str, Any]
  • cvx_code: CVX code (CDC vaccine code)
dict[str, Any]
  • administration_date: Date vaccine was administered
dict[str, Any]
  • status: Status ('completed' or 'refused')
dict[str, Any]
  • lot_number: Optional vaccine lot number
dict[str, Any]
  • manufacturer: Optional manufacturer name
dict[str, Any]
  • route: Route of administration
dict[str, Any]
  • site: Body site where administered
dict[str, Any]
  • dose_quantity: Optional dose quantity
Source code in ccdakit/utils/test_data.py
def generate_immunization(self) -> "dict[str, Any]":
    """Generate a realistic immunization record.

    Returns:
        Dictionary containing immunization data compatible with ImmunizationProtocol:
        - vaccine_name: Name of the vaccine
        - cvx_code: CVX code (CDC vaccine code)
        - administration_date: Date vaccine was administered
        - status: Status ('completed' or 'refused')
        - lot_number: Optional vaccine lot number
        - manufacturer: Optional manufacturer name
        - route: Route of administration
        - site: Body site where administered
        - dose_quantity: Optional dose quantity
    """
    vaccine = random.choice(self.COMMON_VACCINES)
    status = random.choice(
        ["completed", "completed", "completed", "refused"]
    )  # More likely completed

    admin_date = self.faker.date_between(start_date="-3y", end_date="today")

    lot_number = None
    manufacturer = None
    dose_quantity = None

    if status == "completed" and random.random() > 0.3:
        lot_number = self.faker.bothify(text="LOT###??##")
        manufacturer = random.choice(
            [
                "Pfizer",
                "Moderna",
                "Merck",
                "GlaxoSmithKline",
                "Sanofi Pasteur",
                "AstraZeneca",
            ]
        )
        dose_quantity = "0.5 mL" if random.random() > 0.5 else "1.0 mL"

    return {
        "vaccine_name": vaccine[0],
        "cvx_code": vaccine[1],
        "administration_date": admin_date,
        "status": status,
        "lot_number": lot_number,
        "manufacturer": manufacturer,
        "route": vaccine[3],
        "site": vaccine[4],
        "dose_quantity": dose_quantity,
    }

generate_complete_patient_record(num_problems=3, num_medications=2, num_allergies=2, num_vital_signs_sets=1, num_immunizations=3)

Generate a complete patient record with all clinical data.

This method generates a comprehensive patient record including demographics and all major clinical sections: problems, medications, allergies, vital signs, and immunizations.

Parameters:

Name Type Description Default
num_problems int

Number of problems to generate (default: 3)

3
num_medications int

Number of medications to generate (default: 2)

2
num_allergies int

Number of allergies to generate (default: 2)

2
num_vital_signs_sets int

Number of vital signs observation sets (default: 1)

1
num_immunizations int

Number of immunizations to generate (default: 3)

3

Returns:

Type Description
dict[str, Any]

Dictionary containing complete patient record:

dict[str, Any]
  • patient: Patient demographic data
dict[str, Any]
  • problems: List of clinical problems
dict[str, Any]
  • medications: List of medications
dict[str, Any]
  • allergies: List of allergies
dict[str, Any]
  • vital_signs: List of vital signs observation sets
dict[str, Any]
  • immunizations: List of immunizations
Source code in ccdakit/utils/test_data.py
def generate_complete_patient_record(
    self,
    num_problems: int = 3,
    num_medications: int = 2,
    num_allergies: int = 2,
    num_vital_signs_sets: int = 1,
    num_immunizations: int = 3,
) -> "dict[str, Any]":
    """Generate a complete patient record with all clinical data.

    This method generates a comprehensive patient record including demographics
    and all major clinical sections: problems, medications, allergies, vital signs,
    and immunizations.

    Args:
        num_problems: Number of problems to generate (default: 3)
        num_medications: Number of medications to generate (default: 2)
        num_allergies: Number of allergies to generate (default: 2)
        num_vital_signs_sets: Number of vital signs observation sets (default: 1)
        num_immunizations: Number of immunizations to generate (default: 3)

    Returns:
        Dictionary containing complete patient record:
        - patient: Patient demographic data
        - problems: List of clinical problems
        - medications: List of medications
        - allergies: List of allergies
        - vital_signs: List of vital signs observation sets
        - immunizations: List of immunizations
    """
    return {
        "patient": self.generate_patient(),
        "problems": [self.generate_problem() for _ in range(num_problems)],
        "medications": [self.generate_medication() for _ in range(num_medications)],
        "allergies": [self.generate_allergy() for _ in range(num_allergies)],
        "vital_signs": [self.generate_vital_signs() for _ in range(num_vital_signs_sets)],
        "immunizations": [self.generate_immunization() for _ in range(num_immunizations)],
    }

Builders Utilities

SimplePatientBuilder

Fluent API for building patient data that satisfies PatientProtocol.

This builder creates dictionary-based patient data with a fluent interface. The resulting dictionary can be converted to a class instance that satisfies the PatientProtocol.

Example

patient = ( ... SimplePatientBuilder() ... .name("John", "Doe", "Q") ... .birth_date(date(1970, 5, 15)) ... .gender("M") ... .race("2106-3") # White (CDC Race Code) ... .ethnicity("2186-5") # Not Hispanic or Latino ... .language("eng") ... .ssn("123-45-6789") ... .marital_status("M") # Married ... .address("123 Main St", "Boston", "MA", "02101") ... .phone("617-555-1234", "home") ... .email("[email protected]", "home") ... .build() ... )

Source code in ccdakit/utils/builders.py
class SimplePatientBuilder:
    """Fluent API for building patient data that satisfies PatientProtocol.

    This builder creates dictionary-based patient data with a fluent interface.
    The resulting dictionary can be converted to a class instance that satisfies
    the PatientProtocol.

    Example:
        >>> patient = (
        ...     SimplePatientBuilder()
        ...     .name("John", "Doe", "Q")
        ...     .birth_date(date(1970, 5, 15))
        ...     .gender("M")
        ...     .race("2106-3")  # White (CDC Race Code)
        ...     .ethnicity("2186-5")  # Not Hispanic or Latino
        ...     .language("eng")
        ...     .ssn("123-45-6789")
        ...     .marital_status("M")  # Married
        ...     .address("123 Main St", "Boston", "MA", "02101")
        ...     .phone("617-555-1234", "home")
        ...     .email("[email protected]", "home")
        ...     .build()
        ... )
    """

    def __init__(self) -> None:
        """Initialize the patient builder."""
        self._data: Dict[str, Any] = {
            "addresses": [],
            "telecoms": [],
        }

    def name(self, first: str, last: str, middle: Optional[str] = None) -> "SimplePatientBuilder":
        """Set patient name.

        Args:
            first: First name
            last: Last name
            middle: Middle name or initial (optional)

        Returns:
            Self for method chaining
        """
        self._data["first_name"] = first
        self._data["last_name"] = last
        if middle is not None:
            self._data["middle_name"] = middle
        return self

    def birth_date(self, birth_date: date) -> "SimplePatientBuilder":
        """Set date of birth.

        Args:
            birth_date: Patient's date of birth

        Returns:
            Self for method chaining
        """
        self._data["date_of_birth"] = birth_date
        return self

    def gender(self, sex: str) -> "SimplePatientBuilder":
        """Set administrative sex.

        Args:
            sex: Administrative sex code ('M', 'F', or 'UN')

        Returns:
            Self for method chaining
        """
        self._data["sex"] = sex
        return self

    def race(self, race_code: str) -> "SimplePatientBuilder":
        """Set race code.

        Args:
            race_code: CDC Race and Ethnicity code (e.g., '2106-3' for White)

        Returns:
            Self for method chaining
        """
        self._data["race"] = race_code
        return self

    def ethnicity(self, ethnicity_code: str) -> "SimplePatientBuilder":
        """Set ethnicity code.

        Args:
            ethnicity_code: CDC Race and Ethnicity code (e.g., '2186-5' for Not Hispanic or Latino)

        Returns:
            Self for method chaining
        """
        self._data["ethnicity"] = ethnicity_code
        return self

    def language(self, language_code: str) -> "SimplePatientBuilder":
        """Set preferred language.

        Args:
            language_code: ISO 639-2 language code (e.g., 'eng' for English)

        Returns:
            Self for method chaining
        """
        self._data["language"] = language_code
        return self

    def ssn(self, ssn: str) -> "SimplePatientBuilder":
        """Set Social Security Number or national ID.

        Args:
            ssn: Social Security Number or national ID

        Returns:
            Self for method chaining
        """
        self._data["ssn"] = ssn
        return self

    def marital_status(self, status: str) -> "SimplePatientBuilder":
        """Set marital status.

        Args:
            status: HL7 MaritalStatus code (e.g., 'M' for Married, 'S' for Single)

        Returns:
            Self for method chaining
        """
        self._data["marital_status"] = status
        return self

    def address(
        self,
        street: str,
        city: str,
        state: str,
        zip_code: str,
        country: str = "US",
        street2: Optional[str] = None,
    ) -> "SimplePatientBuilder":
        """Add an address.

        Args:
            street: Street address line 1
            city: City name
            state: State/province code (e.g., 'MA', 'CA')
            zip_code: ZIP/postal code
            country: Country code (ISO 3166-1 alpha-2, default: 'US')
            street2: Street address line 2 (optional)

        Returns:
            Self for method chaining
        """
        street_lines = [street]
        if street2:
            street_lines.append(street2)

        address_data = {
            "street_lines": street_lines,
            "city": city,
            "state": state,
            "postal_code": zip_code,
            "country": country,
        }
        self._data["addresses"].append(address_data)
        return self

    def phone(self, number: str, use: str = "home") -> "SimplePatientBuilder":
        """Add a phone number.

        Args:
            number: Phone number
            use: Use code ('home', 'work', 'mobile')

        Returns:
            Self for method chaining
        """
        telecom_data = {"type": "phone", "value": number, "use": use}
        self._data["telecoms"].append(telecom_data)
        return self

    def email(self, email: str, use: str = "home") -> "SimplePatientBuilder":
        """Add an email address.

        Args:
            email: Email address
            use: Use code ('home', 'work')

        Returns:
            Self for method chaining
        """
        telecom_data = {"type": "email", "value": email, "use": use}
        self._data["telecoms"].append(telecom_data)
        return self

    def build(self) -> Dict[str, Any]:
        """Build patient data dictionary.

        Returns:
            Dictionary containing all patient data
        """
        return self._data.copy()

Functions

__init__()

Initialize the patient builder.

Source code in ccdakit/utils/builders.py
def __init__(self) -> None:
    """Initialize the patient builder."""
    self._data: Dict[str, Any] = {
        "addresses": [],
        "telecoms": [],
    }

name(first, last, middle=None)

Set patient name.

Parameters:

Name Type Description Default
first str

First name

required
last str

Last name

required
middle Optional[str]

Middle name or initial (optional)

None

Returns:

Type Description
SimplePatientBuilder

Self for method chaining

Source code in ccdakit/utils/builders.py
def name(self, first: str, last: str, middle: Optional[str] = None) -> "SimplePatientBuilder":
    """Set patient name.

    Args:
        first: First name
        last: Last name
        middle: Middle name or initial (optional)

    Returns:
        Self for method chaining
    """
    self._data["first_name"] = first
    self._data["last_name"] = last
    if middle is not None:
        self._data["middle_name"] = middle
    return self

birth_date(birth_date)

Set date of birth.

Parameters:

Name Type Description Default
birth_date date

Patient's date of birth

required

Returns:

Type Description
SimplePatientBuilder

Self for method chaining

Source code in ccdakit/utils/builders.py
def birth_date(self, birth_date: date) -> "SimplePatientBuilder":
    """Set date of birth.

    Args:
        birth_date: Patient's date of birth

    Returns:
        Self for method chaining
    """
    self._data["date_of_birth"] = birth_date
    return self

gender(sex)

Set administrative sex.

Parameters:

Name Type Description Default
sex str

Administrative sex code ('M', 'F', or 'UN')

required

Returns:

Type Description
SimplePatientBuilder

Self for method chaining

Source code in ccdakit/utils/builders.py
def gender(self, sex: str) -> "SimplePatientBuilder":
    """Set administrative sex.

    Args:
        sex: Administrative sex code ('M', 'F', or 'UN')

    Returns:
        Self for method chaining
    """
    self._data["sex"] = sex
    return self

race(race_code)

Set race code.

Parameters:

Name Type Description Default
race_code str

CDC Race and Ethnicity code (e.g., '2106-3' for White)

required

Returns:

Type Description
SimplePatientBuilder

Self for method chaining

Source code in ccdakit/utils/builders.py
def race(self, race_code: str) -> "SimplePatientBuilder":
    """Set race code.

    Args:
        race_code: CDC Race and Ethnicity code (e.g., '2106-3' for White)

    Returns:
        Self for method chaining
    """
    self._data["race"] = race_code
    return self

ethnicity(ethnicity_code)

Set ethnicity code.

Parameters:

Name Type Description Default
ethnicity_code str

CDC Race and Ethnicity code (e.g., '2186-5' for Not Hispanic or Latino)

required

Returns:

Type Description
SimplePatientBuilder

Self for method chaining

Source code in ccdakit/utils/builders.py
def ethnicity(self, ethnicity_code: str) -> "SimplePatientBuilder":
    """Set ethnicity code.

    Args:
        ethnicity_code: CDC Race and Ethnicity code (e.g., '2186-5' for Not Hispanic or Latino)

    Returns:
        Self for method chaining
    """
    self._data["ethnicity"] = ethnicity_code
    return self

language(language_code)

Set preferred language.

Parameters:

Name Type Description Default
language_code str

ISO 639-2 language code (e.g., 'eng' for English)

required

Returns:

Type Description
SimplePatientBuilder

Self for method chaining

Source code in ccdakit/utils/builders.py
def language(self, language_code: str) -> "SimplePatientBuilder":
    """Set preferred language.

    Args:
        language_code: ISO 639-2 language code (e.g., 'eng' for English)

    Returns:
        Self for method chaining
    """
    self._data["language"] = language_code
    return self

ssn(ssn)

Set Social Security Number or national ID.

Parameters:

Name Type Description Default
ssn str

Social Security Number or national ID

required

Returns:

Type Description
SimplePatientBuilder

Self for method chaining

Source code in ccdakit/utils/builders.py
def ssn(self, ssn: str) -> "SimplePatientBuilder":
    """Set Social Security Number or national ID.

    Args:
        ssn: Social Security Number or national ID

    Returns:
        Self for method chaining
    """
    self._data["ssn"] = ssn
    return self

marital_status(status)

Set marital status.

Parameters:

Name Type Description Default
status str

HL7 MaritalStatus code (e.g., 'M' for Married, 'S' for Single)

required

Returns:

Type Description
SimplePatientBuilder

Self for method chaining

Source code in ccdakit/utils/builders.py
def marital_status(self, status: str) -> "SimplePatientBuilder":
    """Set marital status.

    Args:
        status: HL7 MaritalStatus code (e.g., 'M' for Married, 'S' for Single)

    Returns:
        Self for method chaining
    """
    self._data["marital_status"] = status
    return self

address(street, city, state, zip_code, country='US', street2=None)

Add an address.

Parameters:

Name Type Description Default
street str

Street address line 1

required
city str

City name

required
state str

State/province code (e.g., 'MA', 'CA')

required
zip_code str

ZIP/postal code

required
country str

Country code (ISO 3166-1 alpha-2, default: 'US')

'US'
street2 Optional[str]

Street address line 2 (optional)

None

Returns:

Type Description
SimplePatientBuilder

Self for method chaining

Source code in ccdakit/utils/builders.py
def address(
    self,
    street: str,
    city: str,
    state: str,
    zip_code: str,
    country: str = "US",
    street2: Optional[str] = None,
) -> "SimplePatientBuilder":
    """Add an address.

    Args:
        street: Street address line 1
        city: City name
        state: State/province code (e.g., 'MA', 'CA')
        zip_code: ZIP/postal code
        country: Country code (ISO 3166-1 alpha-2, default: 'US')
        street2: Street address line 2 (optional)

    Returns:
        Self for method chaining
    """
    street_lines = [street]
    if street2:
        street_lines.append(street2)

    address_data = {
        "street_lines": street_lines,
        "city": city,
        "state": state,
        "postal_code": zip_code,
        "country": country,
    }
    self._data["addresses"].append(address_data)
    return self

phone(number, use='home')

Add a phone number.

Parameters:

Name Type Description Default
number str

Phone number

required
use str

Use code ('home', 'work', 'mobile')

'home'

Returns:

Type Description
SimplePatientBuilder

Self for method chaining

Source code in ccdakit/utils/builders.py
def phone(self, number: str, use: str = "home") -> "SimplePatientBuilder":
    """Add a phone number.

    Args:
        number: Phone number
        use: Use code ('home', 'work', 'mobile')

    Returns:
        Self for method chaining
    """
    telecom_data = {"type": "phone", "value": number, "use": use}
    self._data["telecoms"].append(telecom_data)
    return self

email(email, use='home')

Add an email address.

Parameters:

Name Type Description Default
email str

Email address

required
use str

Use code ('home', 'work')

'home'

Returns:

Type Description
SimplePatientBuilder

Self for method chaining

Source code in ccdakit/utils/builders.py
def email(self, email: str, use: str = "home") -> "SimplePatientBuilder":
    """Add an email address.

    Args:
        email: Email address
        use: Use code ('home', 'work')

    Returns:
        Self for method chaining
    """
    telecom_data = {"type": "email", "value": email, "use": use}
    self._data["telecoms"].append(telecom_data)
    return self

build()

Build patient data dictionary.

Returns:

Type Description
Dict[str, Any]

Dictionary containing all patient data

Source code in ccdakit/utils/builders.py
def build(self) -> Dict[str, Any]:
    """Build patient data dictionary.

    Returns:
        Dictionary containing all patient data
    """
    return self._data.copy()

SimpleProblemBuilder

Fluent API for building problem/condition data that satisfies ProblemProtocol.

Example

problem = ( ... SimpleProblemBuilder() ... .name("Essential Hypertension") ... .code("59621000", "SNOMED") ... .status("active") ... .onset_date(date(2018, 5, 10)) ... .build() ... )

Source code in ccdakit/utils/builders.py
class SimpleProblemBuilder:
    """Fluent API for building problem/condition data that satisfies ProblemProtocol.

    Example:
        >>> problem = (
        ...     SimpleProblemBuilder()
        ...     .name("Essential Hypertension")
        ...     .code("59621000", "SNOMED")
        ...     .status("active")
        ...     .onset_date(date(2018, 5, 10))
        ...     .build()
        ... )
    """

    def __init__(self) -> None:
        """Initialize the problem builder."""
        self._data: Dict[str, Any] = {}

    def name(self, problem_name: str) -> "SimpleProblemBuilder":
        """Set problem name.

        Args:
            problem_name: Human-readable problem name

        Returns:
            Self for method chaining
        """
        self._data["name"] = problem_name
        return self

    def code(self, code: str, code_system: str) -> "SimpleProblemBuilder":
        """Set problem code and code system.

        Args:
            code: Problem code (SNOMED CT or ICD-10)
            code_system: Code system name ('SNOMED' or 'ICD-10')

        Returns:
            Self for method chaining
        """
        self._data["code"] = code
        self._data["code_system"] = code_system
        return self

    def status(self, status: str) -> "SimpleProblemBuilder":
        """Set problem status.

        Args:
            status: Status ('active', 'inactive', 'resolved')

        Returns:
            Self for method chaining
        """
        self._data["status"] = status
        return self

    def onset_date(self, onset: date) -> "SimpleProblemBuilder":
        """Set onset date.

        Args:
            onset: Date problem was identified/started

        Returns:
            Self for method chaining
        """
        self._data["onset_date"] = onset
        return self

    def resolved_date(self, resolved: date) -> "SimpleProblemBuilder":
        """Set resolved date.

        Args:
            resolved: Date problem was resolved

        Returns:
            Self for method chaining
        """
        self._data["resolved_date"] = resolved
        return self

    def persistent_id(self, root: str, extension: str) -> "SimpleProblemBuilder":
        """Set persistent identifier.

        Args:
            root: OID or UUID identifying the assigning authority
            extension: Unique identifier within the root's namespace

        Returns:
            Self for method chaining
        """
        self._data["persistent_id"] = {"root": root, "extension": extension}
        return self

    def build(self) -> Dict[str, Any]:
        """Build problem data dictionary.

        Returns:
            Dictionary containing all problem data
        """
        return self._data.copy()

Functions

__init__()

Initialize the problem builder.

Source code in ccdakit/utils/builders.py
def __init__(self) -> None:
    """Initialize the problem builder."""
    self._data: Dict[str, Any] = {}

name(problem_name)

Set problem name.

Parameters:

Name Type Description Default
problem_name str

Human-readable problem name

required

Returns:

Type Description
SimpleProblemBuilder

Self for method chaining

Source code in ccdakit/utils/builders.py
def name(self, problem_name: str) -> "SimpleProblemBuilder":
    """Set problem name.

    Args:
        problem_name: Human-readable problem name

    Returns:
        Self for method chaining
    """
    self._data["name"] = problem_name
    return self

code(code, code_system)

Set problem code and code system.

Parameters:

Name Type Description Default
code str

Problem code (SNOMED CT or ICD-10)

required
code_system str

Code system name ('SNOMED' or 'ICD-10')

required

Returns:

Type Description
SimpleProblemBuilder

Self for method chaining

Source code in ccdakit/utils/builders.py
def code(self, code: str, code_system: str) -> "SimpleProblemBuilder":
    """Set problem code and code system.

    Args:
        code: Problem code (SNOMED CT or ICD-10)
        code_system: Code system name ('SNOMED' or 'ICD-10')

    Returns:
        Self for method chaining
    """
    self._data["code"] = code
    self._data["code_system"] = code_system
    return self

status(status)

Set problem status.

Parameters:

Name Type Description Default
status str

Status ('active', 'inactive', 'resolved')

required

Returns:

Type Description
SimpleProblemBuilder

Self for method chaining

Source code in ccdakit/utils/builders.py
def status(self, status: str) -> "SimpleProblemBuilder":
    """Set problem status.

    Args:
        status: Status ('active', 'inactive', 'resolved')

    Returns:
        Self for method chaining
    """
    self._data["status"] = status
    return self

onset_date(onset)

Set onset date.

Parameters:

Name Type Description Default
onset date

Date problem was identified/started

required

Returns:

Type Description
SimpleProblemBuilder

Self for method chaining

Source code in ccdakit/utils/builders.py
def onset_date(self, onset: date) -> "SimpleProblemBuilder":
    """Set onset date.

    Args:
        onset: Date problem was identified/started

    Returns:
        Self for method chaining
    """
    self._data["onset_date"] = onset
    return self

resolved_date(resolved)

Set resolved date.

Parameters:

Name Type Description Default
resolved date

Date problem was resolved

required

Returns:

Type Description
SimpleProblemBuilder

Self for method chaining

Source code in ccdakit/utils/builders.py
def resolved_date(self, resolved: date) -> "SimpleProblemBuilder":
    """Set resolved date.

    Args:
        resolved: Date problem was resolved

    Returns:
        Self for method chaining
    """
    self._data["resolved_date"] = resolved
    return self

persistent_id(root, extension)

Set persistent identifier.

Parameters:

Name Type Description Default
root str

OID or UUID identifying the assigning authority

required
extension str

Unique identifier within the root's namespace

required

Returns:

Type Description
SimpleProblemBuilder

Self for method chaining

Source code in ccdakit/utils/builders.py
def persistent_id(self, root: str, extension: str) -> "SimpleProblemBuilder":
    """Set persistent identifier.

    Args:
        root: OID or UUID identifying the assigning authority
        extension: Unique identifier within the root's namespace

    Returns:
        Self for method chaining
    """
    self._data["persistent_id"] = {"root": root, "extension": extension}
    return self

build()

Build problem data dictionary.

Returns:

Type Description
Dict[str, Any]

Dictionary containing all problem data

Source code in ccdakit/utils/builders.py
def build(self) -> Dict[str, Any]:
    """Build problem data dictionary.

    Returns:
        Dictionary containing all problem data
    """
    return self._data.copy()

SimpleMedicationBuilder

Fluent API for building medication data that satisfies MedicationProtocol.

Example

medication = ( ... SimpleMedicationBuilder() ... .name("Lisinopril 10mg oral tablet") ... .code("314076") # RxNorm code ... .dosage("10 mg") ... .route("oral") ... .frequency("once daily") ... .start_date(date(2018, 6, 1)) ... .status("active") ... .instructions("Take in the morning") ... .build() ... )

Source code in ccdakit/utils/builders.py
class SimpleMedicationBuilder:
    """Fluent API for building medication data that satisfies MedicationProtocol.

    Example:
        >>> medication = (
        ...     SimpleMedicationBuilder()
        ...     .name("Lisinopril 10mg oral tablet")
        ...     .code("314076")  # RxNorm code
        ...     .dosage("10 mg")
        ...     .route("oral")
        ...     .frequency("once daily")
        ...     .start_date(date(2018, 6, 1))
        ...     .status("active")
        ...     .instructions("Take in the morning")
        ...     .build()
        ... )
    """

    def __init__(self) -> None:
        """Initialize the medication builder."""
        self._data: Dict[str, Any] = {}

    def name(self, medication_name: str) -> "SimpleMedicationBuilder":
        """Set medication name.

        Args:
            medication_name: Human-readable medication name

        Returns:
            Self for method chaining
        """
        self._data["name"] = medication_name
        return self

    def code(self, rxnorm_code: str) -> "SimpleMedicationBuilder":
        """Set RxNorm code.

        Args:
            rxnorm_code: RxNorm code for the medication

        Returns:
            Self for method chaining
        """
        self._data["code"] = rxnorm_code
        return self

    def dosage(self, dosage_amount: str) -> "SimpleMedicationBuilder":
        """Set dosage.

        Args:
            dosage_amount: Dosage amount (e.g., "10 mg", "1 tablet")

        Returns:
            Self for method chaining
        """
        self._data["dosage"] = dosage_amount
        return self

    def route(self, route_of_admin: str) -> "SimpleMedicationBuilder":
        """Set route of administration.

        Args:
            route_of_admin: Route (e.g., "oral", "IV", "topical")

        Returns:
            Self for method chaining
        """
        self._data["route"] = route_of_admin
        return self

    def frequency(self, freq: str) -> "SimpleMedicationBuilder":
        """Set frequency of administration.

        Args:
            freq: Frequency (e.g., "twice daily", "every 6 hours")

        Returns:
            Self for method chaining
        """
        self._data["frequency"] = freq
        return self

    def start_date(self, start: date) -> "SimpleMedicationBuilder":
        """Set start date.

        Args:
            start: Date medication was started

        Returns:
            Self for method chaining
        """
        self._data["start_date"] = start
        return self

    def end_date(self, end: date) -> "SimpleMedicationBuilder":
        """Set end date.

        Args:
            end: Date medication was stopped

        Returns:
            Self for method chaining
        """
        self._data["end_date"] = end
        return self

    def status(self, status: str) -> "SimpleMedicationBuilder":
        """Set medication status.

        Args:
            status: Status ('active', 'completed', 'discontinued')

        Returns:
            Self for method chaining
        """
        self._data["status"] = status
        return self

    def instructions(self, patient_instructions: str) -> "SimpleMedicationBuilder":
        """Set patient instructions.

        Args:
            patient_instructions: Instructions for patient

        Returns:
            Self for method chaining
        """
        self._data["instructions"] = patient_instructions
        return self

    def build(self) -> Dict[str, Any]:
        """Build medication data dictionary.

        Returns:
            Dictionary containing all medication data
        """
        return self._data.copy()

Functions

__init__()

Initialize the medication builder.

Source code in ccdakit/utils/builders.py
def __init__(self) -> None:
    """Initialize the medication builder."""
    self._data: Dict[str, Any] = {}

name(medication_name)

Set medication name.

Parameters:

Name Type Description Default
medication_name str

Human-readable medication name

required

Returns:

Type Description
SimpleMedicationBuilder

Self for method chaining

Source code in ccdakit/utils/builders.py
def name(self, medication_name: str) -> "SimpleMedicationBuilder":
    """Set medication name.

    Args:
        medication_name: Human-readable medication name

    Returns:
        Self for method chaining
    """
    self._data["name"] = medication_name
    return self

code(rxnorm_code)

Set RxNorm code.

Parameters:

Name Type Description Default
rxnorm_code str

RxNorm code for the medication

required

Returns:

Type Description
SimpleMedicationBuilder

Self for method chaining

Source code in ccdakit/utils/builders.py
def code(self, rxnorm_code: str) -> "SimpleMedicationBuilder":
    """Set RxNorm code.

    Args:
        rxnorm_code: RxNorm code for the medication

    Returns:
        Self for method chaining
    """
    self._data["code"] = rxnorm_code
    return self

dosage(dosage_amount)

Set dosage.

Parameters:

Name Type Description Default
dosage_amount str

Dosage amount (e.g., "10 mg", "1 tablet")

required

Returns:

Type Description
SimpleMedicationBuilder

Self for method chaining

Source code in ccdakit/utils/builders.py
def dosage(self, dosage_amount: str) -> "SimpleMedicationBuilder":
    """Set dosage.

    Args:
        dosage_amount: Dosage amount (e.g., "10 mg", "1 tablet")

    Returns:
        Self for method chaining
    """
    self._data["dosage"] = dosage_amount
    return self

route(route_of_admin)

Set route of administration.

Parameters:

Name Type Description Default
route_of_admin str

Route (e.g., "oral", "IV", "topical")

required

Returns:

Type Description
SimpleMedicationBuilder

Self for method chaining

Source code in ccdakit/utils/builders.py
def route(self, route_of_admin: str) -> "SimpleMedicationBuilder":
    """Set route of administration.

    Args:
        route_of_admin: Route (e.g., "oral", "IV", "topical")

    Returns:
        Self for method chaining
    """
    self._data["route"] = route_of_admin
    return self

frequency(freq)

Set frequency of administration.

Parameters:

Name Type Description Default
freq str

Frequency (e.g., "twice daily", "every 6 hours")

required

Returns:

Type Description
SimpleMedicationBuilder

Self for method chaining

Source code in ccdakit/utils/builders.py
def frequency(self, freq: str) -> "SimpleMedicationBuilder":
    """Set frequency of administration.

    Args:
        freq: Frequency (e.g., "twice daily", "every 6 hours")

    Returns:
        Self for method chaining
    """
    self._data["frequency"] = freq
    return self

start_date(start)

Set start date.

Parameters:

Name Type Description Default
start date

Date medication was started

required

Returns:

Type Description
SimpleMedicationBuilder

Self for method chaining

Source code in ccdakit/utils/builders.py
def start_date(self, start: date) -> "SimpleMedicationBuilder":
    """Set start date.

    Args:
        start: Date medication was started

    Returns:
        Self for method chaining
    """
    self._data["start_date"] = start
    return self

end_date(end)

Set end date.

Parameters:

Name Type Description Default
end date

Date medication was stopped

required

Returns:

Type Description
SimpleMedicationBuilder

Self for method chaining

Source code in ccdakit/utils/builders.py
def end_date(self, end: date) -> "SimpleMedicationBuilder":
    """Set end date.

    Args:
        end: Date medication was stopped

    Returns:
        Self for method chaining
    """
    self._data["end_date"] = end
    return self

status(status)

Set medication status.

Parameters:

Name Type Description Default
status str

Status ('active', 'completed', 'discontinued')

required

Returns:

Type Description
SimpleMedicationBuilder

Self for method chaining

Source code in ccdakit/utils/builders.py
def status(self, status: str) -> "SimpleMedicationBuilder":
    """Set medication status.

    Args:
        status: Status ('active', 'completed', 'discontinued')

    Returns:
        Self for method chaining
    """
    self._data["status"] = status
    return self

instructions(patient_instructions)

Set patient instructions.

Parameters:

Name Type Description Default
patient_instructions str

Instructions for patient

required

Returns:

Type Description
SimpleMedicationBuilder

Self for method chaining

Source code in ccdakit/utils/builders.py
def instructions(self, patient_instructions: str) -> "SimpleMedicationBuilder":
    """Set patient instructions.

    Args:
        patient_instructions: Instructions for patient

    Returns:
        Self for method chaining
    """
    self._data["instructions"] = patient_instructions
    return self

build()

Build medication data dictionary.

Returns:

Type Description
Dict[str, Any]

Dictionary containing all medication data

Source code in ccdakit/utils/builders.py
def build(self) -> Dict[str, Any]:
    """Build medication data dictionary.

    Returns:
        Dictionary containing all medication data
    """
    return self._data.copy()

Converters

Conversion utilities are available in ccdakit.utils.converters module.

Templates

Template utilities are available in ccdakit.utils.templates module.

Factories

Factory utilities are available in ccdakit.utils.factories module.

See the source code for detailed documentation of these utility modules.