-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathschemaview.py
1902 lines (1667 loc) · 71.3 KB
/
schemaview.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
import os
import uuid
import logging
import collections
from functools import lru_cache
from copy import copy, deepcopy
from collections import defaultdict, deque
from pathlib import Path
from typing import Mapping, Tuple, TypeVar
import warnings
from linkml_runtime.utils.namespaces import Namespaces
from deprecated.classic import deprecated
from linkml_runtime.utils.context_utils import parse_import_map, map_import
from linkml_runtime.utils.formatutils import is_empty
from linkml_runtime.utils.pattern import PatternResolver
from linkml_runtime.linkml_model.meta import *
from linkml_runtime.exceptions import OrderingError
from enum import Enum
logger = logging.getLogger(__name__)
MAPPING_TYPE = str ## e.g. broad, exact, related, ...
CACHE_SIZE = 1024
SLOTS = 'slots'
CLASSES = 'classes'
ENUMS = 'enums'
SUBSETS = 'subsets'
TYPES = 'types'
CLASS_NAME = Union[ClassDefinitionName, str]
SLOT_NAME = Union[SlotDefinitionName, str]
SUBSET_NAME = Union[SubsetDefinitionName, str]
TYPE_NAME = Union[TypeDefinitionName, str]
ENUM_NAME = Union[EnumDefinitionName, str]
ElementType = TypeVar("ElementType", bound=Element)
ElementNameType = TypeVar("ElementNameType", bound=Union[ElementName,str])
DefinitionType = TypeVar("DefinitionType", bound=Definition)
DefinitionNameType = TypeVar("DefinitionNameType", bound=Union[DefinitionName,str])
ElementDict = Dict[ElementNameType, ElementType]
DefDict = Dict[DefinitionNameType, DefinitionType]
class OrderedBy(Enum):
RANK = "rank"
LEXICAL = "lexical"
PRESERVE = "preserve"
INHERITANCE = "inheritance"
"""
Order according to inheritance such that if C is a child of P then C appears after P
"""
def _closure(f, x, reflexive=True, depth_first=True, **kwargs):
if reflexive:
rv = [x]
else:
rv = []
visited = []
todo = [x]
while len(todo) > 0:
if depth_first:
i = todo.pop()
else:
i = todo[0]
todo = todo[1:]
visited.append(i)
vals = f(i)
if vals is not None:
for v in vals:
if v not in visited and v not in rv:
todo.append(v)
rv.append(v)
return rv
def load_schema_wrap(path: str, **kwargs):
# import here to avoid circular imports
from linkml_runtime.loaders.yaml_loader import YAMLLoader
yaml_loader = YAMLLoader()
schema: SchemaDefinition
schema = yaml_loader.load(path, target_class=SchemaDefinition, **kwargs)
if "\n" not in path:
# if "\n" not in path and "://" not in path:
# only set path if the input is not a yaml string or URL.
# Setting the source path is necessary for relative imports;
# while initializing a schema with a yaml string is possible, there
# should be no expectation of relative imports working.
schema.source_file = path
return schema
def is_absolute_path(path: str) -> bool:
if path.startswith("/"):
return True
# windows
if not os.path.isabs(path):
return False
norm_path = os.path.normpath(path)
if norm_path.startswith("\\\\") or ":" not in norm_path:
return False
drive, tail = os.path.splitdrive(norm_path)
return bool(drive and tail)
@dataclass
class SchemaUsage():
"""
A usage of an element of a schema
"""
used_by: ElementName
slot: SlotDefinitionName
metaslot: SlotDefinitionName
used: ElementName
inferred: bool = None
@dataclass
class SchemaView(object):
"""
A SchemaView provides a virtual schema layered on top of a schema plus its import closure
Most operations are parameterized by `imports`. If this is set to True (default), then the full
import closure is considered when answering
This class utilizes caching for efficient lookup operations.
TODO: decide how to use this in conjunction with the existing schemaloader, which injects
into the schema rather than providing dynamic methods.
See:
- https://github.com/linkml/linkml/issues/59
- https://github.com/linkml/linkml/discussions/144
- https://github.com/linkml/linkml/issues/48
- https://github.com/linkml/linkml/issues/270
"""
schema: SchemaDefinition = None
schema_map: Dict[SchemaDefinitionName, SchemaDefinition] = None
importmap: Optional[Mapping[str, str]] = None
"""Optional mapping between schema names and local paths/URLs"""
modifications: int = 0
uuid: str = None
def __init__(self, schema: Union[str, Path, SchemaDefinition],
importmap: Optional[Dict[str, str]] = None, merge_imports: bool = False, base_dir: str = None):
if isinstance(schema, Path):
schema = str(schema)
if isinstance(schema, str):
schema = load_schema_wrap(schema)
self.schema = schema
self.schema_map = {schema.name: schema}
self.importmap = parse_import_map(importmap, base_dir) if importmap is not None else dict()
if merge_imports:
self.merge_imports()
self.uuid = str(uuid.uuid4())
def __key(self):
return self.schema.id, self.uuid, self.modifications
def __eq__(self, other):
if isinstance(other, SchemaView):
return self.__key() == other.__key()
return NotImplemented
def __hash__(self):
return hash(self.__key())
@lru_cache(None)
def namespaces(self) -> Namespaces:
namespaces = Namespaces()
for s in self.schema_map.values():
for prefix in s.prefixes.values():
namespaces[prefix.prefix_prefix] = prefix.prefix_reference
for cmap in self.schema.default_curi_maps:
namespaces.add_prefixmap(cmap, include_defaults=False)
return namespaces
def load_import(self, imp: str, from_schema: SchemaDefinition = None):
"""
Handles import directives.
The value of the import can be:
- a URL (specified as either a full URL or a CURIE)
- a local file path
The import should leave off the .yaml suffix.
If the import is a URL then the import is fetched over the network UNLESS this is a metamodel
import, in which case it is fetched from within the linkml_runtime package, where the yaml
is distributed. This ensures that the version of the metamodel imported matches the version
of the linkml_runtime package.
In future, this mechanism may be extended to arbitrary modules, such that we avoid
network dependence at runtime in general.
For local paths, the import is resolved relative to the directory containing the source file,
or the URL of the source file, if it is a URL.
:param imp:
:param from_schema:
:return:
"""
if from_schema is None:
from_schema = self.schema
from linkml_runtime import SCHEMA_DIRECTORY
default_import_map = {
"linkml:": str(SCHEMA_DIRECTORY)
}
importmap = {**default_import_map, **self.importmap}
sname = map_import(importmap, self.namespaces, imp)
if from_schema.source_file and not is_absolute_path(sname):
base_dir = os.path.dirname(from_schema.source_file)
else:
base_dir = None
logging.info(f'Importing {imp} as {sname} from source {from_schema.source_file}; base_dir={base_dir}')
schema = load_schema_wrap(sname + '.yaml', base_dir=base_dir)
return schema
@lru_cache(None)
def imports_closure(self, imports: bool = True, traverse: Optional[bool] = None, inject_metadata=True) -> List[SchemaDefinitionName]:
"""
Return all imports
Objects in imported classes override one another in a "python-like" order -
from the point of view of the importing schema, imports will override one
another from first to last, recursively for each layer of imports.
An import tree like::
- main
- s1
- s1_1
- s1_2
- s1_2_1
- s1_2_2
- s2
- s2_1
- s2_2
will override objects with the same name, in order::
['s1_1', 's1_2_1', 's1_2_2', 's1_2', 's1', 's2_1', 's2_2', 's2']
:param imports: bool (default: ``True`` ) include imported schemas, recursively
:param traverse: bool, optional (default: ``True`` ) (Deprecated, use
``imports`` ). if true, traverse recursively
:return: all schema names in the transitive reflexive imports closure
"""
if self.schema_map is None:
self.schema_map = {self.schema.name: self.schema}
closure = deque()
visited = set()
todo = [self.schema.name]
if traverse is not None:
warnings.warn(
'traverse behaves identically to imports and will be removed in a future version. Use imports instead.',
DeprecationWarning
)
if not imports or (not traverse and traverse is not None):
return todo
while len(todo) > 0:
# visit item
sn = todo.pop()
if sn not in self.schema_map:
imported_schema = self.load_import(sn)
self.schema_map[sn] = imported_schema
# resolve item's imports if it has not been visited already
# we will get duplicates, but not cycles this way, and
# filter out dupes, preserving the first entry, at the end.
if sn not in visited:
for i in self.schema_map[sn].imports:
# no self imports ;)
if i != sn:
todo.append(i)
# add item to closure
# append + pop (above) is FILO queue, which correctly extends tree leaves,
# but in backwards order.
closure.appendleft(sn)
visited.add(sn)
# filter duplicates, keeping first entry
closure = list({k:None for k in closure}.keys())
if inject_metadata:
for s in self.schema_map.values():
for x in {**s.classes, **s.enums, **s.slots, **s.subsets, **s.types}.values():
x.from_schema = s.id
for c in s.classes.values():
for a in c.attributes.values():
a.from_schema = s.id
return closure
@lru_cache(None)
def all_schema(self, imports: bool = True) -> List[SchemaDefinition]:
"""
:param imports: include imports closure
:return: all schemas
"""
m = self.schema_map
return [m[sn] for sn in self.imports_closure(imports)]
@deprecated("Use `all_classes` instead")
@lru_cache(None)
def all_class(self, imports=True) -> Dict[ClassDefinitionName, ClassDefinition]:
"""
:param imports: include imports closure
:return: all classes in schema view
"""
return self._get_dict(CLASSES, imports)
def ordered(self, elements: ElementDict, ordered_by: Optional[OrderedBy] = None) -> ElementDict:
"""
Order a dictionary of elements with some ordering method in :class:`.OrderedBy`
"""
if ordered_by in (OrderedBy.LEXICAL, OrderedBy.LEXICAL.value):
return self._order_lexically(elements)
elif ordered_by in (OrderedBy.RANK, OrderedBy.RANK.value):
return self._order_rank(elements)
elif ordered_by in (OrderedBy.INHERITANCE, OrderedBy.INHERITANCE.value):
return self._order_inheritance(elements)
elif ordered_by is None or ordered_by in (OrderedBy.PRESERVE, OrderedBy.PRESERVE.value):
return elements
else:
raise ValueError(f"ordered_by must be in OrderedBy or None, got {ordered_by}")
def _order_lexically(self, elements: ElementDict) -> ElementDict:
"""
:param element: slots or class type to order
:param imports
:return: all classes or slots sorted lexically in schema view
"""
ordered_list_of_names = []
ordered_elements = {}
for c in elements:
ordered_list_of_names.append(c)
ordered_list_of_names.sort()
for name in ordered_list_of_names:
ordered_elements[self.get_element(name).name] = self.get_element(name)
return ordered_elements
def _order_rank(self, elements: ElementDict) -> ElementDict:
"""
:param elements: slots or classes to order
:return: all classes or slots sorted by their rank in schema view
"""
rank_map = {}
unranked_map = {}
rank_ordered_elements = {}
for name, definition in elements.items():
if definition.rank is None:
unranked_map[self.get_element(name).name] = self.get_element(name)
else:
rank_map[definition.rank] = name
rank_ordered_map = collections.OrderedDict(sorted(rank_map.items()))
for k, v in rank_ordered_map.items():
rank_ordered_elements[self.get_element(v).name] = self.get_element(v)
rank_ordered_elements.update(unranked_map)
return rank_ordered_elements
def _order_inheritance(self, elements: DefDict) -> DefDict:
"""
sort classes such that if C is a child of P then C appears after P in the list
"""
clist = list(elements.values())
slist = [] # sorted
can_add = False
while len(clist) > 0:
for i in range(len(clist)):
candidate = clist[i]
can_add = False
if candidate.is_a is None:
can_add = True
else:
if candidate.is_a in [p.name for p in slist]:
can_add = True
if can_add:
slist = slist + [candidate]
del clist[i]
break
if not can_add:
raise OrderingError(f"could not find suitable element in {clist} that does not ref {slist}")
return {s.name: s for s in slist}
@lru_cache(None)
def all_classes(self, ordered_by=OrderedBy.PRESERVE, imports=True) -> Dict[ClassDefinitionName, ClassDefinition]:
"""
:param ordered_by: an enumerated parameter that returns all the slots in the order specified.
:param imports: include imports closure
:return: all classes in schema view
"""
classes = copy(self._get_dict(CLASSES, imports))
classes = self.ordered(classes, ordered_by=ordered_by)
return classes
@deprecated("Use `all_slots` instead")
@lru_cache(None)
def all_slot(self, **kwargs) -> Dict[SlotDefinitionName, SlotDefinition]:
"""
:param imports: include imports closure
:return: all slots in schema view
"""
return self.all_slots(**kwargs)
@lru_cache(None)
def all_slots(self, ordered_by=OrderedBy.PRESERVE, imports=True, attributes=True) -> Dict[
SlotDefinitionName, SlotDefinition]:
"""
:param ordered_by: an enumerated parameter that returns all the slots in the order specified.
:param imports: include imports closure
:param attributes: include attributes as slots or not, default is to include.
:return: all slots in schema view
"""
slots = copy(self._get_dict(SLOTS, imports))
if attributes:
for c in self.all_classes().values():
for aname, a in c.attributes.items():
if aname not in slots:
slots[aname] = a
slots = self.ordered(slots, ordered_by=ordered_by)
return slots
@deprecated("Use `all_enums` instead")
@lru_cache(None)
def all_enum(self, imports=True) -> Dict[EnumDefinitionName, EnumDefinition]:
"""
:param imports: include imports closure
:return: all enums in schema view
"""
return self._get_dict(ENUMS, imports)
@lru_cache(None)
def all_enums(self, imports=True) -> Dict[EnumDefinitionName, EnumDefinition]:
"""
:param imports: include imports closure
:return: all enums in schema view
"""
return self._get_dict(ENUMS, imports)
@deprecated("Use `all_types` instead")
@lru_cache(None)
def all_type(self, imports=True) -> Dict[TypeDefinitionName, TypeDefinition]:
"""
:param imports: include imports closure
:return: all types in schema view
"""
return self._get_dict(TYPES, imports)
@lru_cache(None)
def all_types(self, imports=True) -> Dict[TypeDefinitionName, TypeDefinition]:
"""
:param imports: include imports closure
:return: all types in schema view
"""
return self._get_dict(TYPES, imports)
@deprecated("Use `all_subsets` instead")
def all_subset(self, imports=True) -> Dict[SubsetDefinitionName, SubsetDefinition]:
"""
:param imports: include imports closure
:return: all subsets in schema view
"""
return self._get_dict(SUBSETS, imports)
@lru_cache(None)
def all_subsets(self, imports=True) -> Dict[SubsetDefinitionName, SubsetDefinition]:
"""
:param imports: include imports closure
:return: all subsets in schema view
"""
return self._get_dict(SUBSETS, imports)
@deprecated("Use `all_elements` instead")
@lru_cache(None)
def all_element(self, imports=True) -> Dict[ElementName, Element]:
"""
:param imports: include imports closure
:return: all elements in schema view
"""
all_classes = self.all_classes(imports=imports)
all_slots = self.all_slots(imports=imports)
all_enums = self.all_enums(imports=imports)
all_types = self.all_types(imports=imports)
all_subsets = self.all_subsets(imports=imports)
# {**a,**b} syntax merges dictionary a and b into a single dictionary, removing duplicates.
return {**all_classes, **all_slots, **all_enums, **all_types, **all_subsets}
@lru_cache(None)
def all_elements(self, imports=True) -> Dict[ElementName, Element]:
"""
:param imports: include imports closure
:return: all elements in schema view
"""
all_classes = self.all_classes(imports=imports)
all_slots = self.all_slots(imports=imports)
all_enums = self.all_enums(imports=imports)
all_types = self.all_types(imports=imports)
all_subsets = self.all_subsets(imports=imports)
# {**a,**b} syntax merges dictionary a and b into a single dictionary, removing duplicates.
return {**all_classes, **all_slots, **all_enums, **all_types, **all_subsets}
def _get_dict(self, slot_name: str, imports=True) -> Dict:
schemas = self.all_schema(imports)
d = {}
# pdb.set_trace()
# iterate through all schemas and merge the list together
for s in schemas:
# get the value of element name from the schema, if empty, return empty dictionary.
d1 = getattr(s, slot_name, {})
# {**d,**d1} syntax merges dictionary d and d1 into a single dictionary, removing duplicates.
d = {**d, **d1}
return d
@lru_cache(None)
def slot_name_mappings(self) -> Dict[str, SlotDefinition]:
"""
Mapping between processed safe slot names (following naming conventions) and slots.
For example, a slot may have name 'lives at', the code-safe version is `lives_at`
:return: mapping from safe names to slot
"""
m = {}
for s in self.all_slots().values():
m[underscore(s.name)] = s
return m
@lru_cache(None)
def class_name_mappings(self) -> Dict[str, ClassDefinition]:
"""
Mapping between processed safe class names (following naming conventions) and classes.
For example, a class may have name 'named thing', the code-safe version is `NamedThing`
:return: mapping from safe names to class
"""
m = {}
for s in self.all_classes().values():
m[camelcase(s.name)] = s
return m
@lru_cache(None)
def in_schema(self, element_name: ElementName) -> SchemaDefinitionName:
"""
:param element_name:
:return: name of schema in which element is defined
"""
ix = self.element_by_schema_map()
if element_name not in ix:
raise ValueError(f'Element {element_name} not in any schema')
return ix[element_name]
@lru_cache(None)
def element_by_schema_map(self) -> Dict[ElementName, SchemaDefinitionName]:
ix = {}
schemas = self.all_schema(True)
for schema in schemas:
for type_key in [CLASSES, SLOTS, TYPES, ENUMS, SUBSETS]:
for k, v in getattr(schema, type_key, {}).items():
ix[k] = schema.name
for c in schema.classes.values():
for aname, a in c.attributes.items():
ix[aname] = schema.name
return ix
@lru_cache(None)
def get_class(self, class_name: CLASS_NAME, imports=True, strict=False) -> ClassDefinition:
"""
:param class_name: name of the class to be retrieved
:param imports: include import closure
:return: class definition
"""
c = self.all_classes(imports=imports).get(class_name, None)
if strict and c is None:
raise ValueError(f'No such class as "{class_name}"')
else:
return c
@lru_cache(None)
def get_slot(self, slot_name: SLOT_NAME, imports=True, attributes=True, strict=False) -> SlotDefinition:
"""
:param slot_name: name of the slot to be retrieved
:param imports: include import closure
:param attributes: include attributes
:param strict: raise ValueError is not found
:return: slot definition
"""
slot = self.all_slots(imports=imports, attributes=False).get(slot_name, None)
if slot is None and attributes:
for c in self.all_classes(imports=imports).values():
if slot_name in c.attributes:
if slot is not None:
# slot name is ambiguous: return a stub slot
return SlotDefinition(slot_name)
slot = copy(c.attributes[slot_name])
slot.from_schema = c.from_schema
slot.owner = c.name
if strict and slot is None:
raise ValueError(f'No such slot as "{slot_name}"')
return slot
@lru_cache(None)
def get_subset(self, subset_name: SUBSET_NAME, imports=True, strict=False) -> SubsetDefinition:
"""
:param subset_name: name of the subsey to be retrieved
:param imports: include import closure
:return: subset definition
"""
s = self.all_subsets(imports).get(subset_name, None)
if strict and s is None:
raise ValueError(f'No such subset as "{subset_name}"')
else:
return s
@lru_cache(None)
def get_enum(self, enum_name: ENUM_NAME, imports=True, strict=False) -> EnumDefinition:
"""
:param enum_name: name of the enum to be retrieved
:param imports: include import closure
:return: enum definition
"""
e = self.all_enums(imports).get(enum_name, None)
if strict and e is None:
raise ValueError(f'No such subset as "{enum_name}"')
else:
return e
@lru_cache(None)
def get_type(self, type_name: TYPE_NAME, imports=True, strict=False) -> TypeDefinition:
"""
:param type_name: name of the type to be retrieved
:param imports: include import closure
:return: type definition
"""
t = self.all_types(imports).get(type_name, None)
if strict and t is None:
raise ValueError(f'No such subset as "{type_name}"')
else:
return t
def _parents(self, e: Element, imports=True, mixins=True, is_a=True) -> List[ElementName]:
if mixins:
parents = copy(e.mixins)
else:
parents = []
if e.is_a is not None and is_a:
parents.append(e.is_a)
return parents
@lru_cache(None)
def class_parents(self, class_name: CLASS_NAME, imports=True, mixins=True, is_a=True) -> List[ClassDefinitionName]:
"""
:param class_name: child class name
:param imports: include import closure
:param mixins: include mixins (default is True)
:return: all direct parent class names (is_a and mixins)
"""
cls = self.get_class(class_name, imports, strict=True)
return self._parents(cls, imports, mixins, is_a)
@lru_cache(None)
def enum_parents(self, enum_name: ENUM_NAME, imports=False, mixins=False, is_a=True) -> List[EnumDefinitionName]:
"""
:param enum_name: child enum name
:param imports: include import closure (False)
:param mixins: include mixins (default is False)
:return: all direct parent enum names (is_a and mixins)
"""
e = self.get_enum(enum_name, strict=True)
return self._parents(e, imports, mixins, is_a=is_a)
@lru_cache(None)
def permissible_value_parent(self, permissible_value: str, enum_name: ENUM_NAME) -> Union[
str, PermissibleValueText, None, ValueError]:
"""
:param enum_name: child enum name
:param permissible_value: permissible value
:return: all direct parent enum names (is_a)
"""
enum = self.get_enum(enum_name, strict=True)
if enum:
if permissible_value in enum.permissible_values:
pv = enum.permissible_values[permissible_value]
if pv.is_a:
return [pv.is_a]
else:
return []
@lru_cache(None)
def permissible_value_children(self, permissible_value: str, enum_name: ENUM_NAME) -> Union[
str, PermissibleValueText, None, ValueError]:
"""
:param enum_name: parent enum name
:param permissible_value: permissible value
:return: all direct child permissible values (is_a)
CAT:
LION:
is_a: CAT
ANGRY_LION:
is_a: LION
TABBY:
is_a: CAT
BIRD:
EAGLE:
is_a: BIRD
"""
enum = self.get_enum(enum_name, strict=True)
children = []
if enum:
if permissible_value in enum.permissible_values:
pv = enum.permissible_values[permissible_value]
for isapv in enum.permissible_values:
isapv_entity = enum.permissible_values[isapv]
if isapv_entity.is_a and pv.text == isapv_entity.is_a:
children.append(isapv)
return children
else:
raise ValueError(f'No such enum as "{enum_name}"')
@lru_cache(None)
def slot_parents(self, slot_name: SLOT_NAME, imports=True, mixins=True, is_a=True) -> List[SlotDefinitionName]:
"""
:param slot_name: child slot name
:param imports: include import closure
:param mixins: include mixins (default is True)
:return: all direct parent slot names (is_a and mixins)
"""
s = self.get_slot(slot_name, imports, strict=True)
if s:
return self._parents(s, imports, mixins, is_a)
else:
return []
@lru_cache(None)
def type_parents(self, type_name: TYPE_NAME, imports=True) -> List[TypeDefinitionName]:
"""
:param type_name: child type name
:param imports: include import closure
:return: all direct parent enum names (is_a and mixins)
"""
typ = self.get_type(type_name, imports, strict=True)
if typ.typeof:
return [typ.typeof]
else:
return []
@lru_cache(None)
def get_children(self, name: str, mixin: bool = True) -> List[str]:
"""
get the children of an element (any class, slot, enum, type)
:param name: name of the parent element
:param mixin: include mixins
:return: list of child element
"""
children = []
for e, el in self.all_elements().items():
if isinstance(el, (ClassDefinition, SlotDefinition, EnumDefinition)):
if el.is_a and el.is_a == name:
children.append(el.name)
if mixin and el.mixins and name in el.mixins:
children.append(el.name)
return children
@lru_cache(None)
def class_children(self, class_name: CLASS_NAME, imports=True, mixins=True, is_a=True) -> List[ClassDefinitionName]:
"""
:param class_name: parent class name
:param imports: include import closure
:param mixins: include mixins (default is True)
:param is_a: include is_a parents (default is True)
:return: all direct child class names (is_a and mixins)
"""
elts = [self.get_class(x) for x in self.all_classes(imports=imports)]
return [x.name for x in elts if (x.is_a == class_name and is_a) or (mixins and class_name in x.mixins)]
@lru_cache(None)
def slot_children(self, slot_name: SLOT_NAME, imports=True, mixins=True, is_a=True) -> List[SlotDefinitionName]:
"""
:param slot_name: parent slot name
:param imports: include import closure
:param mixins: include mixins (default is True)
:param is_a: include is_a parents (default is True)
:return: all direct child slot names (is_a and mixins)
"""
elts = [self.get_slot(x) for x in self.all_slots(imports=imports)]
return [x.name for x in elts if (x.is_a == slot_name and is_a) or (mixins and slot_name in x.mixins)]
@lru_cache(None)
def class_ancestors(self, class_name: CLASS_NAME, imports=True, mixins=True, reflexive=True, is_a=True,
depth_first=True) -> List[ClassDefinitionName]:
"""
Closure of class_parents method
:param class_name: query class
:param imports: include import closure
:param mixins: include mixins (default is True)
:param is_a: include is_a parents (default is True)
:param reflexive: include self in set of ancestors
:param depth_first:
:return: ancestor class names
"""
return _closure(lambda x: self.class_parents(x, imports=imports, mixins=mixins, is_a=is_a),
class_name,
reflexive=reflexive, depth_first=depth_first)
@lru_cache(None)
def permissible_value_ancestors(self, permissible_value_text: str,
enum_name: ENUM_NAME,
reflexive=True,
depth_first=True) -> List[str]:
"""
Closure of permissible_value_parents method
:enum
"""
return _closure(lambda x: self.permissible_value_parent(x, enum_name),
permissible_value_text,
reflexive=reflexive,
depth_first=depth_first)
@lru_cache(None)
def permissible_value_descendants(self, permissible_value_text: str,
enum_name: ENUM_NAME,
reflexive=True,
depth_first=True) -> List[str]:
"""
Closure of permissible_value_children method
:enum
"""
return _closure(lambda x: self.permissible_value_children(x, enum_name),
permissible_value_text,
reflexive=reflexive,
depth_first=depth_first)
@lru_cache(None)
def enum_ancestors(self, enum_name: ENUM_NAME, imports=True, mixins=True, reflexive=True, is_a=True,
depth_first=True) -> List[EnumDefinitionName]:
"""
Closure of enum_parents method
:param enum_name: query enum
:param imports: include import closure
:param mixins: include mixins (default is True)
:param is_a: include is_a parents (default is True)
:param reflexive: include self in set of ancestors
:param depth_first:
:return: ancestor enum names
"""
return _closure(lambda x: self.enum_parents(x, imports=imports, mixins=mixins, is_a=is_a),
enum_name,
reflexive=reflexive, depth_first=depth_first)
@lru_cache(None)
def type_ancestors(self, type_name: TYPES, imports=True, reflexive=True, depth_first=True) -> List[
TypeDefinitionName]:
"""
All ancestors of a type via typeof
:param type_name: query type
:param imports: include import closure
:param reflexive: include self in set of ancestors
:param depth_first:
:return: ancestor class names
"""
return _closure(lambda x: self.type_parents(x, imports=imports),
type_name,
reflexive=reflexive, depth_first=depth_first)
@lru_cache(None)
def slot_ancestors(self, slot_name: SLOT_NAME, imports=True, mixins=True, reflexive=True, is_a=True) -> List[
SlotDefinitionName]:
"""
Closure of slot_parents method
:param slot_name: query slot
:param imports: include import closure
:param mixins: include mixins (default is True)
:param is_a: include is_a parents (default is True)
:param reflexive: include self in set of ancestors
:return: ancestor slot names
"""
return _closure(lambda x: self.slot_parents(x, imports=imports, mixins=mixins, is_a=is_a),
slot_name,
reflexive=reflexive)
@lru_cache(None)
def class_descendants(self, class_name: CLASS_NAME, imports=True, mixins=True, reflexive=True, is_a=True) -> List[
ClassDefinitionName]:
"""
Closure of class_children method
:param class_name: query class
:param imports: include import closure
:param mixins: include mixins (default is True)
:param is_a: include is_a parents (default is True)
:param reflexive: include self in set of descendants
:return: descendants class names
"""
return _closure(lambda x: self.class_children(x, imports=imports, mixins=mixins, is_a=is_a), class_name,
reflexive=reflexive)
@lru_cache(None)
def slot_descendants(self, slot_name: SLOT_NAME, imports=True, mixins=True, reflexive=True, is_a=True) -> List[
SlotDefinitionName]:
"""
Closure of slot_children method
:param slot_name: query slot
:param imports: include import closure
:param mixins: include mixins (default is True)
:param is_a: include is_a parents (default is True)
:param reflexive: include self in set of descendants
:return: descendants slot names
"""
return _closure(lambda x: self.slot_children(x, imports=imports, mixins=mixins, is_a=is_a), slot_name,
reflexive=reflexive)
@lru_cache(None)
def class_roots(self, imports=True, mixins=True, is_a=True) -> List[ClassDefinitionName]:
"""
All classes that have no parents
:param imports:
:param mixins:
:param is_a: include is_a parents (default is True)
:return:
"""
return [c
for c in self.all_classes(imports=imports)
if self.class_parents(c, mixins=mixins, is_a=is_a, imports=imports) == []]
@lru_cache(None)
def class_leaves(self, imports=True, mixins=True, is_a=True) -> List[ClassDefinitionName]:
"""
All classes that have no children
:param imports:
:param mixins:
:param is_a: include is_a parents (default is True)
:return:
"""
return [c
for c in self.all_classes(imports=imports)
if self.class_children(c, mixins=mixins, is_a=is_a, imports=imports) == []]
@lru_cache(None)
def slot_roots(self, imports=True, mixins=True) -> List[SlotDefinitionName]:
"""
All slotes that have no parents
:param imports:
:param mixins:
:return:
"""
return [c
for c in self.all_slots(imports=imports)
if self.slot_parents(c, mixins=mixins, imports=imports) == []]
@lru_cache(None)
def slot_leaves(self, imports=True, mixins=True) -> List[SlotDefinitionName]:
"""
All slotes that have no children
:param imports:
:param mixins:
:return:
"""
return [c
for c in self.all_slots(imports=imports)
if self.slot_children(c, mixins=mixins, imports=imports) == []]
@lru_cache(None)
def is_multivalued(self, slot_name: SlotDefinition) -> bool:
"""
returns True if slot is multivalued, else returns False
:param slot_name: slot to test for multivalued
:return boolean:
"""
induced_slot = self.induced_slot(slot_name)
return True if induced_slot.multivalued else False