-
Notifications
You must be signed in to change notification settings - Fork 283
/
metadata.py
2021 lines (1617 loc) · 66.2 KB
/
metadata.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
# Copyright Iris contributors
#
# This file is part of Iris and is released under the BSD license.
# See LICENSE in the root of the repository for full licensing details.
"""Provides the infrastructure to support the common metadata API."""
from __future__ import annotations
from abc import ABCMeta
from collections import namedtuple
from collections.abc import Iterable, Mapping
from copy import deepcopy
from functools import lru_cache, wraps
import re
from typing import TYPE_CHECKING, Any
import cf_units
import numpy as np
import numpy.ma as ma
from xxhash import xxh64_hexdigest
if TYPE_CHECKING:
from iris.coords import CellMethod
from ..config import get_logger
from ._split_attribute_dicts import adjust_for_split_attribute_dictionaries
from .lenient import _LENIENT
from .lenient import _lenient_service as lenient_service
from .lenient import _qualname as qualname
__all__ = [
"AncillaryVariableMetadata",
"BaseMetadata",
"CellMeasureMetadata",
"CoordMetadata",
"CubeMetadata",
"DimCoordMetadata",
"MeshCoordMetadata",
"MeshMetadata",
"SERVICES",
"SERVICES_COMBINE",
"SERVICES_DIFFERENCE",
"SERVICES_EQUAL",
"hexdigest",
"metadata_filter",
"metadata_manager_factory",
]
# https://www.unidata.ucar.edu/software/netcdf/docs/netcdf_data_set_components.html#object_name
_TOKEN_PARSE = re.compile(r"""^[a-zA-Z0-9][\w\.\+\-@]*$""")
# Configure the logger.
logger = get_logger(__name__, fmt="[%(cls)s.%(funcName)s]")
def hexdigest(item):
"""Calculate a hexadecimal string hash representation of the provided item.
Calculates a 64-bit non-cryptographic hash of the provided item, using
the extremely fast ``xxhash`` hashing algorithm, and returns the hexdigest
string representation of the hash.
This provides a means to compare large and/or complex objects through
simple string hexdigest comparison.
Parameters
----------
item : object
The item that requires to have its hexdigest calculated.
Returns
-------
str
The string hexadecimal representation of the item's 64-bit hash.
"""
# Special case: deal with numpy arrays.
if ma.isMaskedArray(item):
parts = (
item.shape,
xxh64_hexdigest(item.data),
xxh64_hexdigest(item.mask),
)
item = str(parts)
elif isinstance(item, np.ndarray):
parts = (item.shape, xxh64_hexdigest(item))
item = str(parts)
try:
# Calculate single-shot hash to avoid allocating state on the heap
result = xxh64_hexdigest(item)
except TypeError:
# xxhash expects a bytes-like object, so try hashing the
# string representation of the provided item instead, but
# also fold in the object type...
parts = (type(item), item)
result = xxh64_hexdigest(str(parts))
return result
class _NamedTupleMeta(ABCMeta):
"""Meta-class convenience for creating a namedtuple.
Meta-class to support the convenience of creating a namedtuple from
names/members of the metadata class hierarchy.
"""
def __new__(mcs, name, bases, namespace):
names = []
for base in bases:
if hasattr(base, "_fields"):
base_names = getattr(base, "_fields")
is_abstract = getattr(base_names, "__isabstractmethod__", False)
if not is_abstract:
if (not isinstance(base_names, Iterable)) or isinstance(
base_names, str
):
base_names = (base_names,)
names.extend(base_names)
if "_members" in namespace and not getattr(
namespace["_members"], "__isabstractmethod__", False
):
namespace_names = namespace["_members"]
if (not isinstance(namespace_names, Iterable)) or isinstance(
namespace_names, str
):
namespace_names = (namespace_names,)
names.extend(namespace_names)
if names:
item = namedtuple(f"{name}Namedtuple", names)
bases = list(bases)
# Influence the appropriate MRO.
bases.insert(0, item)
bases = tuple(bases)
return super().__new__(mcs, name, bases, namespace)
class BaseMetadata(metaclass=_NamedTupleMeta):
"""Container for common metadata."""
DEFAULT_NAME = "unknown" # the fall-back name for metadata identity
_members: str | Iterable[str] = (
"standard_name",
"long_name",
"var_name",
"units",
"attributes",
)
__slots__ = ()
standard_name: str | None
long_name: str | None
var_name: str | None
units: cf_units.Unit
attributes: Any
@lenient_service
def __eq__(self, other):
"""Determine whether the associated metadata members are equivalent.
Parameters
----------
other : metadata
A metadata instance of the same type.
Returns
-------
bool
"""
result = NotImplemented
# Only perform equivalence with similar class instances.
if hasattr(other, "__class__") and other.__class__ is self.__class__:
if _LENIENT(self.__eq__) or _LENIENT(self.equal):
# Perform "lenient" equality.
logger.debug("lenient", extra=dict(cls=self.__class__.__name__))
result = self._compare_lenient(other)
else:
# Perform "strict" equality.
logger.debug("strict", extra=dict(cls=self.__class__.__name__))
def func(field):
left = getattr(self, field)
right = getattr(other, field)
if self._is_attributes(field, left, right):
result = self._compare_strict_attributes(left, right)
else:
result = left == right
return result
# Note that, for strict we use "_fields" not "_members".
# TODO: refactor so that 'non-participants' can be held in their specific subclasses.
# Certain members never participate in strict equivalence, so
# are filtered out.
fields = filter(
lambda field: field
not in (
"circular",
"location_axis",
"node_dimension",
"edge_dimension",
"face_dimension",
),
self._fields,
)
result = all([func(field) for field in fields])
return result
def __lt__(self, other):
#
# Support Python2 behaviour for a "<" operation involving a
# "NoneType" operand.
#
if not isinstance(other, self.__class__):
return NotImplemented
def _sort_key(item):
keys = []
for field in item._fields:
if field != "attributes":
value = getattr(item, field)
keys.extend((value is not None, value))
return tuple(keys)
return _sort_key(self) < _sort_key(other)
def __ne__(self, other):
result = self.__eq__(other)
if result is not NotImplemented:
result = not result
return result
def __str__(self):
field_strings = []
for field in self._fields:
value = getattr(self, field)
if value is None or isinstance(value, (str, Mapping)) and not value:
continue
field_strings.append(f"{field}={value}")
return f"{type(self).__name__}({', '.join(field_strings)})"
def _api_common(self, other, func_service, func_operation, action, lenient=None):
"""Perform common entry-point for lenient metadata API methods.
Parameters
----------
other : metadata
A metadata instance of the same type.
func_service : callable
The parent service method offering the API entry-point to the service.
func_operation : callable
The parent service method that provides the actual service.
action : str
The verb describing the service operation.
lenient : bool, optional
Enable/disable the lenient service operation. The default is to automatically
detect whether this lenient service operation is enabled.
Returns
-------
The result of the service operation to the parent service caller.
"""
# Ensure that we have similar class instances.
if not hasattr(other, "__class__") or other.__class__ is not self.__class__:
emsg = "Cannot {} {!r} with {!r}."
raise TypeError(emsg.format(action, self.__class__.__name__, type(other)))
if lenient is None:
result = func_operation(other)
else:
if lenient:
# Use qualname to disassociate from the instance bounded method.
args, kwargs = (qualname(func_service),), dict()
else:
# Use qualname to guarantee that the instance bounded method
# is a hashable key.
args, kwargs = (), {qualname(func_service): False}
with _LENIENT.context(*args, **kwargs):
result = func_operation(other)
return result
def _combine(self, other):
"""Perform associated metadata member combination."""
if _LENIENT(self.combine):
# Perform "lenient" combine.
logger.debug("lenient", extra=dict(cls=self.__class__.__name__))
values = self._combine_lenient(other)
else:
# Perform "strict" combine.
logger.debug("strict", extra=dict(cls=self.__class__.__name__))
def func(field):
left = getattr(self, field)
right = getattr(other, field)
if self._is_attributes(field, left, right):
result = self._combine_strict_attributes(left, right)
else:
result = left if left == right else None
return result
# Note that, for strict we use "_fields" not "_members".
values = [func(field) for field in self._fields]
return values
def _combine_lenient(self, other):
"""Perform lenient combination of metadata members.
Parameters
----------
other : BaseMetadata
The other metadata participating in the lenient combination.
Returns
-------
A list of combined metadata member values.
"""
def func(field):
left = getattr(self, field)
right = getattr(other, field)
result = None
if field == "units":
# Perform "strict" combination for "units".
result = left if left == right else None
elif self._is_attributes(field, left, right):
result = self._combine_lenient_attributes(left, right)
else:
if left == right:
result = left
elif left is None:
result = right
elif right is None:
result = left
return result
# Note that, we use "_members" not "_fields".
return [func(field) for field in BaseMetadata._members]
@staticmethod
def _combine_lenient_attributes(left, right):
"""Leniently combine the dictionary members together."""
# Copy the dictionaries.
left = deepcopy(left)
right = deepcopy(right)
# Use xxhash to perform an extremely fast non-cryptographic hash of
# each dictionary key rvalue, thus ensuring that the dictionary is
# completely hashable, as required by a set.
sleft = {(k, hexdigest(v)) for k, v in left.items()}
sright = {(k, hexdigest(v)) for k, v in right.items()}
# Intersection of common items.
common = sleft & sright
# Items in sleft different from sright.
dsleft = dict(sleft - sright)
# Items in sright different from sleft.
dsright = dict(sright - sleft)
# Intersection of common item keys with different values.
keys = set(dsleft.keys()) & set(dsright.keys())
# Remove (in-place) common item keys with different values.
[dsleft.pop(key) for key in keys]
[dsright.pop(key) for key in keys]
# Now bring the result together.
result = {k: left[k] for k, _ in common}
result.update({k: left[k] for k in dsleft.keys()})
result.update({k: right[k] for k in dsright.keys()})
return result
@staticmethod
def _combine_strict_attributes(left, right):
"""Perform strict combination of the dictionary members."""
# Copy the dictionaries.
left = deepcopy(left)
right = deepcopy(right)
# Use xxhash to perform an extremely fast non-cryptographic hash of
# each dictionary key rvalue, thus ensuring that the dictionary is
# completely hashable, as required by a set.
sleft = {(k, hexdigest(v)) for k, v in left.items()}
sright = {(k, hexdigest(v)) for k, v in right.items()}
# Intersection of common items.
common = sleft & sright
# Now bring the result together.
result = {k: left[k] for k, _ in common}
return result
def _compare_lenient(self, other):
"""Perform lenient equality of metadata members.
Parameters
----------
other : BaseMetadata
The other metadata participating in the lenient comparison.
Returns
-------
bool
"""
result = False
# Use the "name" method to leniently compare "standard_name",
# "long_name", and "var_name" in a well defined way.
if self.name() == other.name():
def func(field):
left = getattr(self, field)
right = getattr(other, field)
if field == "units":
# Perform "strict" compare for "units".
result = left == right
elif self._is_attributes(field, left, right):
result = self._compare_lenient_attributes(left, right)
else:
# Perform "lenient" compare for members.
result = (left == right) or left is None or right is None
return result
# Note that, we use "_members" not "_fields".
# Lenient equality explicitly ignores the "var_name" member.
result = all(
[func(field) for field in BaseMetadata._members if field != "var_name"]
)
return result
@staticmethod
def _compare_lenient_attributes(left, right):
"""Perform lenient compare between the dictionary members."""
# Use xxhash to perform an extremely fast non-cryptographic hash of
# each dictionary key rvalue, thus ensuring that the dictionary is
# completely hashable, as required by a set.
sleft = {(k, hexdigest(v)) for k, v in left.items()}
sright = {(k, hexdigest(v)) for k, v in right.items()}
# Items in sleft different from sright.
dsleft = dict(sleft - sright)
# Items in sright different from sleft.
dsright = dict(sright - sleft)
# Intersection of common item keys with different values.
keys = set(dsleft.keys()) & set(dsright.keys())
return not bool(keys)
@staticmethod
def _compare_strict_attributes(left, right):
"""Perform strict compare between the dictionary members."""
# Use xxhash to perform an extremely fast non-cryptographic hash of
# each dictionary key rvalue, thus ensuring that the dictionary is
# completely hashable, as required by a set.
sleft = {(k, hexdigest(v)) for k, v in left.items()}
sright = {(k, hexdigest(v)) for k, v in right.items()}
return sleft == sright
def _difference(self, other):
"""Perform associated metadata member difference."""
if _LENIENT(self.difference):
# Perform "lenient" difference.
logger.debug("lenient", extra=dict(cls=self.__class__.__name__))
values = self._difference_lenient(other)
else:
# Perform "strict" difference.
logger.debug("strict", extra=dict(cls=self.__class__.__name__))
def func(field):
left = getattr(self, field)
right = getattr(other, field)
if self._is_attributes(field, left, right):
result = self._difference_strict_attributes(left, right)
else:
result = None if left == right else (left, right)
return result
# Note that, for strict we use "_fields" not "_members".
values = [func(field) for field in self._fields]
return values
def _difference_lenient(self, other):
"""Perform lenient difference of metadata members.
Parameters
----------
other : BaseMetadata
The other metadata participating in the lenient difference.
Returns
-------
A list of difference metadata member values.
"""
def func(field):
left = getattr(self, field)
right = getattr(other, field)
if field == "units":
# Perform "strict" difference for "units".
result = None if left == right else (left, right)
elif self._is_attributes(field, left, right):
result = self._difference_lenient_attributes(left, right)
else:
# Perform "lenient" difference for members.
result = (
(left, right)
if left is not None and right is not None and left != right
else None
)
return result
# Note that, we use "_members" not "_fields".
return [func(field) for field in BaseMetadata._members]
@staticmethod
def _difference_lenient_attributes(left, right):
"""Perform lenient difference between the dictionary members."""
# Use xxhash to perform an extremely fast non-cryptographic hash of
# each dictionary key rvalue, thus ensuring that the dictionary is
# completely hashable, as required by a set.
sleft = {(k, hexdigest(v)) for k, v in left.items()}
sright = {(k, hexdigest(v)) for k, v in right.items()}
# Items in sleft different from sright.
dsleft = dict(sleft - sright)
# Items in sright different from sleft.
dsright = dict(sright - sleft)
# Intersection of common item keys with different values.
keys = set(dsleft.keys()) & set(dsright.keys())
# Keep (in-place) common item keys with different values.
[dsleft.pop(key) for key in list(dsleft.keys()) if key not in keys]
[dsright.pop(key) for key in list(dsright.keys()) if key not in keys]
if not bool(dsleft) and not bool(dsright):
result = None
else:
# Replace hash-rvalue with original rvalue.
dsleft = {k: left[k] for k in dsleft.keys()}
dsright = {k: right[k] for k in dsright.keys()}
result = (dsleft, dsright)
return result
@staticmethod
def _difference_strict_attributes(left, right):
"""Perform strict difference between the dictionary members."""
# Use xxhash to perform an extremely fast non-cryptographic hash of
# each dictionary key rvalue, thus ensuring that the dictionary is
# completely hashable, as required by a set.
sleft = {(k, hexdigest(v)) for k, v in left.items()}
sright = {(k, hexdigest(v)) for k, v in right.items()}
# Items in sleft different from sright.
dsleft = dict(sleft - sright)
# Items in sright different from sleft.
dsright = dict(sright - sleft)
if not bool(dsleft) and not bool(dsright):
result = None
else:
# Replace hash-rvalue with original rvalue.
dsleft = {k: left[k] for k in dsleft.keys()}
dsright = {k: right[k] for k in dsright.keys()}
result = (dsleft, dsright)
return result
@staticmethod
def _is_attributes(field, left, right):
"""Determine whether we have two 'attributes' dictionaries."""
return (
field == "attributes"
and isinstance(left, Mapping)
and isinstance(right, Mapping)
)
@lenient_service
def combine(self, other, lenient=None):
"""Return a new metadata instance created by combining each of the associated metadata members.
Parameters
----------
other : metadata
A metadata instance of the same type.
lenient : bool, optional
Enable/disable lenient combination. The default is to automatically
detect whether this lenient operation is enabled.
Returns
-------
Metadata instance.
"""
result = self._api_common(
other, self.combine, self._combine, "combine", lenient=lenient
)
return self.__class__(*result)
@lenient_service
def difference(self, other, lenient=None):
"""Perform lenient metadata difference operation.
Return a new metadata instance created by performing a difference
comparison between each of the associated metadata members.
A metadata member returned with a value of "None" indicates that there
is no difference between the members being compared. Otherwise, a tuple
of the different values is returned.
Parameters
----------
other : metadata
A metadata instance of the same type.
lenient : bool, optional
Enable/disable lenient difference. The default is to automatically
detect whether this lenient operation is enabled.
Returns
-------
Metadata instance of member differences or None.
"""
result = self._api_common(
other, self.difference, self._difference, "differ", lenient=lenient
)
result = (
None if all([item is None for item in result]) else self.__class__(*result)
)
return result
@lenient_service
def equal(self, other, lenient=None):
"""Determine whether the associated metadata members are equivalent.
Parameters
----------
other : metadata
A metadata instance of the same type.
lenient : bool, optional
Enable/disable lenient equivalence. The default is to automatically
detect whether this lenient operation is enabled.
Returns
-------
bool
"""
result = self._api_common(
other, self.equal, self.__eq__, "compare", lenient=lenient
)
return result
@classmethod
def from_metadata(cls, other):
"""Convert metadata instance to this metadata type.
Convert the provided metadata instance from a different type
to this metadata type, using only the relevant metadata members.
Non-common metadata members are set to ``None``.
Parameters
----------
other : metadata
A metadata instance of any type.
Returns
-------
New metadata instance.
"""
result = None
if isinstance(other, BaseMetadata):
if other.__class__ is cls:
result = other
else:
kwargs = {field: None for field in cls._fields}
fields = set(cls._fields) & set(other._fields)
for field in fields:
kwargs[field] = getattr(other, field)
result = cls(**kwargs)
return result
def name(self, default: str | None = None, token: bool = False) -> str:
"""Return a string name representing the identity of the metadata.
First it tries standard name, then it tries the long name, then
the NetCDF variable name, before falling-back to a default value,
which itself defaults to the string 'unknown'.
Parameters
----------
default :
The fall-back string representing the default name. Defaults to
the string 'unknown'.
token :
If True, ensures that the name returned satisfies the criteria for
the characters required by a valid NetCDF name. If it is not
possible to return a valid name, then a ValueError exception is
raised. Defaults to False.
Returns
-------
str
"""
def _check(item):
return self.token(item) if token else item
default = self.DEFAULT_NAME if default is None else default
result = (
_check(self.standard_name)
or _check(self.long_name)
or _check(self.var_name)
or _check(default)
)
if token and result is None:
emsg = "Cannot retrieve a valid name token from {!r}"
raise ValueError(emsg.format(self))
return result
@classmethod
def token(cls, name):
"""Verify validity of provided NetCDF name.
Determine whether the provided name is a valid NetCDF name and thus
safe to represent a single parsable token.
Parameters
----------
name : str
The string name to verify.
Returns
-------
The provided name if valid, otherwise None.
"""
if name is not None:
result = _TOKEN_PARSE.match(name)
name = result if result is None else name
return name
class AncillaryVariableMetadata(BaseMetadata):
"""Metadata container for a :class:`~iris.coords.AncillaryVariableMetadata`."""
__slots__ = ()
@wraps(BaseMetadata.__eq__, assigned=("__doc__",), updated=())
@lenient_service
def __eq__(self, other):
return super().__eq__(other)
@wraps(BaseMetadata.combine, assigned=("__doc__",), updated=())
@lenient_service
def combine(self, other, lenient=None):
return super().combine(other, lenient=lenient)
@wraps(BaseMetadata.difference, assigned=("__doc__",), updated=())
@lenient_service
def difference(self, other, lenient=None):
return super().difference(other, lenient=lenient)
@wraps(BaseMetadata.equal, assigned=("__doc__",), updated=())
@lenient_service
def equal(self, other, lenient=None):
return super().equal(other, lenient=lenient)
class CellMeasureMetadata(BaseMetadata):
"""Metadata container for a :class:`~iris.coords.CellMeasure`."""
_members = "measure"
__slots__ = ()
@wraps(BaseMetadata.__eq__, assigned=("__doc__",), updated=())
@lenient_service
def __eq__(self, other):
return super().__eq__(other)
def _combine_lenient(self, other):
"""Perform lenient combination of metadata members for cell measures.
Parameters
----------
other : CellMeasureMetadata
The other cell measure metadata participating in the lenient
combination.
Returns
-------
A list of combined metadata member values.
"""
# Perform "strict" combination for "measure".
value = self.measure if self.measure == other.measure else None
# Perform lenient combination of the other parent members.
result = super()._combine_lenient(other)
result.append(value)
return result
def _compare_lenient(self, other):
"""Perform lenient equality of metadata members for cell measures.
Parameters
----------
other : CellMeasureMetadata
The other cell measure metadata participating in the lenient
comparison.
Returns
-------
bool
"""
# Perform "strict" comparison for "measure".
result = self.measure == other.measure
if result:
# Perform lenient comparison of the other parent members.
result = super()._compare_lenient(other)
return result
def _difference_lenient(self, other):
"""Perform lenient difference of metadata members for cell measures.
Parameters
----------
other : CellMeasureMetadata
The other cell measure metadata participating in the lenient
difference.
Returns
-------
A list of difference metadata member values.
"""
# Perform "strict" difference for "measure".
value = None if self.measure == other.measure else (self.measure, other.measure)
# Perform lenient difference of the other parent members.
result = super()._difference_lenient(other)
result.append(value)
return result
@wraps(BaseMetadata.combine, assigned=("__doc__",), updated=())
@lenient_service
def combine(self, other, lenient=None):
return super().combine(other, lenient=lenient)
@wraps(BaseMetadata.difference, assigned=("__doc__",), updated=())
@lenient_service
def difference(self, other, lenient=None):
return super().difference(other, lenient=lenient)
@wraps(BaseMetadata.equal, assigned=("__doc__",), updated=())
@lenient_service
def equal(self, other, lenient=None):
return super().equal(other, lenient=lenient)
class CoordMetadata(BaseMetadata):
"""Metadata container for a :class:`~iris.coords.Coord`."""
_members: str | Iterable[str] = ("coord_system", "climatological")
__slots__ = ()
@wraps(BaseMetadata.__eq__, assigned=("__doc__",), updated=())
@lenient_service
def __eq__(self, other):
# Convert a DimCoordMetadata instance to a CoordMetadata instance.
if (
self.__class__ is CoordMetadata
and hasattr(other, "__class__")
and other.__class__ is DimCoordMetadata
):
other = self.from_metadata(other)
return super().__eq__(other)
def __lt__(self, other):
#
# Support Python2 behaviour for a "<" operation involving a
# "NoneType" operand.
#
if not isinstance(other, BaseMetadata):
return NotImplemented
if other.__class__ is DimCoordMetadata:
other = self.from_metadata(other)
if not isinstance(other, self.__class__):
return NotImplemented
def _sort_key(item):
keys = []
for field in item._fields:
if field not in ("attributes", "coord_system"):
value = getattr(item, field)
keys.extend((value is not None, value))
return tuple(keys)
return _sort_key(self) < _sort_key(other)
def _combine_lenient(self, other):
"""Perform lenient combination of metadata members for coordinates.
Parameters
----------
other : CoordMetadata
The other coordinate metadata participating in the lenient
combination.
Returns
-------
A list of combined metadata member values.
"""
# Perform "strict" combination for "coord_system" and "climatological".
def func(field):
left = getattr(self, field)
right = getattr(other, field)
return left if left == right else None
# Note that, we use "_members" not "_fields".
values = [func(field) for field in CoordMetadata._members]
# Perform lenient combination of the other parent members.
result = super()._combine_lenient(other)
result.extend(values)
return result
def _compare_lenient(self, other):
"""Perform lenient equality of metadata members for coordinates.
Parameters
----------
other : CoordMetadata
The other coordinate metadata participating in the lenient
comparison.
Returns
-------
bool
"""
# Perform "strict" comparison for "coord_system" and "climatological".
result = all(
[
getattr(self, field) == getattr(other, field)
for field in CoordMetadata._members
]
)
if result:
# Perform lenient comparison of the other parent members.
result = super()._compare_lenient(other)
return result
def _difference_lenient(self, other):
"""Perform lenient difference of metadata members for coordinates.
Parameters
----------
other : CoordMetadata
The other coordinate metadata participating in the lenient
difference.
Returns
-------
A list of difference metadata member values.
"""
# Perform "strict" difference for "coord_system" and "climatological".
def func(field):
left = getattr(self, field)