-
Notifications
You must be signed in to change notification settings - Fork 282
/
_concatenate.py
1490 lines (1217 loc) · 53.8 KB
/
_concatenate.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.
"""Automatic concatenation of multiple cubes over one or more existing dimensions."""
from collections import namedtuple
from collections.abc import Sequence
import itertools
from typing import Any, Iterable
import warnings
import dask
import dask.array as da
from dask.base import tokenize
import numpy as np
from xxhash import xxh3_64_digest
from iris._lazy_data import concatenate as concatenate_arrays
import iris.coords
import iris.cube
import iris.exceptions
from iris.util import array_equal, guess_coord_axis
import iris.warnings
#
# TODO:
#
# * Cope with auxiliary coordinate factories.
#
# * Allow concatenation over a user specified dimension.
#
# Restrict the names imported from this namespace.
__all__ = ["concatenate"]
# Direction of dimension coordinate value order.
_CONSTANT = 0
_DECREASING = -1
_INCREASING = 1
class _CoordAndDims(namedtuple("CoordAndDims", ["coord", "dims"])):
"""Container for a coordinate and the associated data dimension(s).
Container for a coordinate and the associated data dimension(s)
spanned over a :class:`iris.cube.Cube`.
Parameters
----------
coord : :class:`iris.coords.DimCoord` or :class:`iris.coords.AuxCoord`
dims : tuple
A tuple of the data dimension(s) spanned by the coordinate.
"""
__slots__ = ()
class _CoordMetaData(
namedtuple(
"CoordMetaData",
["defn", "dims", "points_dtype", "bounds_dtype", "kwargs"],
)
):
"""Container for the metadata that defines a dimension or auxiliary coordinate.
Parameters
----------
defn : :class:`iris.common.CoordMetadata`
The :class:`iris.common.CoordMetadata` metadata that represents a
coordinate.
dims :
The dimension(s) associated with the coordinate.
points_dtype : :class:`np.dtype`
The points data :class:`np.dtype` of an associated coordinate.
bounds_dtype : :class:`np.dtype`
The bounds data :class:`np.dtype` of an associated coordinate.
**kwargs : dict, optional
A dictionary of key/value pairs required to define a coordinate.
"""
def __new__(mcs, coord, dims):
"""Create a new :class:`_CoordMetaData` instance.
Parameters
----------
coord : :class:`iris.coord.DimCoord` or :class:`iris.coord.AuxCoord`
dims :
The dimension(s) associated with the coordinate.
Returns
-------
The new class instance.
"""
defn = coord.metadata
points_dtype = coord.core_points().dtype
bounds_dtype = (
coord.core_bounds().dtype if coord.core_bounds() is not None else None
)
kwargs = {}
# Add scalar flag metadata.
kwargs["scalar"] = coord.core_points().size == 1
# Add circular flag metadata for dimensional coordinates.
if hasattr(coord, "circular"):
kwargs["circular"] = coord.circular
if isinstance(coord, iris.coords.DimCoord):
# Mix the monotonic ordering into the metadata.
if coord.points[0] == coord.points[-1]:
order = _CONSTANT
elif coord.points[-1] > coord.points[0]:
order = _INCREASING
else:
order = _DECREASING
kwargs["order"] = order
metadata = super().__new__(mcs, defn, dims, points_dtype, bounds_dtype, kwargs)
return metadata
__slots__ = ()
def __hash__(self):
return super().__hash__()
def __eq__(self, other):
result = NotImplemented
if isinstance(other, _CoordMetaData):
sprops, oprops = self._asdict(), other._asdict()
# Ignore "kwargs" meta-data for the first comparison.
sprops["kwargs"] = oprops["kwargs"] = None
result = sprops == oprops
if result:
skwargs, okwargs = self.kwargs.copy(), other.kwargs.copy()
# Monotonic "order" only applies to DimCoord's.
# The monotonic "order" must be _INCREASING or _DECREASING if
# the DimCoord is NOT "scalar". Otherwise, if the DimCoord is
# "scalar" then the "order" must be _CONSTANT.
if skwargs["scalar"] or okwargs["scalar"]:
# We don't care about the monotonic "order" given that
# at least one coordinate is a scalar coordinate.
skwargs["scalar"] = okwargs["scalar"] = None
skwargs["order"] = okwargs["order"] = None
result = skwargs == okwargs
return result
def __ne__(self, other):
result = self.__eq__(other)
if result is not NotImplemented:
result = not result
return result
def name(self):
"""Get the name from the coordinate definition."""
return self.defn.name()
class _DerivedCoordAndDims(
namedtuple("DerivedCoordAndDims", ["coord", "dims", "aux_factory"])
):
"""Container for a derived coordinate and dimensions(s).
Container for a derived coordinate, the associated AuxCoordFactory, and the
associated data dimension(s) spanned over a :class:`iris.cube.Cube`.
Parameters
----------
coord : :class:`iris.coord.DimCoord` or :class:`iris.coord.AuxCoord`
dims : tuple
A tuple of the data dimension(s) spanned by the coordinate.
aux_factory : :class:`iris.aux_factory.AuxCoordFactory`
"""
__slots__ = ()
def __eq__(self, other):
"""Do not take aux factories into account for equality."""
result = NotImplemented
if isinstance(other, _DerivedCoordAndDims):
equal_coords = self.coord == other.coord
equal_dims = self.dims == other.dims
result = equal_coords and equal_dims
return result
class _OtherMetaData(namedtuple("OtherMetaData", ["defn", "dims"])):
"""Container for the metadata that defines a cell measure or ancillary variable.
Parameters
----------
defn : :class:`iris.coords._DMDefn` or :class:`iris.coords._CellMeasureDefn`
The :class:`iris.coords._DMDefn` or :class:`iris.coords._CellMeasureDefn`
metadata that represents a coordinate.
dims :
The dimension(s) associated with the coordinate.
"""
def __new__(cls, ancil, dims):
"""Create a new :class:`_OtherMetaData` instance.
Parameters
----------
ancil : :class:`iris.coord.CellMeasure` or :class:`iris.coord.AncillaryVariable`
dims :
The dimension(s) associated with ancil.
Returns
-------
The new class instance.
"""
defn = ancil.metadata
metadata = super().__new__(cls, defn, dims)
return metadata
__slots__ = ()
def __hash__(self):
return super().__hash__()
def __eq__(self, other):
result = NotImplemented
if isinstance(other, _OtherMetaData):
result = self._asdict() == other._asdict()
return result
def __ne__(self, other):
result = self.__eq__(other)
if result is not NotImplemented:
result = not result
return result
def name(self):
"""Get the name from the coordinate definition."""
return self.defn.name()
class _SkeletonCube(namedtuple("SkeletonCube", ["signature", "data"])):
"""Basis of a source-cube.
Basis of a source-cube, containing the associated coordinate metadata,
coordinates and cube data payload.
Parameters
----------
signature : :class:`_CoordSignature`
The :class:`_CoordSignature` of an associated source-cube.
data :
The data payload of an associated :class:`iris.cube.Cube` source-cube.
"""
__slots__ = ()
class _Extent(namedtuple("Extent", ["min", "max"])):
"""Container representing the limits of a one-dimensional extent/range.
Parameters
----------
min :
The minimum value of the extent.
max :
The maximum value of the extent.
"""
__slots__ = ()
class _CoordExtent(namedtuple("CoordExtent", ["points", "bounds"])):
"""Container representing the points and bounds extent of a one dimensional coordinate.
Parameters
----------
points : :class:`_Extent`
The :class:`_Extent` of the coordinate point values.
bounds :
A list containing the :class:`_Extent` of the coordinate lower
bound and the upper bound. Defaults to None if no associated
bounds exist for the coordinate.
"""
__slots__ = ()
def _hash_array(a: da.Array | np.ndarray) -> np.int64:
"""Calculate a hash representation of the provided array.
Calculates a 64-bit non-cryptographic hash of the provided array, using
the fast ``xxhash`` hashing algorithm.
Note that the computed hash depends on how the array is chunked.
Parameters
----------
a :
The array that requires to have its hexdigest calculated.
Returns
-------
np.int64
The array's hash.
"""
def arrayhash(x):
return np.frombuffer(xxh3_64_digest(x.tobytes()), dtype=np.int64)
return da.reduction(
a,
chunk=lambda x, axis, keepdims: arrayhash(x).reshape((1,) * a.ndim),
combine=lambda x, axis, keepdims: arrayhash(x).reshape((1,) * a.ndim),
aggregate=lambda x, axis, keepdims: arrayhash(x)[0],
keepdims=False,
meta=np.empty(tuple(), dtype=np.int64),
dtype=np.int64,
)
class _ArrayHash(namedtuple("ArrayHash", ["value", "chunks"])):
"""Container for a hash value and the chunks used when computing it.
Parameters
----------
value : :class:`np.int64`
The hash value.
chunks : tuple
The chunks the array had when the hash was computed.
"""
__slots__ = ()
def __eq__(self, other: Any) -> bool:
if not isinstance(other, self.__class__):
return NotImplemented
if self.chunks != other.chunks:
raise ValueError(
"Unable to compare arrays with different chunks: "
f"{self.chunks} != {other.chunks}"
)
return self.value == other.value
def array_id(array: np.ndarray | da.Array) -> str:
"""Get a deterministic token representing `array`."""
if isinstance(array, np.ma.MaskedArray):
# Tokenizing a masked array is much slower than separately tokenizing
# the data and mask.
return tokenize((tokenize(array.data), tokenize(array.mask)))
return tokenize(array)
def _compute_hashes(arrays: Iterable[np.ndarray | da.Array]) -> dict[str, _ArrayHash]:
"""Compute hashes for the arrays that will be compared."""
def is_numerical(dtype):
return np.issubdtype(dtype, np.bool_) or np.issubdtype(dtype, np.number)
def group_key(a):
if is_numerical(a.dtype):
dtype = "numerical"
else:
dtype = str(a.dtype)
return a.shape, dtype
hashes = {}
arrays = sorted(arrays, key=group_key)
for _, group_iter in itertools.groupby(arrays, key=group_key):
group = list(group_iter)
# Unify dtype for numerical arrays, as the hash depends on it
if is_numerical(group[0].dtype):
dtype = np.result_type(*group)
same_dtype_arrays = [a.astype(dtype) for a in group]
else:
same_dtype_arrays = group
# Unify chunks as the hash depends on the chunks.
indices = tuple(range(group[0].ndim))[::-1]
argpairs = [(a, indices) for a in same_dtype_arrays]
rechunked_arrays = da.core.unify_chunks(*itertools.chain(*argpairs))[1]
for array, rechunked in zip(group, rechunked_arrays):
hashes[array_id(array)] = (
_hash_array(rechunked),
rechunked.chunks,
)
hashes = dask.compute(hashes)[0]
return {k: _ArrayHash(*v) for k, v in hashes.items()}
def concatenate(
cubes: Sequence[iris.cube.Cube],
error_on_mismatch: bool = False,
check_aux_coords: bool = True,
check_cell_measures: bool = True,
check_ancils: bool = True,
check_derived_coords: bool = True,
) -> iris.cube.CubeList:
"""Concatenate the provided cubes over common existing dimensions.
Parameters
----------
cubes : iterable of :class:`iris.cube.Cube`
An iterable containing one or more :class:`iris.cube.Cube` instances
to be concatenated together.
error_on_mismatch : bool, default=False
If True, raise an informative
:class:`~iris.exceptions.ContatenateError` if registration fails.
check_aux_coords : bool, default=True
Checks if the points and bounds of auxiliary coordinates of the cubes
match. This check is not applied to auxiliary coordinates that span the
dimension the concatenation is occurring along. Defaults to True.
check_cell_measures : bool, default=True
Checks if the data of cell measures of the cubes match. This check is
not applied to cell measures that span the dimension the concatenation
is occurring along. Defaults to True.
check_ancils : bool, default=True
Checks if the data of ancillary variables of the cubes match. This
check is not applied to ancillary variables that span the dimension the
concatenation is occurring along. Defaults to True.
check_derived_coords : bool, default=True
Checks if the points and bounds of derived coordinates of the cubes
match. This check is not applied to derived coordinates that span the
dimension the concatenation is occurring along. Note that differences
in scalar coordinates and dimensional coordinates used to derive the
coordinate are still checked. Checks for auxiliary coordinates used to
derive the coordinates can be ignored with `check_aux_coords`. Defaults
to True.
Returns
-------
:class:`iris.cube.CubeList`
A :class:`iris.cube.CubeList` of concatenated :class:`iris.cube.Cube` instances.
"""
proto_cubes: list[_ProtoCube] = []
# Initialise the nominated axis (dimension) of concatenation
# which requires to be negotiated.
axis = None
# Compute hashes for parallel array comparison.
arrays = []
for cube in cubes:
if check_aux_coords:
for coord in cube.aux_coords:
arrays.append(coord.core_points())
if coord.has_bounds():
arrays.append(coord.core_bounds())
if check_derived_coords:
for coord in cube.derived_coords:
arrays.append(coord.core_points())
if coord.has_bounds():
arrays.append(coord.core_bounds())
if check_cell_measures:
for var in cube.cell_measures():
arrays.append(var.core_data())
if check_ancils:
for var in cube.ancillary_variables():
arrays.append(var.core_data())
hashes = _compute_hashes(arrays)
# Register each cube with its appropriate proto-cube.
for cube in cubes:
registered = False
# Register cube with an existing proto-cube.
for proto_cube in proto_cubes:
registered = proto_cube.register(
cube,
hashes,
axis,
error_on_mismatch,
check_aux_coords,
check_cell_measures,
check_ancils,
check_derived_coords,
)
if registered:
axis = proto_cube.axis
break
# Create a new proto-cube for an unregistered cube.
if not registered:
proto_cubes.append(_ProtoCube(cube))
# Construct a concatenated cube from each of the proto-cubes.
concatenated_cubes = iris.cube.CubeList()
# Emulate Python 2 behaviour.
def _none_sort(proto_cube):
return (proto_cube.name is not None, proto_cube.name)
for proto_cube in sorted(proto_cubes, key=_none_sort):
concatenated_cubes.append(proto_cube.concatenate())
# Perform concatenation until we've reached an equilibrium.
count = len(concatenated_cubes)
if count != 1 and count != len(cubes):
concatenated_cubes = concatenate(concatenated_cubes)
return concatenated_cubes
class _CubeSignature:
"""Template for identifying a specific type of :class:`iris.cube.Cube`.
Template for identifying a specific type of :class:`iris.cube.Cube` based
on its metadata, coordinates and cell_measures.
"""
def __init__(self, cube: iris.cube.Cube) -> None:
"""Represent the cube metadata and associated coordinate metadata.
Parameters
----------
cube : :class:`iris.cube.Cube`
The :class:`iris.cube.Cube` source-cube.
"""
self.aux_coords_and_dims = []
self.aux_metadata = []
self.dim_coords = cube.dim_coords
self.dim_metadata = []
self.ndim = cube.ndim
self.scalar_coords = []
self.cell_measures_and_dims = []
self.cm_metadata = []
self.ancillary_variables_and_dims = []
self.av_metadata = []
self.derived_coords_and_dims = []
self.derived_metadata = []
self.dim_mapping = []
# Determine whether there are any anonymous cube dimensions.
covered = set(cube.coord_dims(coord)[0] for coord in self.dim_coords)
self.anonymous = covered != set(range(self.ndim))
self.defn = cube.metadata
self.data_type = cube.dtype
#
# Collate the dimension coordinate metadata.
#
for coord in self.dim_coords:
dims = cube.coord_dims(coord)
metadata = _CoordMetaData(coord, dims)
self.dim_metadata.append(metadata)
self.dim_mapping.append(dims[0])
#
# Collate the auxiliary coordinate metadata and scalar coordinates.
#
axes = dict(T=0, Z=1, Y=2, X=3)
# Coordinate sort function - by guessed coordinate axis, then
# by coordinate name, then by dimensions, in ascending order.
def key_func(coord):
return (
axes.get(guess_coord_axis(coord), len(axes) + 1),
coord.name(),
cube.coord_dims(coord),
)
for coord in sorted(cube.aux_coords, key=key_func):
dims = cube.coord_dims(coord)
if dims:
metadata = _CoordMetaData(coord, dims)
self.aux_metadata.append(metadata)
coord_and_dims = _CoordAndDims(coord, tuple(dims))
self.aux_coords_and_dims.append(coord_and_dims)
else:
self.scalar_coords.append(coord)
def meta_key_func(dm):
return (dm.metadata, dm.cube_dims(cube))
for cm in sorted(cube.cell_measures(), key=meta_key_func):
dims = cube.cell_measure_dims(cm)
metadata = _OtherMetaData(cm, dims)
self.cm_metadata.append(metadata)
cm_and_dims = _CoordAndDims(cm, tuple(dims))
self.cell_measures_and_dims.append(cm_and_dims)
for av in sorted(cube.ancillary_variables(), key=meta_key_func):
dims = cube.ancillary_variable_dims(av)
metadata = _OtherMetaData(av, dims)
self.av_metadata.append(metadata)
av_and_dims = _CoordAndDims(av, tuple(dims))
self.ancillary_variables_and_dims.append(av_and_dims)
def name_key_func(factory):
return factory.name()
for factory in sorted(cube.aux_factories, key=name_key_func):
coord = factory.make_coord(cube.coord_dims)
dims = cube.coord_dims(coord)
metadata = _CoordMetaData(coord, dims)
self.derived_metadata.append(metadata)
coord_and_dims = _DerivedCoordAndDims(coord, tuple(dims), factory)
self.derived_coords_and_dims.append(coord_and_dims)
def _coordinate_differences(self, other, attr, reason="metadata"):
"""Determine the names of the coordinates that differ.
Determine the names of the coordinates that differ between `self` and
`other` for a coordinate attribute on a _CubeSignature.
Parameters
----------
other : _CubeSignature
The _CubeSignature to compare against.
attr : str
The _CubeSignature attribute within which differences exist
between `self` and `other`.
reason : str, default="metadata"
The reason to give for mismatch (function is normally, but not
always, testing metadata).
Returns
-------
tuple
Tuple of a descriptive error message and the names of attributes
that differ between `self` and `other`.
"""
# Set up {name: attribute} dictionaries.
self_dict = {x.name(): x for x in getattr(self, attr)}
other_dict = {x.name(): x for x in getattr(other, attr)}
if len(self_dict) == 0:
self_dict = {"< None >": None}
if len(other_dict) == 0:
other_dict = {"< None >": None}
self_names = sorted(self_dict.keys())
other_names = sorted(other_dict.keys())
# Compare coord attributes.
if len(self_names) != len(other_names) or self_names != other_names:
result = ("", ", ".join(self_names), ", ".join(other_names))
else:
diff_names = []
for self_key, self_value in self_dict.items():
other_value = other_dict[self_key]
if self_value != other_value:
diff_names.append(self_key)
result = (
" " + reason,
", ".join(diff_names),
", ".join(diff_names),
)
return result
def match(self, other, error_on_mismatch):
"""Return whether this _CubeSignature equals another.
This is the first step to determine if two "cubes" (either a
real Cube or a ProtoCube) can be concatenated, by considering:
* data dimensions
* aux coords metadata
* scalar coords
* attributes
* dtype
Parameters
----------
other : _CubeSignature
The _CubeSignature to compare against.
error_on_mismatch : bool
If True, raise a :class:`~iris.exceptions.MergeException`
with a detailed explanation if the two do not match.
Returns
-------
bool
True if and only if this _CubeSignature matches the other.
"""
msg_template = "{}{} differ: {} != {}"
msgs = []
# Check cube definitions.
if self.defn != other.defn:
# Note that the case of different phenomenon names is dealt
# with in :meth:`iris.cube.CubeList.concatenate_cube()`.
msg = "Cube metadata differs for phenomenon: {}"
msgs.append(msg.format(self.defn.name()))
# Check dim coordinates.
if self.dim_metadata != other.dim_metadata:
differences = self._coordinate_differences(other, "dim_metadata")
msgs.append(msg_template.format("Dimension coordinates", *differences))
# Check aux coordinates.
if self.aux_metadata != other.aux_metadata:
differences = self._coordinate_differences(other, "aux_metadata")
msgs.append(msg_template.format("Auxiliary coordinates", *differences))
# Check cell measures.
if self.cm_metadata != other.cm_metadata:
differences = self._coordinate_differences(other, "cm_metadata")
msgs.append(msg_template.format("Cell measures", *differences))
# Check ancillary variables.
if self.av_metadata != other.av_metadata:
differences = self._coordinate_differences(other, "av_metadata")
msgs.append(msg_template.format("Ancillary variables", *differences))
# Check derived coordinates.
if self.derived_metadata != other.derived_metadata:
differences = self._coordinate_differences(other, "derived_metadata")
msgs.append(msg_template.format("Derived coordinates", *differences))
# Check scalar coordinates.
if self.scalar_coords != other.scalar_coords:
differences = self._coordinate_differences(
other, "scalar_coords", reason="values or metadata"
)
msgs.append(msg_template.format("Scalar coordinates", *differences))
# Check ndim.
if self.ndim != other.ndim:
msgs.append(
msg_template.format("Data dimensions", "", self.ndim, other.ndim)
)
# Check data type.
if self.data_type != other.data_type:
msgs.append(
msg_template.format("Data types", "", self.data_type, other.data_type)
)
match = not bool(msgs)
if error_on_mismatch and not match:
raise iris.exceptions.ConcatenateError(msgs)
return match
class _CoordSignature:
"""Template for identifying a specific type of :class:`iris.cube.Cube` based on its coordinates."""
def __init__(self, cube_signature: _CubeSignature) -> None:
"""Represent the coordinate metadata.
Represent the coordinate metadata required to identify suitable
non-overlapping :class:`iris.cube.Cube` source-cubes for
concatenation over a common single dimension.
Parameters
----------
cube_signature : :class:`_CubeSignature`
The :class:`_CubeSignature` that defines the source-cube.
"""
self.aux_coords_and_dims = cube_signature.aux_coords_and_dims
self.cell_measures_and_dims = cube_signature.cell_measures_and_dims
self.ancillary_variables_and_dims = cube_signature.ancillary_variables_and_dims
self.derived_coords_and_dims = cube_signature.derived_coords_and_dims
self.dim_coords = cube_signature.dim_coords
self.dim_mapping = cube_signature.dim_mapping
self.dim_extents: list[_CoordExtent] = []
self.dim_order = [
metadata.kwargs["order"] for metadata in cube_signature.dim_metadata
]
# Calculate the extents for each dimensional coordinate.
self._calculate_extents()
@staticmethod
def _cmp(
coord: iris.coords.DimCoord,
other: iris.coords.DimCoord,
) -> tuple[bool, bool]:
"""Compare the coordinates for concatenation compatibility.
Returns
-------
bool tuple
A boolean tuple pair of whether the coordinates are compatible,
and whether they represent a candidate axis of concatenation.
"""
# A candidate axis must have non-identical coordinate points.
candidate_axis = not array_equal(coord.points, other.points)
# Ensure both have equal availability of bounds.
result = coord.has_bounds() == other.has_bounds()
if result and not candidate_axis:
# Ensure equality of bounds.
result = array_equal(coord.bounds, other.bounds)
return result, candidate_axis
def candidate_axis(self, other: "_CoordSignature") -> int | None:
"""Determine the candidate axis of concatenation with the given coordinate signature.
If a candidate axis is found, then the coordinate
signatures are compatible.
Parameters
----------
other : :class:`_CoordSignature`
Returns
-------
result :
None if no single candidate axis exists, otherwise the candidate
axis of concatenation.
"""
result = False
candidate_axes = []
# Compare dimension coordinates.
for ind, coord in enumerate(self.dim_coords):
result, candidate_axis = self._cmp(coord, other.dim_coords[ind])
if not result:
break
if candidate_axis:
dim = self.dim_mapping[ind]
candidate_axes.append(dim)
# Only permit one degree of dimensional freedom when
# determining the candidate axis of concatenation.
if result and len(candidate_axes) == 1:
axis = candidate_axes[0]
else:
axis = None
return axis
def _calculate_extents(self) -> None:
"""Calculate the extent over each dimension coordinates points and bounds."""
self.dim_extents = []
for coord, order in zip(self.dim_coords, self.dim_order):
if order == _CONSTANT or order == _INCREASING:
points = _Extent(coord.points[0], coord.points[-1])
if coord.bounds is not None:
bounds = (
_Extent(coord.bounds[0, 0], coord.bounds[-1, 0]),
_Extent(coord.bounds[0, 1], coord.bounds[-1, 1]),
)
else:
bounds = None
else:
# The order must be decreasing ...
points = _Extent(coord.points[-1], coord.points[0])
if coord.bounds is not None:
bounds = (
_Extent(coord.bounds[-1, 0], coord.bounds[0, 0]),
_Extent(coord.bounds[-1, 1], coord.bounds[0, 1]),
)
else:
bounds = None
self.dim_extents.append(_CoordExtent(points, bounds))
class _ProtoCube:
"""Framework for concatenating multiple source-cubes over one common dimension."""
def __init__(self, cube):
"""Create a new _ProtoCube from the given cube and record the cube as a source-cube.
Parameters
----------
cube :
Source :class:`iris.cube.Cube` of the :class:`_ProtoCube`.
"""
# Cache the source-cube of this proto-cube.
self._cube = cube
# The cube signature is a combination of cube and coordinate
# metadata that defines this proto-cube.
self._cube_signature = _CubeSignature(cube)
# The coordinate signature allows suitable non-overlapping
# source-cubes to be identified.
self._coord_signature = _CoordSignature(self._cube_signature)
# The list of source-cubes relevant to this proto-cube.
self._skeletons = []
self._add_skeleton(self._coord_signature, cube.lazy_data())
# The nominated axis of concatenation.
self._axis = None
@property
def axis(self):
"""Return the nominated dimension of concatenation."""
return self._axis
@property
def name(self) -> str | None:
"""Return the standard_name or long name."""
metadata = self._cube_signature.defn
return metadata.standard_name or metadata.long_name
def concatenate(self):
"""Concatenate all the source-cubes registered with the :class:`_ProtoCube`.
Concatenate all the source-cubes registered with the
:class:`_ProtoCube` over the nominated common dimension.
Returns
-------
:class:`iris.cube.Cube`
The concatenated :class:`iris.cube.Cube`.
"""
if len(self._skeletons) > 1:
skeletons = self._skeletons
dim_ind = self._coord_signature.dim_mapping.index(self.axis)
order = self._coord_signature.dim_order[dim_ind]
cube_signature = self._cube_signature
# Sequence the skeleton segments into the correct order
# pending concatenation.
skeletons.sort(
key=lambda skeleton: skeleton.signature.dim_extents,
reverse=(order == _DECREASING),
)
# Concatenate the new dimension coordinate.
dim_coords_and_dims = self._build_dim_coordinates()
# Concatenate the new auxiliary coordinates (does NOT include
# scalar coordinates!).
aux_coords_and_dims = self._build_aux_coordinates()
# Concatenate the new scalar coordinates.
scalar_coords = self._build_scalar_coordinates()
# Concatenate the new cell measures
cell_measures_and_dims = self._build_cell_measures()
# Concatenate the new ancillary variables
ancillary_variables_and_dims = self._build_ancillary_variables()
# Concatenate the new aux factories
aux_factories = self._build_aux_factories(
dim_coords_and_dims, aux_coords_and_dims, scalar_coords
)
# Concatenate the new data payload.
data = self._build_data()
# Build the new cube.
all_aux_coords_and_dims = aux_coords_and_dims + [
(scalar_coord, ()) for scalar_coord in scalar_coords
]
kwargs = cube_signature.defn._asdict()
cube = iris.cube.Cube(
data,
dim_coords_and_dims=dim_coords_and_dims,
aux_coords_and_dims=all_aux_coords_and_dims,
cell_measures_and_dims=cell_measures_and_dims,
ancillary_variables_and_dims=ancillary_variables_and_dims,
aux_factories=aux_factories,
**kwargs,
)
else:
# There are no other source-cubes to concatenate
# with this proto-cube.
cube = self._cube
return cube
def register(
self,
cube: iris.cube.Cube,
hashes: dict[str, _ArrayHash],
axis: int | None = None,
error_on_mismatch: bool = False,
check_aux_coords: bool = False,
check_cell_measures: bool = False,
check_ancils: bool = False,
check_derived_coords: bool = False,
) -> bool:
"""Determine if the given source-cube is suitable for concatenation.
Determine if the given source-cube is suitable for concatenation
with this :class:`_ProtoCube`.
Parameters
----------
cube : :class:`iris.cube.Cube`
The :class:`iris.cube.Cube` source-cube candidate for
concatenation.
axis : optional
Seed the dimension of concatenation for the :class:`_ProtoCube`
rather than rely on negotiation with source-cubes.
error_on_mismatch : bool, default=False
If True, raise an informative error if registration fails.
check_aux_coords : bool, default=False
Checks if the points and bounds of auxiliary coordinates of the
cubes match. This check is not applied to auxiliary coordinates
that span the dimension the concatenation is occurring along.
Defaults to False.
check_cell_measures : bool, default=False