-
Notifications
You must be signed in to change notification settings - Fork 5
/
fhirspec.py
2256 lines (1941 loc) · 78.9 KB
/
fhirspec.py
1
2
3
4
5
6
7
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
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""Python representation of FHIR® https://www.hl7.org/fhir/ specification.
Idea and class structure based on https://github.com/smart-on-fhir/fhir-parser.
"""
import datetime
import enum
import importlib
import inspect
import io
import json
import logging
import mimetypes
import os
import pathlib
import re
import types
import typing
from ast import literal_eval
from collections import defaultdict
from http.client import HTTPResponse
from typing import (
Any,
DefaultDict,
Dict,
ItemsView,
Iterable,
List,
Optional,
Sequence,
Set,
Tuple,
Union,
)
from urllib.error import HTTPError
from urllib.parse import urlparse
from urllib.request import Request, urlopen
__version__ = "0.4.0"
__author__ = "Md Nazrul Islam <[email protected]>"
__all__ = ["Configuration", "FHIRSpec", "download", "filename_from_response"]
# --*-- Enums
class FHIR_RELEASES(str, enum.Enum):
""" """
R5 = "R5"
R4 = "R4"
R4B = "R4B"
STU3 = "STU3"
class FHIR_CLASS_TYPES(str, enum.Enum):
""" """
resource = "resource"
complex_type = "complex_type"
primitive_type = "primitive_type"
logical = "logical"
other = "other"
# --*-- Variables
LOGGER = logging.getLogger(__name__)
FHIR_VERSIONS_MAP = {
"3.0.0": FHIR_RELEASES.STU3,
"3.0.1": FHIR_RELEASES.STU3,
"3.0.2": FHIR_RELEASES.STU3,
"4.0.0": FHIR_RELEASES.R4,
"4.0.1": FHIR_RELEASES.R4,
"4.3.0": FHIR_RELEASES.R4B,
}
HTTP_URL = re.compile(r"^https?://", re.IGNORECASE)
UNSUPPORTED_PROFILES = [r"SimpleQuantity"]
# --*-- Classes
class ConfigurationVariable:
""" """
name: str
required: bool
type_: Any
class Configuration:
"""Simple Configuration Class"""
_initialized: bool
__storage__: DefaultDict[str, Any]
__slots__ = ("__storage__", "_initialized")
def __init__(
self, data_dict: Dict[str, Any], path_variables: Optional[List[str]] = None
):
""" """
object.__setattr__(self, "__storage__", defaultdict())
object.__setattr__(self, "_initialized", False)
self.init(data_dict)
object.__setattr__(self, "_initialized", True)
self.validate(["BASE_PATH"])
self.normalize_paths(path_variables)
@classmethod
def from_module(cls, mod: types.ModuleType) -> "Configuration":
""" """
data_dict = mod.__dict__.copy()
return cls(data_dict)
@classmethod
def from_json_file(cls, file: pathlib.Path) -> "Configuration":
""" """
assert file.is_file() and file.exists()
try:
# json5 supported
from json5 import load as j_load
except ImportError:
if file.suffix == ".json5":
raise
j_load = json.load
with open(str(file), "r", encoding="utf-8") as fp:
data_dict = j_load(fp)
assert isinstance(data_dict, dict)
return cls(data_dict)
@classmethod
def from_text_file(cls, file: pathlib.Path) -> "Configuration":
"""KEY=VALUE formatted variables
@todo: dict type value by dotted path?
"""
assert file.is_file() and file.exists()
data_dict: Dict[str, Any] = dict()
with open(str(file), "r", encoding="utf-8") as fp:
for line in fp:
ln = line.strip()
if not ln or ln.startswith("#") or "=" not in ln:
continue
key, val = ln.split("=", 1)
key = key.strip()
if not key.isupper() or not val:
continue
values: List[str] = list(map(lambda x: x.strip(), val.split(",")))
if len(values) == 1:
data_dict[key] = values[0]
else:
data_dict[key] = values
return cls(data_dict)
@classmethod
def from_cfg_file(cls, filepath: pathlib.Path) -> None:
""" """
assert filepath.is_file() and filepath.suffix in (".cfg", ".ini")
@classmethod
def from_toml_file(cls, filepath: pathlib.Path) -> "Configuration":
""" """
import pytoml as toml
assert filepath.is_file() and filepath.suffix == ".toml"
with open(str(filepath), "r", encoding="utf-8") as fp:
data = toml.load(fp)
return cls(data_dict=data)
def init(self, data_dict: Dict[str, Any]) -> None:
""" """
init_ = object.__getattribute__(self, "_initialized")
if init_ is True:
raise ValueError("Instance has already be initialized!")
def _add(items: ItemsView[str, Any]) -> None:
""" """
for key, val in items:
if key.isupper() is False:
continue
setattr(self, key, val)
_add(data_dict.items())
def normalize_paths(self, path_variables: Optional[List[str]] = None) -> None:
""" """
init_ = object.__getattribute__(self, "_initialized")
if init_ is False:
raise ValueError("Instance has must be initialized!")
storage = object.__getattribute__(self, "__storage__")
base_path = storage["BASE_PATH"]
if not isinstance(base_path, pathlib.PurePath):
base_path = resolve_path(base_path, None)
storage["BASE_PATH"] = base_path
paths = [
"CACHE_PATH",
"RESOURCE_TARGET_DIRECTORY",
"DEPENDENCIES_TARGET_FILE_NAME",
"UNITTEST_TARGET_DIRECTORY",
"UNITTEST_COPY_FILES",
]
if path_variables is not None:
paths.extend(path_variables)
for np in paths:
if np not in storage:
continue
val = storage[np]
if isinstance(val, list):
new_val = list()
for p in val:
if isinstance(p, pathlib.PurePath):
new_val.append(p)
else:
new_val.append(resolve_path(p, base_path))
storage[np] = new_val
else:
if not isinstance(val, pathlib.PurePath):
storage[np] = resolve_path(val, base_path)
# take care of manual profiles
new_profiles = list()
for path, mod_name, values in storage["MANUAL_PROFILES"]:
if not isinstance(path, pathlib.PurePath):
path = resolve_path(path, base_path)
new_profiles.append((path, mod_name, values))
storage["MANUAL_PROFILES"] = new_profiles
def validate(self, required_variables: List[str]) -> None:
"""XXX: variable could include with value type(s) and required flag"""
missing: List[str] = list()
for v in required_variables:
if v not in self.__storage__:
missing.append(v)
if len(missing) > 0:
raise ValueError(f"{missing} variable(s) are missing!")
def as_dict(self) -> defaultdict:
""" """
init_ = object.__getattribute__(self, "_initialized")
if init_ is False:
raise ValueError("Instance has must be initialized!")
storage = object.__getattribute__(self, "__storage__")
return storage.copy()
def update(self, data_dict: Dict[str, Any]) -> None:
""" """
init_ = object.__getattribute__(self, "_initialized")
if init_ is False:
raise ValueError("Instance has must be initialized!")
storage = object.__getattribute__(self, "__storage__")
for key, val in data_dict.items():
if key.isupper():
storage[key] = val
def merge(self, other: "Configuration") -> None:
""" """
storage = object.__getattribute__(self, "__storage__")
storage.update(object.__getattribute__(other, "__storage__").copy())
def __add__(self, other: "Configuration") -> "Configuration":
""" """
data_dict = object.__getattribute__(self, "__storage__").copy()
data_dict.update(object.__getattribute__(other, "__storage__").copy())
return Configuration(data_dict)
def __getitem__(self, item: str) -> Any:
""" """
try:
return self.__storage__[item]
except KeyError:
raise KeyError(f"´{item}´ is not defined in any configuration.")
def __getattr__(self, item: str) -> Any:
""" """
try:
return self.__storage__[item]
except KeyError:
raise AttributeError(f"´{item}´ is not defined in any configuration.")
def __setitem__(self, key: str, value: Any) -> None:
""" """
storage = object.__getattribute__(self, "__storage__")
storage[key] = value
def __setattr__(self, key: str, value: Any) -> None:
""" """
self[key] = value
class FHIRSpec:
"""The FHIR specification."""
_finalized: bool
def __init__(
self, settings: Configuration, src_directory: Optional[pathlib.Path] = None
):
"""
:param src_directory:
:param settings:
"""
self._finalized = False
self.validate_settings(settings)
self.definition_directory: pathlib.Path = typing.cast(
pathlib.Path, getattr(settings, "FHIR_DEFINITION_DIRECTORY", None)
)
self.example_directory: pathlib.Path = typing.cast(
pathlib.Path, getattr(settings, "FHIR_EXAMPLE_DIRECTORY", None)
)
version_info_file: pathlib.Path = typing.cast(
pathlib.Path, getattr(settings, "FHIR_VERSION_INFO_FILE", None)
)
if (
self.definition_directory is None
or self.example_directory is None
or version_info_file is None
) and src_directory is None:
raise ValueError("src_directory is value is required!")
if self.definition_directory is None:
assert src_directory
self.definition_directory = src_directory / "definitions"
if self.example_directory is None:
assert src_directory
self.example_directory = src_directory / "examples"
if version_info_file is None:
assert src_directory
version_info_file = src_directory / "version.info"
self.settings = settings
self.info: FHIRVersionInfo = FHIRVersionInfo(self, version_info_file)
# system-url: FHIRValueSet()
self.valuesets: DefaultDict[str, FHIRValueSet] = defaultdict()
# system-url: FHIRCodeSystem()
self.codesystems: DefaultDict[str, FHIRCodeSystem] = defaultdict()
# profile-name: FHIRStructureDefinition()
self.profiles: DefaultDict[str, FHIRStructureDefinition] = defaultdict()
# FHIRUnitTestCollection()
self.unit_tests: List[FHIRUnitTestCollection] = list()
self.prepare()
self.read_profiles()
self.finalize()
@staticmethod
def validate_settings(settings: Configuration) -> None:
"""
:param settings:
:return:
"""
required_variables = [
"WRITE_RESOURCES",
"CLASS_MAP",
"REPLACE_MAP",
"NATIVES",
"JSON_MAP",
"JSON_MAP_DEFAULT",
"RESERVED_MAP",
"ENUM_MAP",
"ENUM_NAME_MAP",
"DEFAULT_BASES",
"MANUAL_PROFILES",
"CAMELCASE_CLASSES",
"CAMELCASE_ENUMS",
"BACKBONE_CLASS_ADDS_PARENT",
"RESOURCE_MODULE_LOWERCASE",
"FHIR_PRIMITIVES",
]
write_resources = getattr(settings, "WRITE_RESOURCES", False)
if write_resources is True:
required_variables.extend(
[
"TEMPLATE_DIRECTORY",
"RESOURCE_FILE_NAME_PATTERN",
"RESOURCE_TARGET_DIRECTORY",
"RESOURCE_SOURCE_TEMPLATE",
"CODE_SYSTEMS_SOURCE_TEMPLATE",
"CODE_SYSTEMS_TARGET_NAME",
"WRITE_DEPENDENCIES",
"DEPENDENCIES_SOURCE_TEMPLATE",
"DEPENDENCIES_TARGET_FILE_NAME",
"RESOURCE_MODULE_LOWERCASE",
]
)
write_unittests = getattr(settings, "WRITE_UNITTESTS", False)
if write_unittests is True:
required_variables.extend(
[
"UNITTEST_COPY_FILES",
"UNITTEST_FORMAT_PATH_PREPARE",
"UNITTEST_SOURCE_TEMPLATE",
"UNITTEST_TARGET_DIRECTORY",
"UNITTEST_TARGET_FILE_NAME_PATTERN",
"UNITTEST_FORMAT_PATH_KEY",
"UNITTEST_FORMAT_PATH_INDEX",
]
)
settings.validate(required_variables)
if (
settings.WRITE_RESOURCES is True
and getattr(settings, "RESOURCES_WRITER_CLASS", None) is None
):
raise ValueError("Writer class is required, when resources to be written.")
def prepare(self) -> None:
"""Run actions before starting to parse profiles."""
self.read_valuesets()
self.handle_manual_profiles()
def read_bundle_resources(self, filename: str) -> List[Dict[str, Any]]:
"""Return an array of the Bundle's entry's "resource" elements."""
LOGGER.info(f"Reading {filename}")
filepath = self.definition_directory / filename
with open(str(filepath), encoding="utf-8") as handle:
parsed = json.load(handle)
if "resourceType" not in parsed:
raise Exception(
f'Expecting "resourceType" to be present, but is not in {filepath}'
)
if "Bundle" != parsed["resourceType"]:
raise Exception('Can only process "Bundle" resources')
if "entry" not in parsed:
raise Exception(f"There are no entries in the Bundle at {filepath}")
return [e["resource"] for e in parsed["entry"]]
# MARK: Managing ValueSets and CodeSystems
def read_valuesets(self) -> None:
filename = getattr(self.settings, "FHIR_VALUESETS_FILE_NAME", "valuesets.json")
resources = self.read_bundle_resources(filename)
for resource in resources:
if "ValueSet" == resource["resourceType"]:
assert "url" in resource
self.valuesets[resource["url"]] = FHIRValueSet(self, resource)
elif "CodeSystem" == resource["resourceType"]:
assert "url" in resource
if "content" in resource and "concept" in resource:
self.codesystems[resource["url"]] = FHIRCodeSystem(self, resource)
else:
LOGGER.warning(f"CodeSystem with no concepts: {resource['url']}")
LOGGER.info(
f"Found {len(self.valuesets)} ValueSets and "
f"{len(self.codesystems)} CodeSystems"
)
def valueset_with_uri(self, uri: str) -> Optional["FHIRValueSet"]:
"""
:param uri:
:return: FHIRValueSetType
"""
try:
return self.valuesets[uri]
except KeyError:
# raise NotImplementedError
LOGGER.warning(f"NotImplementedError could not find valuesets for {uri}")
return None
def codesystem_with_uri(self, uri: str) -> Optional["FHIRCodeSystem"]:
"""
:param uri:
:return: FHIRCodeSystem
"""
try:
return self.codesystems[uri]
except KeyError:
# raise NotImplementedError
LOGGER.warning(f"NotImplementedError could not find codesystem for {uri}")
return None
# MARK: Handling Profiles
def read_profiles(self) -> None:
"""Find all (JSON) profiles and instantiate into FHIRStructureDefinition."""
resources = []
files = getattr(
self.settings,
"FHIR_PROFILES_FILE_NAMES",
["profiles-types.json", "profiles-resources.json"],
)
for filename in files:
bundle_res = self.read_bundle_resources(filename)
for resource in bundle_res:
if "StructureDefinition" == resource["resourceType"]:
resources.append(resource)
else:
LOGGER.debug(
f"Not handling resource of type {resource['resourceType']}"
)
# create profile instances
for resource in resources:
profile: FHIRStructureDefinition = FHIRStructureDefinition(self, resource)
for pattern in UNSUPPORTED_PROFILES:
assert isinstance(profile.url, str)
if re.search(pattern, profile.url) is not None:
LOGGER.info(f'Skipping "{resource["url"]}"')
continue
if self.found_profile(profile):
profile.process_profile()
def found_profile(self, profile: "FHIRStructureDefinition") -> bool:
if not profile or not profile.name:
raise Exception(f"No name for profile {profile}")
if profile.name.lower() in self.profiles:
LOGGER.debug(f'Already have profile "{profile.name}", discarding')
return False
self.profiles[profile.name.lower()] = profile
return True
def handle_manual_profiles(self) -> None:
"""Creates in-memory representations for all our manually defined
profiles.
"""
for filepath, module, contains in self.settings.MANUAL_PROFILES:
for contained in contains:
profile: FHIRStructureDefinition = FHIRStructureDefinition(self, None)
profile.is_manual = True
prof_dict = {
"name": contained,
"differential": {"element": [{"path": contained}]},
}
if module == "fhirtypes":
profile_name = self.class_name_for_profile(contained)
assert isinstance(profile_name, str)
if self.class_name_is_primitive(profile_name):
prof_dict["kind"] = "primitive-type"
profile.structure = FHIRStructureDefinitionStructure(profile, prof_dict)
if self.found_profile(profile):
profile.process_profile()
def finalize(self) -> None:
"""Should be called after all profiles have been parsed and allows
to perform additional actions, like looking up class implementations
from different profiles.
"""
if self._finalized is True:
raise ValueError("Specification is already been finalized!")
# self.profiles['meta'].structure.snapshot[-1]
for key, prof in self.profiles.items():
prof.finalize()
if len(prof.elements_sequences) == 0:
for item in prof.structure.snapshot[1:]:
prof.elements_sequences.append(item["id"].split(".")[1])
if self.settings.WRITE_UNITTESTS:
self.parse_unit_tests()
self._finalized = True
@property
def finalized(self) -> bool:
return self._finalized
# MARK: Naming Utilities
def as_module_name(self, name: str) -> str:
if self.class_name_is_primitive(name):
return "fhirtypes"
return (
name.lower() if name and self.settings.RESOURCE_MODULE_LOWERCASE else name
)
def as_class_name(
self, classname: str, parent_name: Optional[str] = None
) -> Union[str, None]:
"""
:param classname:
:param parent_name:
:return: str | None
"""
if not classname or 0 == len(classname):
return None
# if we have a parent, do we have a mapped class?
pathname = (
"{0}.{1}".format(parent_name, classname)
if parent_name is not None
else None
)
if pathname is not None and pathname in self.settings.CLASS_MAP:
return self.settings.CLASS_MAP[pathname]
# is our plain class mapped?
if classname in self.settings.CLASS_MAP:
return self.settings.CLASS_MAP[classname]
# CamelCase or just plain
if self.settings.CAMELCASE_CLASSES:
return classname[:1].upper() + classname[1:]
return classname
def class_name_for_type(
self, type_name: str, parent_name: Optional[str] = None
) -> Union[str, None]:
"""
:param type_name:
:param parent_name:
:return: str or None
"""
return self.as_class_name(type_name, parent_name)
def class_name_for_type_if_property(self, type_name: str) -> Union[str, None]:
"""
:param type_name:
:return: str | None
"""
classname = self.class_name_for_type(type_name)
if not classname:
return None
return self.settings.REPLACE_MAP.get(classname, classname)
def class_name_for_profile(
self, profile_name: Union[str, List[str]]
) -> Union[str, List[str], None]:
if not profile_name:
return None
# TODO need to figure out what to do with this later.
# Annotation author supports multiples types that caused this to fail
if isinstance(profile_name, (list,)) and len(profile_name) > 0:
classnames: List[str] = []
for p_name in profile_name:
cls_name = self.class_name_for_profile(p_name)
if isinstance(cls_name, str):
classnames.append(cls_name)
return classnames
# may be the full Profile URI,
# like http://hl7.org/fhir/Profile/MyProfile
if isinstance(profile_name, str):
type_name = profile_name.split("/")[-1]
else:
raise NotImplementedError
return self.as_class_name(type_name)
def class_name_is_native(self, class_name: str) -> bool:
"""
:param class_name:
:return: bool
"""
return class_name in self.settings.NATIVES
def class_name_is_primitive(self, class_name: str) -> bool:
"""
:param class_name:
:return: bool
"""
for typ in self.settings.FHIR_PRIMITIVES:
if typ.lower() == class_name.lower():
return True
return False
def safe_property_name(self, prop_name: str) -> str:
"""
:param prop_name:
:return:
"""
return self.settings.RESERVED_MAP.get(prop_name, prop_name)
def safe_enum_name(self, enum_name: str, ucfirst: bool = False) -> str:
assert enum_name, "Must have a name"
name = self.settings.ENUM_MAP.get(enum_name, enum_name)
parts = re.split(r"\W+", name)
if self.settings.CAMELCASE_ENUMS:
name = "".join([n[:1].upper() + n[1:] for n in parts])
if not ucfirst and name.upper() != name:
name = name[:1].lower() + name[1:]
else:
name = "_".join(parts)
return self.settings.RESERVED_MAP.get(name, name)
def json_class_for_class_name(self, class_name: str) -> str:
"""
:param class_name:
:return: str
"""
return self.settings.JSON_MAP.get(class_name, self.settings.JSON_MAP_DEFAULT)
# MARK: Unit Tests
def parse_unit_tests(self) -> None:
controller: FHIRUnitTestController = FHIRUnitTestController(self)
controller.find_and_parse_tests(self.example_directory)
self.unit_tests = controller.collections
# MARK: Writing Data
def writable_profiles(self) -> List["FHIRStructureDefinition"]:
"""Returns a list of `FHIRStructureDefinition` instances."""
profiles = []
for key, profile in self.profiles.items():
if not profile.is_manual:
profiles.append(profile)
return profiles
def write(self) -> None:
""" """
klass = self.settings.RESOURCES_WRITER_CLASS
if isinstance(klass, str):
parts = klass.split(".")
assert len(parts) > 1
klass_name = parts[-1]
module_name = ".".join(parts[:-1])
factory = getattr(importlib.import_module(module_name), klass_name)
else:
factory = klass
assert inspect.isclass(factory)
assert issubclass(factory, FHIRSpecWriter)
writer = factory(self)
return writer.write()
class FHIRSpecWriter:
""" """
def __init__(self, spec: FHIRSpec):
""" """
if spec.finalized is not True:
raise ValueError(
"Specification must be in finalized state, ready to write."
)
self.spec = spec
self.settings = spec.settings
def write(self) -> None:
""" """
raise NotImplementedError
class FHIRVersionInfo:
"""The version of a FHIR specification."""
def __init__(self, spec: FHIRSpec, info_file: pathlib.Path):
self.spec = spec
now = datetime.date.today()
self.date = now.isoformat()
self.year = now.year
self.version: Optional[str] = None
self.version_raw: Optional[str] = None
self.build: Optional[str] = None
self.revision: Optional[str] = None
self.read_version(info_file)
def read_version(self, filepath: pathlib.Path) -> None:
assert filepath.is_file()
with open(str(filepath), "r", encoding="utf-8") as handle:
text = handle.read()
for line in text.split("\n"):
if "=" in line:
(n, v) = line.strip().split("=", 2)
if "FhirVersion" == n:
self.version_raw = v
elif "version" == n:
self.version = v
elif "buildId" == n:
self.build = v
elif "revision" == n:
self.revision = v
class FHIRValueSet:
"""Holds on to ValueSets bundled with the spec."""
def __init__(self, spec: FHIRSpec, set_dict: Dict[str, Any]):
"""
:param spec:
:param set_dict:
"""
self.spec = spec
self.definition = set_dict
self._enum: Dict[str, Union[str, None, List]] = dict()
@property
def enum(self) -> Union[None, Dict[str, Union[str, List[str], None]]]:
"""Returns FHIRCodeSystem if this valueset can be represented by one."""
if len(self._enum) > 0:
return self._enum
compose = self.definition.get("compose")
if compose is None:
raise Exception("Currently only composed ValueSets are supported")
if "exclude" in compose:
raise Exception("Not currently supporting 'exclude' on ValueSet")
include = compose.get("include")
if 1 != len(include):
LOGGER.warning(
f"Ignoring ValueSet ({self.definition['url']}) with more than "
f"1 includes ({len(include)}: {include})"
)
return None
system = include[0].get("system")
if system is None:
return None
# alright, this is a ValueSet with 1 include and
# a system, is there a CodeSystem?
cs: Optional[FHIRCodeSystem] = self.spec.codesystem_with_uri(system)
if cs is None or not cs.generate_enum:
return None
# do we only allow specific concepts?
restricted_to = []
concepts = include[0].get("concept")
if concepts is not None:
for concept in concepts:
assert "code" in concept
restricted_to.append(concept["code"])
self._enum = {
"name": cs.name,
"restricted_to": restricted_to if len(restricted_to) > 0 else None,
}
return self._enum
class FHIRCodeSystem:
"""Holds on to CodeSystems bundled with the spec."""
def __init__(self, spec: FHIRSpec, resource: Dict[str, Any]):
"""
:param spec:
:param resource:
"""
assert "content" in resource
self.spec = spec
self.definition = resource
self.url = resource.get("url")
if self.url in self.spec.settings.ENUM_NAME_MAP:
self.name = self.spec.settings.ENUM_NAME_MAP[self.url]
else:
self.name = self.spec.safe_enum_name(resource["name"], ucfirst=True)
self.codes = None
self.generate_enum = False
concepts = self.definition.get("concept", [])
if resource.get("experimental"):
return
self.generate_enum = "complete" == resource["content"]
if not self.generate_enum:
LOGGER.debug(
"Will not generate enum for CodeSystem "
f'"{self.url}" whose content is {resource["content"]}'
)
return
assert concepts, 'Expecting at least one code for "complete" CodeSystem'
if len(concepts) > 200:
self.generate_enum = False
LOGGER.info(
"Will not generate enum for CodeSystem "
f'"{self.url}" because it has > 200 ({len(concepts)}) concepts.'
)
return
self.codes = self.parsed_codes(concepts)
def parsed_codes(
self, codes: Sequence[Dict[str, Any]], prefix: Optional[str] = None
) -> List[Dict[str, Any]]:
"""
:param codes:
:param prefix:
:return:
"""
found: List[Dict[str, Any]] = []
for c in codes:
if re.match(r"\d", c["code"][:1]):
self.generate_enum = False
LOGGER.info(
f'Will not generate enum for CodeSystem "{self.url}" '
"because at least one concept code starts with a number"
)
return found
cd = c["code"]
name = ( # noqa: F841
"{}-{}".format(prefix, cd)
if prefix and not cd.startswith(prefix)
else cd
)
c["name"] = self.spec.safe_enum_name(cd)
c["definition"] = c.get("definition") or c["name"]
found.append(c)
# nested concepts?
if "concept" in c:
fnd = self.parsed_codes(c["concept"])
if fnd is None:
return found
found.extend(fnd)
return found
class FHIRStructureDefinition:
"""One FHIR structure definition."""
def __init__(self, spec: FHIRSpec, profile: Optional[Dict[str, Any]]):
self.is_manual: bool = False
# FHIRStructureDefinitionStructure()
self.structure: FHIRStructureDefinitionStructure
self.spec: FHIRSpec = spec
self.url: Optional[str] = None
self.targetname: Optional[str] = None
# List of FHIRStructureDefinitionElement
self.elements: List[FHIRStructureDefinitionElement] = list()
self.main_element: Optional[FHIRStructureDefinitionElement] = None
# xxx: if ._class_map is required
# self._class_map: Dict[str, str] = dict()
self.classes: List[FHIRClass] = list()
self._did_finalize: bool = False
self.fhir_version: Optional[str] = None
self.fhir_last_updated: Optional[str] = None
self.elements_sequences: List[str] = list()
if profile is not None:
self.parse_profile(profile)
@property
def name(self) -> Union[str, None]:
return self.structure.name if self.structure is not None else None
def read_profile(self, filepath: pathlib.Path) -> None:
"""Read the JSON definition of a profile from disk and parse.
Not currently used.
"""
with open(str(filepath), "r", encoding="utf-8") as handle:
profile = json.load(handle)
self.parse_profile(profile)
def parse_profile(self, profile: Dict[str, Any]) -> None:
"""Parse a JSON profile into a structure."""
assert profile
assert "StructureDefinition" == profile["resourceType"]
# parse structure
self.url = profile.get("url")
self.fhir_version = profile.get("fhirVersion")
self.fhir_last_updated = profile.get("meta", {}).get("lastUpdated")
LOGGER.info('Parsing profile "{}"'.format(profile.get("name")))
self.structure = FHIRStructureDefinitionStructure(self, profile)
def process_profile(self) -> None:
"""Extract all elements and create classes."""
# or self.structure.snapshot
struct = self.structure.differential
if struct is not None:
mapped = {}
for elem_dict in struct:
element: FHIRStructureDefinitionElement = (
FHIRStructureDefinitionElement( # noqa: E501
self, elem_dict, self.main_element is None
)
)
self.elements.append(element)
mapped[element.path] = element
# establish hierarchy (may move to extra
# loop in case elements are no longer in order)
if element.is_main_profile_element:
self.main_element = element
parent = mapped.get(element.parent_name)
if parent:
parent.add_child(element)
# resolve element dependencies
for element in self.elements:
element.resolve_dependencies()
# run check: if n_min > 0 and parent is in summary, must also be in summary
for element in self.elements:
if element.n_min is not None and element.n_min > 0:
if (
element.parent is not None
and element.parent.is_summary
and not element.is_summary
):
LOGGER.error(
"n_min > 0 but not summary: `{}`".format(element.path)
)
element.summary_n_min_conflict = True
# create classes and class properties
if self.main_element is not None:
snap_class, subs = self.main_element.create_class()
if snap_class is None:
raise Exception(
f'The main element for "{self.url}" did not create a class'
)
self.found_class(snap_class)
if subs is not None: