-
Notifications
You must be signed in to change notification settings - Fork 60
/
Copy pathmodel.py
2363 lines (1801 loc) · 72.9 KB
/
model.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
"""SDMX Information Model (SDMX-IM).
This module implements many of the classes described in the SDMX-IM specification
('spec'), which is available from:
- https://sdmx.org/?page_id=5008
- https://sdmx.org/wp-content/uploads/
SDMX_2-1-1_SECTION_2_InformationModel_201108.pdf
Details of the implementation:
- Python typing and pydantic are used to enforce the types of attributes that reference
instances of other classes.
- Some classes have convenience attributes not mentioned in the spec, to ease navigation
between related objects. These are marked “:mod:`sdmx` extension not in the IM.”
- Class definitions are grouped by section of the spec, but these sections appear out
of order so that dependent classes are defined first.
"""
# TODO for complete implementation of the IM, enforce TimeKeyValue (instead of KeyValue)
# for {Generic,StructureSpecific} TimeSeriesDataSet.
import logging
from collections import ChainMap
from collections.abc import Collection
from collections.abc import Iterable as IterableABC
from copy import copy
from datetime import date, datetime, timedelta
from enum import Enum
from functools import lru_cache
from inspect import isclass
from itertools import product
from operator import attrgetter, itemgetter
from typing import (
Any,
Dict,
Generator,
Generic,
Iterable,
List,
Mapping,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
)
from warnings import warn
from pandasdmx.util import (
BaseModel,
DictLike,
compare,
dictlike_field,
only,
Resource,
validate_dictlike,
validator,
)
log = logging.getLogger(__name__)
# Used by writers to select from InternationalString.
# Exposed through pandasdmx.api.Request.default_locale
DEFAULT_LOCALE = "en"
# Configure validation level (new in v1.8.0)
# This is currently used only to prevent URN matching
ValidationLevels = Enum("ValidationLevels", "strict sloppy")
DEFAULT_VAL_LEVEL = ValidationLevels.sloppy
# §3.2: Base structures
class InternationalString:
"""SDMX-IM InternationalString.
SDMX-IM LocalisedString is not implemented. Instead, the 'localizations' is a
mapping where:
- keys correspond to the 'locale' property of LocalisedString.
- values correspond to the 'label' property of LocalisedString.
When used as a type hint with pydantic, InternationalString fields can be assigned
to in one of four ways::
class Foo(BaseModel):
name: InternationalString = InternationalString()
# Equivalent: no localizations
f = Foo()
f = Foo(name={})
# Using an explicit locale
f.name['en'] = "Foo's name in English"
# Using a (locale, label) tuple
f.name = ('fr', "Foo's name in French")
# Using a dict
f.name = {'en': "Replacement English name",
'fr': "Replacement French name"}
# Using a bare string, implicitly for the DEFAULT_LOCALE
f.name = "Name in DEFAULT_LOCALE language"
Only the first method preserves existing localizations; the latter three replace
them.
"""
localizations: Dict[str, str] = {}
def __init__(self, value=None, **kwargs):
super().__init__()
# Handle initial values according to type
if isinstance(value, str):
# Bare string
value = {DEFAULT_LOCALE: value}
elif (
isinstance(value, Collection)
and len(value) == 2
and isinstance(value[0], str)
):
# 2-tuple of str is (locale, label)
value = {value[0]: value[1]}
elif isinstance(value, dict):
# dict; use directly
pass
elif isinstance(value, IterableABC):
# Iterable of 2-tuples
value = {locale: label for (locale, label) in value}
elif value is None:
# Keyword arguments → dict, possibly empty
value = dict(kwargs)
else:
raise ValueError(value, kwargs)
self.localizations = value
# Convenience access
def __getitem__(self, locale):
return self.localizations[locale]
def __setitem__(self, locale, label):
self.localizations[locale] = label
# Duplicate of __getitem__, to pass existing tests in test_dsd.py
def __getattr__(self, name):
try:
return self.__dict__["localizations"][name]
except KeyError:
raise AttributeError(name) from None
def __add__(self, other):
result = copy(self)
result.localizations.update(other.localizations)
return result
def localized_default(self, locale=None):
"""Return the string in *locale* if not empty, or else the first defined."""
if locale and (locale in self.localizations) and self.localizations[locale]:
return self.localizations[locale]
if len(self.localizations):
# No label in the default locale; use the first stored non-empty str value
return next(filter(None, self.localizations.values()))
else:
return ""
def __str__(self):
return self.localized_default(DEFAULT_LOCALE)
def __repr__(self):
return "\n".join(
["{}: {}".format(*kv) for kv in sorted(self.localizations.items())]
)
def __eq__(self, other):
try:
return self.localizations == other.localizations
except AttributeError:
return NotImplemented
@classmethod
def __get_validators__(cls):
yield cls.__validate
@classmethod
def __validate(cls, value, values, config, field):
# Any value that the constructor can handle can be assigned
if not isinstance(value, InternationalString):
value = InternationalString(value)
try:
# Update existing value
existing = values[field.name]
existing.localizations.update(value.localizations)
return existing
except KeyError:
# No existing value/None; return the assigned value
return value
class Annotation(BaseModel):
#: Can be used to disambiguate multiple annotations for one AnnotableArtefact.
id: Optional[str] = None
#: Title, used to identify an annotation.
title: Optional[str] = None
#: Specifies how the annotation is processed.
type: Optional[str] = None
#: A link to external descriptive text.
url: Optional[str] = None
#: Content of the annotation.
text: InternationalString = InternationalString()
class AnnotableArtefact(BaseModel):
#: :class:`Annotations <.Annotation>` of the object.
#:
#: :mod:`pandaSDMX` implementation: The IM does not specify the name of this
#: feature.
annotations: List[Annotation] = []
def get_annotation(self, **attrib):
"""Return a :class:`Annotation` with given `attrib`, e.g. 'id'.
If more than one `attrib` is given, all must match a particular annotation.
Raises
------
KeyError
If there is no matching annotation.
"""
for anno in self.annotations:
if all(getattr(anno, key, None) == value for key, value in attrib.items()):
return anno
raise KeyError(attrib)
def pop_annotation(self, **attrib):
"""Remove and return a :class:`Annotation` with given `attrib`, e.g. 'id'.
If more than one `attrib` is given, all must match a particular annotation.
Raises
------
KeyError
If there is no matching annotation.
"""
for i, anno in enumerate(self.annotations):
if all(getattr(anno, key, None) == value for key, value in attrib.items()):
return self.annotations.pop(i)
raise KeyError(attrib)
class _MissingID(str):
def __str__(self):
return "(missing id)"
def __eq__(self, other):
return isinstance(other, self.__class__)
MissingID = _MissingID()
class IdentifiableArtefact(AnnotableArtefact):
#: Unique identifier of the object.
id: str = MissingID
#: Universal resource identifier that may or may not be resolvable.
uri: Optional[str] = None
#: Universal resource name. For use in SDMX registries; all registered
#: objects have a URN.
urn: Optional[str] = None
urn_group: Dict = dict()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.urn and DEFAULT_VAL_LEVEL == ValidationLevels.strict:
import pandasdmx.urn
self.urn_group = pandasdmx.urn.match(self.urn)
try:
if self.id not in (self.urn_group["item_id"] or self.urn_group["id"]):
raise ValueError(f"ID {self.id} does not match URN {self.urn}")
except KeyError:
pass
def __eq__(self, other):
"""Equality comparison.
IdentifiableArtefacts can be compared to other instances. For convenience, a
string containing the object's ID is also equal to the object.
"""
if isinstance(other, self.__class__):
return self.id == other.id
elif isinstance(other, str):
return self.id == other
def compare(self, other, strict=True):
"""Return :obj:`True` if `self` is the same as `other`.
Two IdentifiableArtefacts are the same if they have the same :attr:`id`,
:attr:`uri`, and :attr:`urn`.
Parameters
----------
strict : bool, optional
Passed to :func:`.compare`.
"""
return (
compare("id", self, other, strict)
and compare("uri", self, other, strict)
and compare("urn", self, other, strict)
)
def __hash__(self):
return id(self) if self.id == MissingID else hash(self.id)
def __lt__(self, other):
return (
self.id < other.id if isinstance(other, self.__class__) else NotImplemented
)
def __str__(self):
return self.id
def __repr__(self):
return f"<{self.__class__.__name__} {self.id}>"
class NameableArtefact(IdentifiableArtefact):
#: Multi-lingual name of the object.
name: InternationalString = InternationalString()
#: Multi-lingual description of the object.
description: InternationalString = InternationalString()
def compare(self, other, strict=True):
"""Return :obj:`True` if `self` is the same as `other`.
Two NameableArtefacts are the same if:
- :meth:`.IdentifiableArtefact.compare` is :obj:`True`, and
- they have the same :attr:`name` and :attr:`description`.
Parameters
----------
strict : bool, optional
Passed to :func:`.compare` and :meth:`.IdentifiableArtefact.compare`.
"""
if not super().compare(other, strict):
pass
elif self.name != other.name:
log.debug(
f"Not identical: name <{repr(self.name)}> != <{repr(other.name)}>"
)
elif self.description != other.description:
log.debug(
f"Not identical: description <{repr(self.description)}> != "
f"<{repr(other.description)}>"
)
else:
return True
return False
def _repr_kw(self):
return dict(
cls=self.__class__.__name__,
id=self.id,
name=f": {self.name}" if len(self.name.localizations) else "",
)
def __repr__(self):
return "<{cls} {id}{name}>".format(**self._repr_kw())
class VersionableArtefact(NameableArtefact):
#: A version string following an agreed convention.
version: Optional[str] = None
#: Date from which the version is valid.
valid_from: Optional[str] = None
#: Date from which the version is superseded.
valid_to: Optional[str] = None
def __init__(self, **kwargs):
super().__init__(**kwargs)
try:
if self.version and self.version != self.urn_group["version"]:
raise ValueError(
f"Version {self.version} does not match URN {self.urn}"
)
else:
self.version = self.urn_group["version"]
except KeyError:
pass
def compare(self, other, strict=True):
"""Return :obj:`True` if `self` is the same as `other`.
Two VersionableArtefacts are the same if:
- :meth:`.NameableArtefact.compare` is :obj:`True`, and
- they have the same :attr:`version`.
Parameters
----------
strict : bool, optional
Passed to :func:`.compare` and :meth:`.NameableArtefact.compare`.
"""
return super().compare(other, strict) and compare(
"version", self, other, strict
)
def _repr_kw(self) -> Mapping:
return ChainMap(
super()._repr_kw(),
dict(version=f"({self.version})" if self.version else ""),
)
class MaintainableArtefact(VersionableArtefact):
#: True if the object is final; otherwise it is in a draft state.
is_final: Optional[bool] = None
#: :obj:`True` if the content of the object is held externally; i.e., not
#: the current :class:`Message`.
is_external_reference: Optional[bool] = None
#: URL of an SDMX-compliant web service from which the object can be
#: retrieved.
service_url: Optional[str] = None
#: URL of an SDMX-ML document containing the object.
structure_url: Optional[str] = None
#: Association to the Agency responsible for maintaining the object.
maintainer: Optional["Agency"] = None
def __init__(self, **kwargs):
super().__init__(**kwargs)
try:
if self.maintainer and self.maintainer.id != self.urn_group["agency"]:
raise ValueError(
f"Maintainer {self.maintainer} does not match URN {self.urn}"
)
else:
self.maintainer = Agency(id=self.urn_group["agency"])
except KeyError:
pass
def compare(self, other, strict=True):
"""Return :obj:`True` if `self` is the same as `other`.
Two MaintainableArtefacts are the same if:
- :meth:`.VersionableArtefact.compare` is :obj:`True`, and
- they have the same :attr:`maintainer`.
Parameters
----------
strict : bool, optional
Passed to :func:`.compare` and :meth:`.VersionableArtefact.compare`.
"""
return super().compare(other, strict) and compare(
"maintainer", self, other, strict
)
def _repr_kw(self):
return ChainMap(
super()._repr_kw(),
dict(maint=f"{self.maintainer}:" if self.maintainer else ""),
)
def __repr__(self):
return "<{cls} {maint}{id}{version}{name}>".format(**self._repr_kw())
# §3.4: Data Types
ActionType = Enum("ActionType", "delete replace append information")
UsageStatus = Enum("UsageStatus", "mandatory conditional")
# NB three diagrams in the spec show this enumeration containing 'gregorianYearMonth'
# but not 'gregorianYear' or 'gregorianMonth'. The table in §3.6.3.3 Representation
# Constructs does the opposite. One ESTAT query (via SGR) shows a real-world usage
# of 'gregorianYear'; while one query shows usage of 'gregorianYearMonth'; so all
# three are included.
FacetValueType = Enum(
"FacetValueType",
"""string bigInteger integer long short decimal float double boolean uri count
inclusiveValueRange alpha alphaNumeric numeric exclusiveValueRange incremental
observationalTimePeriod standardTimePeriod basicTimePeriod gregorianTimePeriod
gregorianYear gregorianMonth gregorianYearMonth gregorianDay reportingTimePeriod
reportingYear reportingSemester reportingTrimester reportingQuarter reportingMonth
reportingWeek reportingDay dateTime timesRange month monthDay day time duration
keyValues identifiableReference dataSetReference""",
)
ConstraintRoleType = Enum("ConstraintRoleType", "allowable actual")
# §3.5: Item Scheme
IT = TypeVar("IT", bound="Item")
class Item(NameableArtefact, Generic[IT]):
parent: Optional[Union[IT, "ItemScheme"]] = None
child: List[IT] = []
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Add this Item as a child of its parent
parent = kwargs.get("parent", None)
if parent:
parent.append_child(self)
# Add this Item as a parent of its children
for c in kwargs.get("child", []):
self.append_child(c)
def __contains__(self, item):
"""Recursive containment."""
for c in self.child:
if item == c or item in c:
return True
def __iter__(self, recurse=True):
yield self
for c in self.child:
yield from iter(c)
@property
def hierarchical_id(self):
"""Construct the ID of an Item in a hierarchical ItemScheme.
Returns, for example, 'A.B.C' for an Item with id 'C' that is the child of an
item with id 'B', which is the child of a root Item with id 'A'.
See also
--------
.ItemScheme.get_hierarchical
"""
return (
f"{self.parent.hierarchical_id}.{self.id}"
if isinstance(self.parent, self.__class__)
else self.id
)
def append_child(self, other: IT):
if other not in self.child:
self.child.append(other)
other.parent = self
def get_child(self, id) -> IT:
"""Return the child with the given *id*."""
for c in self.child:
if c.id == id:
return c
raise ValueError(id)
def get_scheme(self):
"""Return the :class:`ItemScheme` to which the Item belongs, if any."""
try:
# Recurse
return self.parent.get_scheme()
except AttributeError:
# Either this Item is a top-level Item whose .parent refers to the
# ItemScheme, or it has no parent
return self.parent
class ItemScheme(MaintainableArtefact, Generic[IT]):
"""SDMX-IM Item Scheme.
The IM states that ItemScheme “defines a *set* of :class:`Items <.Item>`…” To
simplify indexing/retrieval, this implementation uses a :class:`dict` for the
:attr:`items` attribute, in which the keys are the :attr:`~.IdentifiableArtefact.id`
of the Item.
Because this may change in future versions of pandaSDMX, user code should not access
:attr:`items` directly. Instead, use the :func:`getattr` and indexing features of
ItemScheme, or the public methods, to access and manipulate Items:
>>> foo = ItemScheme(id='foo')
>>> bar = Item(id='bar')
>>> foo.append(bar)
>>> foo
<ItemScheme: 'foo', 1 items>
>>> (foo.bar is bar) and (foo['bar'] is bar) and (bar in foo)
True
"""
# TODO add delete()
# TODO add sorting capability; perhaps sort when new items are inserted
is_partial: Optional[bool]
#: Members of the ItemScheme. Both ItemScheme and Item are abstract classes.
#: Concrete classes are paired: for example, a :class:`.Codelist` contains
#: :class:`Codes <.Code>`.
items: Dict[str, IT] = {}
# The type of the Items in the ItemScheme. This is necessary because the type hint
# in the class declaration is static; not meant to be available at runtime.
_Item: Type = Item
@validator("items", pre=True)
def convert_to_dict(cls, v):
if isinstance(v, dict):
return v
return {i.id: i for i in v}
# Convenience access to items
def __getattr__(self, name: str) -> IT:
# Provided to pass test_dsd.py
try:
return self.__getitem__(name)
except KeyError:
raise AttributeError(name)
def __getitem__(self, name: str) -> IT:
return self.items[name]
def get_hierarchical(self, id: str) -> IT:
"""Get an Item by its :attr:`~.Item.hierarchical_id`."""
if "." not in id:
return self.items[id]
else:
for item in self.items.values():
if item.hierarchical_id == id:
return item
raise KeyError(id)
def __contains__(self, item: Union[str, IT]) -> bool:
"""Check containment.
No recursive search on children is performed as these are assumed to be included
in :attr:`items`. Allow searching by Item or its id attribute.
"""
if isinstance(item, str):
return item in self.items
return item in self.items.values()
def __iter__(self):
return iter(self.items.values())
def extend(self, items: Iterable[IT]):
"""Extend the ItemScheme with members of `items`.
Parameters
----------
items : iterable of :class:`.Item`
Elements must be of the same class as :attr:`items`.
"""
for i in items:
self.append(i)
def __len__(self):
return len(self.items)
def append(self, item: IT):
"""Add *item* to the ItemScheme.
Parameters
----------
item : same class as :attr:`items`
Item to add.
"""
if item.id in self.items:
raise ValueError(f"Item with id {repr(item.id)} already exists")
self.items[item.id] = item
if item.parent is None:
item.parent = self
def compare(self, other, strict=True):
"""Return :obj:`True` if `self` is the same as `other`.
Two ItemSchemes are the same if:
- :meth:`.MaintainableArtefact.compare` is :obj:`True`, and
- their :attr:`items` have the same keys, and corresponding
:class:`Items <Item>` compare equal.
Parameters
----------
strict : bool, optional
Passed to :func:`.compare` and :meth:`.MaintainableArtefact.compare`.
"""
if not super().compare(other, strict):
pass
elif set(self.items) != set(other.items):
log.debug(
f"ItemScheme contents differ: {repr(set(self.items))} != "
+ repr(set(other.items))
)
else:
for id, item in self.items.items():
if not item.compare(other.items[id], strict):
log.debug(f"…for items with id={repr(id)}")
return False
return True
return False
def __repr__(self):
return "<{cls} {maint}{id}{version} ({N} items){name}>".format(
**self._repr_kw(), N=len(self.items)
)
def setdefault(self, obj=None, **kwargs) -> IT:
"""Retrieve the item *name*, or add it with *kwargs* and return it.
The returned object is a reference to an object in the ItemScheme, and is of the
appropriate class.
"""
if obj and len(kwargs):
raise ValueError(
"cannot give both *obj* and keyword arguments to setdefault()"
)
if not obj:
# Replace a string 'parent' ID with a reference to the object
parent = kwargs.pop("parent", None)
if isinstance(parent, str):
kwargs["parent"] = self[parent]
# Instantiate an object of the correct class
obj = self._Item(**kwargs)
try:
# Add the object to the ItemScheme
self.append(obj)
except ValueError:
pass # Already present
return obj
Item.update_forward_refs()
# §3.6: Structure
class FacetType(BaseModel):
class Config:
extra = "forbid"
#:
is_sequence: Optional[bool] = None
#:
min_length: Optional[int] = None
#:
max_length: Optional[int] = None
#:
min_value: Optional[float] = None
#:
max_value: Optional[float] = None
#:
start_value: Optional[float] = None
#:
end_value: Optional[str] = None
#:
interval: Optional[float] = None
#:
time_interval: Optional[timedelta] = None
#:
decimals: Optional[int] = None
#:
pattern: Optional[str] = None
#:
start_time: Optional[datetime] = None
#:
end_time: Optional[datetime] = None
class Facet(BaseModel):
class Config:
extra = "forbid"
#:
type: FacetType = FacetType()
#:
value: Optional[str] = None
#:
value_type: Optional[FacetValueType] = None
class Representation(BaseModel):
class Config:
extra = "forbid"
#:
enumerated: Optional[ItemScheme] = None
#:
non_enumerated: List[Facet] = []
def __repr__(self):
return "<{}: {}, {}>".format(
self.__class__.__name__, self.enumerated, self.non_enumerated
)
# §4.4: Concept Scheme
class ISOConceptReference(BaseModel):
class Config:
extra = "forbid"
#:
agency: str
#:
id: str
#:
scheme_id: str
class Concept(Item["Concept"]):
#:
core_representation: Optional[Representation] = None
#:
iso_concept: Optional[ISOConceptReference] = None
class ConceptScheme(ItemScheme[Concept]):
_Item = Concept
# §3.3: Basic Inheritance
class Component(IdentifiableArtefact):
#:
concept_identity: Optional[Concept] = None
#:
local_representation: Optional[Representation] = None
def __contains__(self, value):
for repr in [
self.concept_identity.core_representation,
self.local_representation,
]:
enum = getattr(repr, "enumerated", None)
if enum is not None:
return value in enum
raise TypeError("membership not defined for non-enumerated representations")
CT = TypeVar("CT", bound=Component)
class ComponentList(IdentifiableArtefact, Generic[CT]):
#:
components: List[CT] = []
#:
auto_order = 1
# The default type of the Components in the ComponentList. See comment on
# ItemScheme._Item
_Component: Type = Component
# Convenience access to the components
def append(self, value: CT):
"""Append *value* to :attr:`components`."""
self.components.append(value)
def get(self, id) -> CT:
"""Return the component with the given *id*."""
# Search for an existing Component
for c in self.components:
if c.id == id:
return c
raise KeyError(id)
def getdefault(self, id, cls=None, **kwargs) -> CT:
"""Return or create the component with the given *id*.
If the component is automatically created, its :attr:`.Dimension.order`
attribute is set to the value of :attr:`auto_order`, which is then incremented.
Parameters
----------
id : str
Component ID.
cls : type, optional
Hint for the class of a new object.
kwargs
Passed to the constructor of :class:`.Component`, or a Component subclass if
:attr:`.components` is overridden in a subclass of ComponentList.
"""
try:
return self.get(id)
except KeyError:
# No match
pass
# Create a new object of a class:
# 1. Given by the cls argument,
# 2. Specified by a subclass' _default_type attribute, or
# 3. Hinted for a subclass' components attribute.
cls = cls or self._Component
component = cls(id=id, **kwargs)
if "order" not in kwargs:
# For automatically created dimensions, give a serial value to the
# order property
try:
component.order = self.auto_order
self.auto_order += 1
except ValueError:
pass
self.components.append(component)
return component
# Properties of components
def __getitem__(self, key) -> CT:
"""Convenience access to components."""
return self.components[key]
def __len__(self):
return len(self.components)
def __iter__(self):
return iter(self.components)
def __repr__(self):
return "<{}: {}>".format(
self.__class__.__name__, "; ".join(map(repr, self.components))
)
def __eq__(self, other):
"""ID equal and same components occur in same order."""
return super().__eq__(other) and all(
s == o for s, o in zip(self.components, other.components)
)
# Must be reset because __eq__ is defined
def __hash__(self):
return super().__hash__()
def compare(self, other, strict=True):
"""Return :obj:`True` if `self` is the same as `other`.
Two ComponentLists are the same if:
- :meth:`.IdentifiableArtefact.compare` is :obj:`True`, and
- corresponding :attr:`components` compare equal.
Parameters
----------
strict : bool, optional
Passed to :func:`.compare` and :meth:`.IdentifiableArtefact.compare`.
"""
return super().compare(other, strict) and all(
c.compare(other.get(c.id), strict) for c in self.components
)
# §4.3: Codelist
class Code(Item["Code"]):
"""SDMX-IM Code."""
class Codelist(ItemScheme[Code]):
_Item = Code
# §4.5: Category Scheme
class Category(Item["Category"]):
"""SDMX-IM Category."""
class CategoryScheme(ItemScheme[Category]):
_Item = Category
class Categorisation(MaintainableArtefact):
#:
category: Optional[Category] = None
#:
artefact: Optional[IdentifiableArtefact] = None
# §4.6: Organisations