-
Notifications
You must be signed in to change notification settings - Fork 279
/
cube.py
4921 lines (4113 loc) · 186 KB
/
cube.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.
"""Classes for representing multi-dimensional data with metadata."""
from collections import OrderedDict
import copy
from copy import deepcopy
from functools import partial, reduce
import itertools
import operator
from typing import (
Container,
Iterable,
Iterator,
Mapping,
MutableMapping,
Optional,
Union,
)
from xml.dom.minidom import Document
import zlib
from cf_units import Unit
import dask.array as da
import numpy as np
import numpy.ma as ma
import iris._constraints
from iris._data_manager import DataManager
import iris._lazy_data as _lazy
import iris._merge
import iris.analysis
from iris.analysis import _Weights
from iris.analysis.cartography import wrap_lons
import iris.analysis.maths
import iris.aux_factory
from iris.common import CFVariableMixin, CubeMetadata, metadata_manager_factory
from iris.common.metadata import metadata_filter
from iris.common.mixin import LimitedAttributeDict
import iris.coord_systems
import iris.coords
import iris.exceptions
from iris.exceptions import warn_once_at_level
import iris.util
__all__ = ["Cube", "CubeAttrsDict", "CubeList"]
# The XML namespace to use for CubeML documents
XML_NAMESPACE_URI = "urn:x-iris:cubeml-0.2"
class _CubeFilter:
"""A constraint, paired with a list of cubes matching that constraint."""
def __init__(self, constraint, cubes=None):
self.constraint = constraint
if cubes is None:
cubes = CubeList()
self.cubes = cubes
def __len__(self):
return len(self.cubes)
def add(self, cube):
"""Add the appropriate (sub)cube to the list of cubes where it matches the constraint."""
sub_cube = self.constraint.extract(cube)
if sub_cube is not None:
self.cubes.append(sub_cube)
def merged(self, unique=False):
"""Return a new :class:`_CubeFilter` by merging the list of cubes.
Parameters
----------
unique : bool, default=False
If True, raises `iris.exceptions.DuplicateDataError` if
duplicate cubes are detected.
"""
return _CubeFilter(self.constraint, self.cubes.merge(unique))
class _CubeFilterCollection:
"""A list of _CubeFilter instances."""
@staticmethod
def from_cubes(cubes, constraints=None):
"""Create a new collection from an iterable of cubes, and some optional constraints."""
constraints = iris._constraints.list_of_constraints(constraints)
pairs = [_CubeFilter(constraint) for constraint in constraints]
collection = _CubeFilterCollection(pairs)
for cube in cubes:
collection.add_cube(cube)
return collection
def __init__(self, pairs):
self.pairs = pairs
def add_cube(self, cube):
"""Add the given :class:`~iris.cube.Cube` to all of the relevant constraint pairs."""
for pair in self.pairs:
pair.add(cube)
def cubes(self):
"""Return all the cubes in this collection concatenated into a single :class:`CubeList`."""
result = CubeList()
for pair in self.pairs:
result.extend(pair.cubes)
return result
def merged(self, unique=False):
"""Return a new :class:`_CubeFilterCollection` by merging all the cube lists of this collection.
Parameters
----------
unique : bool, default=False
If True, raises `iris.exceptions.DuplicateDataError` if
duplicate cubes are detected.
"""
return _CubeFilterCollection([pair.merged(unique) for pair in self.pairs])
class CubeList(list):
"""All the functionality of a standard :class:`list` with added "Cube" context."""
def __init__(self, *args, **kwargs):
"""Given an iterable of cubes, return a CubeList instance."""
# Do whatever a list does, to initialise ourself "as a list"
super().__init__(*args, **kwargs)
# Check that all items in the list are cubes.
for cube in self:
self._assert_is_cube(cube)
def __str__(self):
"""Run short :meth:`Cube.summary` on every cube."""
result = [
"%s: %s" % (i, cube.summary(shorten=True)) for i, cube in enumerate(self)
]
if result:
result = "\n".join(result)
else:
result = "< No cubes >"
return result
def __repr__(self):
"""Run repr on every cube."""
return "[%s]" % ",\n".join([repr(cube) for cube in self])
@staticmethod
def _assert_is_cube(obj):
if not hasattr(obj, "add_aux_coord"):
msg = r"Object {obj} cannot be put in a cubelist, as it is not a Cube."
raise ValueError(msg)
def _repr_html_(self):
from iris.experimental.representation import CubeListRepresentation
representer = CubeListRepresentation(self)
return representer.repr_html()
# TODO #370 Which operators need overloads?
def __add__(self, other):
return CubeList(list.__add__(self, other))
def __getitem__(self, keys):
"""x.__getitem__(y) <==> x[y]."""
result = super().__getitem__(keys)
if isinstance(result, list):
result = CubeList(result)
return result
def __getslice__(self, start, stop):
"""x.__getslice__(i, j) <==> x[i:j].
Use of negative indices is not supported.
"""
result = super().__getslice__(start, stop)
result = CubeList(result)
return result
def __iadd__(self, other_cubes):
"""Add a sequence of cubes to the cubelist in place."""
return super(CubeList, self).__iadd__(CubeList(other_cubes))
def __setitem__(self, key, cube_or_sequence):
"""Set self[key] to cube or sequence of cubes."""
if isinstance(key, int):
# should have single cube.
self._assert_is_cube(cube_or_sequence)
else:
# key is a slice (or exception will come from list method).
cube_or_sequence = CubeList(cube_or_sequence)
super(CubeList, self).__setitem__(key, cube_or_sequence)
def append(self, cube):
"""Append a cube."""
self._assert_is_cube(cube)
super(CubeList, self).append(cube)
def extend(self, other_cubes):
"""Extend cubelist by appending the cubes contained in other_cubes.
Parameters
----------
other_cubes :
A cubelist or other sequence of cubes.
"""
super(CubeList, self).extend(CubeList(other_cubes))
def insert(self, index, cube):
"""Insert a cube before index."""
self._assert_is_cube(cube)
super(CubeList, self).insert(index, cube)
def xml(self, checksum=False, order=True, byteorder=True):
"""Return a string of the XML that this list of cubes represents."""
doc = Document()
cubes_xml_element = doc.createElement("cubes")
cubes_xml_element.setAttribute("xmlns", XML_NAMESPACE_URI)
for cube_obj in self:
cubes_xml_element.appendChild(
cube_obj._xml_element(
doc, checksum=checksum, order=order, byteorder=byteorder
)
)
doc.appendChild(cubes_xml_element)
# return our newly created XML string
doc = Cube._sort_xml_attrs(doc)
return doc.toprettyxml(indent=" ")
def extract(self, constraints):
"""Filter each of the cubes which can be filtered by the given constraints.
This method iterates over each constraint given, and subsets each of
the cubes in this CubeList where possible. Thus, a CubeList of length
**n** when filtered with **m** constraints can generate a maximum of
**m * n** cubes.
Parameters
----------
constraints : :class:`~iris.Constraint` or iterable of constraints
A single constraint or an iterable.
"""
return self._extract_and_merge(self, constraints, strict=False)
def extract_cube(self, constraint):
"""Extract a single cube from a CubeList, and return it.
Extract a single cube from a CubeList, and return it.
Raise an error if the extract produces no cubes, or more than one.
Parameters
----------
constraint : :class:`~iris.Constraint`
The constraint to extract with.
See Also
--------
:meth:`~iris.cube.CubeList.extract`
"""
# Just validate this, so we can accept strings etc, but not multiples.
constraint = iris._constraints.as_constraint(constraint)
return self._extract_and_merge(
self, constraint, strict=True, return_single_cube=True
)
def extract_cubes(self, constraints):
"""Extract specific cubes from a CubeList, one for each given constraint.
Extract specific cubes from a CubeList, one for each given constraint.
Each constraint must produce exactly one cube, otherwise an error is
raised.
Parameters
----------
constraints : iter of, or single, :class:`~iris.Constraint`
The constraints to extract with.
See Also
--------
:meth:`~iris.cube.CubeList.extract`
"""
return self._extract_and_merge(
self, constraints, strict=True, return_single_cube=False
)
@staticmethod
def _extract_and_merge(cubes, constraints, strict=False, return_single_cube=False):
constraints = iris._constraints.list_of_constraints(constraints)
# group the resultant cubes by constraints in a dictionary
constraint_groups = dict(
[(constraint, CubeList()) for constraint in constraints]
)
for cube in cubes:
for constraint, cube_list in constraint_groups.items():
sub_cube = constraint.extract(cube)
if sub_cube is not None:
cube_list.append(sub_cube)
result = CubeList()
for constraint in constraints:
constraint_cubes = constraint_groups[constraint]
if strict and len(constraint_cubes) != 1:
msg = "Got %s cubes for constraint %r, expecting 1." % (
len(constraint_cubes),
constraint,
)
raise iris.exceptions.ConstraintMismatchError(msg)
result.extend(constraint_cubes)
if return_single_cube:
if len(result) != 1:
# Practically this should never occur, as we now *only* request
# single cube result for 'extract_cube'.
msg = "Got {!s} cubes for constraints {!r}, expecting 1."
raise iris.exceptions.ConstraintMismatchError(
msg.format(len(result), constraints)
)
result = result[0]
return result
def extract_overlapping(self, coord_names):
"""Return a :class:`CubeList` of cubes extracted over regions.
Return a :class:`CubeList` of cubes extracted over regions
where the coordinates overlap, for the coordinates
in coord_names.
Parameters
----------
coord_names : str or list of str
A string or list of strings of the names of the coordinates
over which to perform the extraction.
"""
if isinstance(coord_names, str):
coord_names = [coord_names]
def make_overlap_fn(coord_name):
def overlap_fn(cell):
return all(cell in cube.coord(coord_name).cells() for cube in self)
return overlap_fn
coord_values = {
coord_name: make_overlap_fn(coord_name) for coord_name in coord_names
}
return self.extract(iris.Constraint(coord_values=coord_values))
def merge_cube(self):
"""Return the merged contents of the :class:`CubeList` as a single :class:`Cube`.
If it is not possible to merge the `CubeList` into a single
`Cube`, a :class:`~iris.exceptions.MergeError` will be raised
describing the reason for the failure.
For example:
>>> cube_1 = iris.cube.Cube([1, 2])
>>> cube_1.add_aux_coord(iris.coords.AuxCoord(0, long_name='x'))
>>> cube_2 = iris.cube.Cube([3, 4])
>>> cube_2.add_aux_coord(iris.coords.AuxCoord(1, long_name='x'))
>>> cube_2.add_dim_coord(
... iris.coords.DimCoord([0, 1], long_name='z'), 0)
>>> single_cube = iris.cube.CubeList([cube_1, cube_2]).merge_cube()
Traceback (most recent call last):
...
iris.exceptions.MergeError: failed to merge into a single cube.
Coordinates in cube.dim_coords differ: z.
Coordinate-to-dimension mapping differs for cube.dim_coords.
"""
if not self:
raise ValueError("can't merge an empty CubeList")
# Register each of our cubes with a single ProtoCube.
proto_cube = iris._merge.ProtoCube(self[0])
for cube in self[1:]:
proto_cube.register(cube, error_on_mismatch=True)
# Extract the merged cube from the ProtoCube.
(merged_cube,) = proto_cube.merge()
return merged_cube
def merge(self, unique=True):
"""Return the :class:`CubeList` resulting from merging this :class:`CubeList`.
Parameters
----------
unique : bool, default=True
If True, raises `iris.exceptions.DuplicateDataError` if
duplicate cubes are detected.
Examples
--------
This combines cubes with different values of an auxiliary scalar
coordinate, by constructing a new dimension.
.. testsetup::
import iris
c1 = iris.cube.Cube([0,1,2], long_name='some_parameter')
xco = iris.coords.DimCoord([11, 12, 13], long_name='x_vals')
c1.add_dim_coord(xco, 0)
c1.add_aux_coord(iris.coords.AuxCoord([100], long_name='y_vals'))
c2 = c1.copy()
c2.coord('y_vals').points = [200]
::
>>> print(c1)
some_parameter / (unknown) (x_vals: 3)
Dimension coordinates:
x_vals x
Scalar coordinates:
y_vals: 100
>>> print(c2)
some_parameter / (unknown) (x_vals: 3)
Dimension coordinates:
x_vals x
Scalar coordinates:
y_vals: 200
>>> cube_list = iris.cube.CubeList([c1, c2])
>>> new_cube = cube_list.merge()[0]
>>> print(new_cube)
some_parameter / (unknown) (y_vals: 2; x_vals: 3)
Dimension coordinates:
y_vals x -
x_vals - x
>>> print(new_cube.coord('y_vals').points)
[100 200]
>>>
Contrast this with :meth:`iris.cube.CubeList.concatenate`, which joins
cubes along an existing dimension.
.. note::
Cubes may contain additional dimensional elements such as auxiliary
coordinates, cell measures or ancillary variables.
A group of similar cubes can only merge to a single result if all such
elements are identical in every input cube : they are then present,
unchanged, in the merged output cube.
.. note::
If time coordinates in the list of cubes have differing epochs then
the cubes will not be able to be merged. If this occurs, use
:func:`iris.util.unify_time_units` to normalise the epochs of the
time coordinates so that the cubes can be merged.
"""
# Register each of our cubes with its appropriate ProtoCube.
proto_cubes_by_name = {}
for cube in self:
name = cube.standard_name
proto_cubes = proto_cubes_by_name.setdefault(name, [])
proto_cube = None
for target_proto_cube in proto_cubes:
if target_proto_cube.register(cube):
proto_cube = target_proto_cube
break
if proto_cube is None:
proto_cube = iris._merge.ProtoCube(cube)
proto_cubes.append(proto_cube)
# Emulate Python 2 behaviour.
def _none_sort(item):
return (item is not None, item)
# Extract all the merged cubes from the ProtoCubes.
merged_cubes = CubeList()
for name in sorted(proto_cubes_by_name, key=_none_sort):
for proto_cube in proto_cubes_by_name[name]:
merged_cubes.extend(proto_cube.merge(unique=unique))
return merged_cubes
def concatenate_cube(
self,
check_aux_coords=True,
check_cell_measures=True,
check_ancils=True,
check_derived_coords=True,
):
"""Return the concatenated contents of the :class:`CubeList` as a single :class:`Cube`.
If it is not possible to concatenate the `CubeList` into a single
`Cube`, a :class:`~iris.exceptions.ConcatenateError` will be raised
describing the reason for the failure.
Parameters
----------
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.
Notes
-----
.. note::
Concatenation cannot occur along an anonymous dimension.
"""
from iris._concatenate import concatenate
if not self:
raise ValueError("can't concatenate an empty CubeList")
names = [cube.metadata.name() for cube in self]
unique_names = list(OrderedDict.fromkeys(names))
if len(unique_names) == 1:
res = concatenate(
self,
error_on_mismatch=True,
check_aux_coords=check_aux_coords,
check_cell_measures=check_cell_measures,
check_ancils=check_ancils,
check_derived_coords=check_derived_coords,
)
n_res_cubes = len(res)
if n_res_cubes == 1:
return res[0]
else:
msgs = []
msgs.append("An unexpected problem prevented concatenation.")
msgs.append(
"Expected only a single cube, found {}.".format(n_res_cubes)
)
raise iris.exceptions.ConcatenateError(msgs)
else:
msgs = []
msgs.append(
"Cube names differ: {} != {}".format(unique_names[0], unique_names[1])
)
raise iris.exceptions.ConcatenateError(msgs)
def concatenate(
self,
check_aux_coords=True,
check_cell_measures=True,
check_ancils=True,
check_derived_coords=True,
):
"""Concatenate the cubes over their common dimensions.
Parameters
----------
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 new :class:`iris.cube.CubeList` of concatenated
:class:`iris.cube.Cube` instances.
Notes
-----
This combines cubes with a common dimension coordinate, but occupying
different regions of the coordinate value. The cubes are joined across
that dimension.
.. testsetup::
import iris
import numpy as np
xco = iris.coords.DimCoord([11, 12, 13, 14], long_name='x_vals')
yco1 = iris.coords.DimCoord([4, 5], long_name='y_vals')
yco2 = iris.coords.DimCoord([7, 9, 10], long_name='y_vals')
c1 = iris.cube.Cube(np.zeros((2,4)), long_name='some_parameter')
c1.add_dim_coord(xco, 1)
c1.add_dim_coord(yco1, 0)
c2 = iris.cube.Cube(np.zeros((3,4)), long_name='some_parameter')
c2.add_dim_coord(xco, 1)
c2.add_dim_coord(yco2, 0)
For example::
>>> print(c1)
some_parameter / (unknown) (y_vals: 2; x_vals: 4)
Dimension coordinates:
y_vals x -
x_vals - x
>>> print(c1.coord('y_vals').points)
[4 5]
>>> print(c2)
some_parameter / (unknown) (y_vals: 3; x_vals: 4)
Dimension coordinates:
y_vals x -
x_vals - x
>>> print(c2.coord('y_vals').points)
[ 7 9 10]
>>> cube_list = iris.cube.CubeList([c1, c2])
>>> new_cube = cube_list.concatenate()[0]
>>> print(new_cube)
some_parameter / (unknown) (y_vals: 5; x_vals: 4)
Dimension coordinates:
y_vals x -
x_vals - x
>>> print(new_cube.coord('y_vals').points)
[ 4 5 7 9 10]
>>>
Contrast this with :meth:`iris.cube.CubeList.merge`, which makes a new
dimension from values of an auxiliary scalar coordinate.
.. note::
Cubes may contain 'extra' dimensional elements such as auxiliary
coordinates, cell measures or ancillary variables.
For a group of similar cubes to concatenate together into one output, all
such elements which do not map to the concatenation axis must be identical
in every input cube : these then appear unchanged in the output.
Similarly, those elements which *do* map to the concatenation axis must
have matching properties, but may have different data values : these then
appear, concatenated, in the output cube.
If any cubes in a group have dimensional elements which do not match
correctly, the group will not concatenate to a single output cube.
.. note::
If time coordinates in the list of cubes have differing epochs then
the cubes will not be able to be concatenated. If this occurs, use
:func:`iris.util.unify_time_units` to normalise the epochs of the
time coordinates so that the cubes can be concatenated.
.. note::
Concatenation cannot occur along an anonymous dimension.
"""
from iris._concatenate import concatenate
return concatenate(
self,
check_aux_coords=check_aux_coords,
check_cell_measures=check_cell_measures,
check_ancils=check_ancils,
check_derived_coords=check_derived_coords,
)
def realise_data(self):
"""Fetch 'real' data for all cubes, in a shared calculation.
This computes any lazy data, equivalent to accessing each `cube.data`.
However, lazy calculations and data fetches can be shared between the
computations, improving performance.
For example::
# Form stats.
a_std = cube_a.collapsed(['x', 'y'], iris.analysis.STD_DEV)
b_std = cube_b.collapsed(['x', 'y'], iris.analysis.STD_DEV)
ab_mean_diff = (cube_b - cube_a).collapsed(['x', 'y'],
iris.analysis.MEAN)
std_err = (a_std * a_std + b_std * b_std) ** 0.5
# Compute these stats together (avoiding multiple data passes).
CubeList([a_std, b_std, ab_mean_diff, std_err]).realise_data()
.. Note::
Cubes with non-lazy data are not affected.
"""
_lazy.co_realise_cubes(*self)
def copy(self):
"""Return a CubeList when CubeList.copy() is called."""
if isinstance(self, CubeList):
return deepcopy(self)
def _is_single_item(testee):
"""Return whether this is a single item, rather than an iterable.
We count string types as 'single', also.
"""
return isinstance(testee, str) or not isinstance(testee, Iterable)
class CubeAttrsDict(MutableMapping):
"""A :class:`dict`-like object for :attr:`iris.cube.Cube.attributes`.
A :class:`dict`-like object for :attr:`iris.cube.Cube.attributes`,
providing unified user access to combined cube "local" and "global" attributes
dictionaries, with the access behaviour of an ordinary (single) dictionary.
Properties :attr:`globals` and :attr:`locals` are regular
:class:`~iris.common.mixin.LimitedAttributeDict`, which can be accessed and
modified separately. The :class:`CubeAttrsDict` itself contains *no* additional
state, but simply provides a 'combined' view of both global + local attributes.
All the read- and write-type methods, such as ``get()``, ``update()``, ``values()``,
behave according to the logic documented for : :meth:`__getitem__`,
:meth:`__setitem__` and :meth:`__iter__`.
Notes
-----
For type testing, ``issubclass(CubeAttrsDict, Mapping)`` is ``True``, but
``issubclass(CubeAttrsDict, dict)`` is ``False``.
Examples
--------
>>> from iris.cube import Cube
>>> cube = Cube([0])
>>> # CF defines 'history' as global by default.
>>> cube.attributes.update({"history": "from test-123", "mycode": 3})
>>> print(cube.attributes)
{'history': 'from test-123', 'mycode': 3}
>>> print(repr(cube.attributes))
CubeAttrsDict(globals={'history': 'from test-123'}, locals={'mycode': 3})
>>> cube.attributes['history'] += ' +added'
>>> print(repr(cube.attributes))
CubeAttrsDict(globals={'history': 'from test-123 +added'}, locals={'mycode': 3})
>>> cube.attributes.locals['history'] = 'per-variable'
>>> print(cube.attributes)
{'history': 'per-variable', 'mycode': 3}
>>> print(repr(cube.attributes))
CubeAttrsDict(globals={'history': 'from test-123 +added'}, locals={'mycode': 3, 'history': 'per-variable'})
"""
# TODO: Create a 'further topic' / 'tech paper' on NetCDF I/O, including
# discussion of attribute handling.
def __init__(
self,
combined: Optional[Union[Mapping, str]] = "__unspecified",
locals: Optional[Mapping] = None,
globals: Optional[Mapping] = None,
):
"""Create a cube attributes dictionary.
We support initialisation from a single generic mapping input, using the default
global/local assignment rules explained at :meth:`__setattr__`, or from
two separate mappings. Two separate dicts can be passed in the ``locals``
and ``globals`` args, **or** via a ``combined`` arg which has its own
``.globals`` and ``.locals`` properties -- so this allows passing an existing
:class:`CubeAttrsDict`, which will be copied.
Parameters
----------
combined : dict
values to init both 'self.globals' and 'self.locals'. If 'combined' itself
has attributes named 'locals' and 'globals', these are used to update the
respective content (after initially setting the individual ones).
Otherwise, 'combined' is treated as a generic mapping, applied as
``self.update(combined)``,
i.e. it will set locals and/or globals with the same logic as
:meth:`~iris.cube.CubeAttrsDict.__setitem__` .
locals : dict
initial content for 'self.locals'
globals : dict
initial content for 'self.globals'
Examples
--------
>>> from iris.cube import CubeAttrsDict
>>> # CF defines 'history' as global by default.
>>> CubeAttrsDict({'history': 'data-story', 'comment': 'this-cube'})
CubeAttrsDict(globals={'history': 'data-story'}, locals={'comment': 'this-cube'})
>>> CubeAttrsDict(locals={'history': 'local-history'})
CubeAttrsDict(globals={}, locals={'history': 'local-history'})
>>> CubeAttrsDict(globals={'x': 'global'}, locals={'x': 'local'})
CubeAttrsDict(globals={'x': 'global'}, locals={'x': 'local'})
>>> x1 = CubeAttrsDict(globals={'x': 1}, locals={'y': 2})
>>> x2 = CubeAttrsDict(x1)
>>> x2
CubeAttrsDict(globals={'x': 1}, locals={'y': 2})
"""
# First initialise locals + globals, defaulting to empty.
self.locals = locals
self.globals = globals
# Update with combined, if present.
if not isinstance(combined, str) or combined != "__unspecified":
# Treat a single input with 'locals' and 'globals' properties as an
# existing CubeAttrsDict, and update from its content.
# N.B. enforce deep copying, consistent with general Iris usage.
if hasattr(combined, "globals") and hasattr(combined, "locals"):
# Copy a mapping with globals/locals, like another 'CubeAttrsDict'
self.globals.update(deepcopy(combined.globals))
self.locals.update(deepcopy(combined.locals))
else:
# Treat any arbitrary single input value as a mapping (dict), and
# update from it.
self.update(dict(deepcopy(combined)))
#
# Ensure that the stored local/global dictionaries are "LimitedAttributeDicts".
#
@staticmethod
def _normalise_attrs(
attributes: Optional[Mapping],
) -> LimitedAttributeDict:
# Convert an input attributes arg into a standard form.
# N.B. content is always a LimitedAttributeDict, and a deep copy of input.
# Allow arg of None, etc.
if not attributes:
attributes = {}
else:
attributes = deepcopy(attributes)
# Ensure the expected mapping type.
attributes = LimitedAttributeDict(attributes)
return attributes
@property
def locals(self) -> LimitedAttributeDict:
return self._locals
@locals.setter
def locals(self, attributes: Optional[Mapping]):
self._locals = self._normalise_attrs(attributes)
@property
def globals(self) -> LimitedAttributeDict:
return self._globals
@globals.setter
def globals(self, attributes: Optional[Mapping]):
self._globals = self._normalise_attrs(attributes)
#
# Provide a serialisation interface
#
def __getstate__(self):
return (self.locals, self.globals)
def __setstate__(self, state):
self.locals, self.globals = state
#
# Support comparison -- required because default operation only compares a single
# value at each key.
#
def __eq__(self, other):
# For equality, require both globals + locals to match exactly.
# NOTE: array content works correctly, since 'locals' and 'globals' are always
# iris.common.mixin.LimitedAttributeDict, which gets this right.
other = CubeAttrsDict(other)
result = self.locals == other.locals and self.globals == other.globals
return result
#
# Provide methods duplicating those for a 'dict', but which are *not* provided by
# MutableMapping, for compatibility with code which expected a cube.attributes to be
# a :class:`~iris.common.mixin.LimitedAttributeDict`.
# The extra required methods are :
# 'copy', 'update', '__ior__', '__or__', '__ror__' and 'fromkeys'.
#
def copy(self):
"""Return a copy.
Implemented with deep copying, consistent with general Iris usage.
"""
return CubeAttrsDict(self)
def update(self, *args, **kwargs):
"""Update by adding items from a mapping arg, or keyword-values.
If the argument is a split dictionary, preserve the local/global nature of its
keys.
"""
if args and hasattr(args[0], "globals") and hasattr(args[0], "locals"):
dic = args[0]
self.globals.update(dic.globals)
self.locals.update(dic.locals)
else:
super().update(*args)
super().update(**kwargs)
def __or__(self, arg):
"""Implement 'or' via 'update'."""
if not isinstance(arg, Mapping):
return NotImplemented
new_dict = self.copy()
new_dict.update(arg)
return new_dict
def __ior__(self, arg):
"""Implement 'ior' via 'update'."""
self.update(arg)
return self
def __ror__(self, arg):
"""Implement 'ror' via 'update'.
This needs to promote, such that the result is a CubeAttrsDict.
"""
if not isinstance(arg, Mapping):
return NotImplemented
result = CubeAttrsDict(arg)
result.update(self)
return result
@classmethod
def fromkeys(cls, iterable, value=None):
"""Create a new object with keys taken from an argument, all set to one value.
If the argument is a split dictionary, preserve the local/global nature of its
keys.
"""
if hasattr(iterable, "globals") and hasattr(iterable, "locals"):
# When main input is a split-attrs dict, create global/local parts from its
# global/local keys
result = cls(
globals=dict.fromkeys(iterable.globals, value),
locals=dict.fromkeys(iterable.locals, value),
)
else:
# Create from a dict.fromkeys, using default classification of the keys.
result = cls(dict.fromkeys(iterable, value))
return result
#
# The remaining methods are sufficient to generate a complete standard Mapping
# API. See -
# https://docs.python.org/3/reference/datamodel.html#emulating-container-types.
#
def __iter__(self):
"""Define the combined iteration order.
Result is: all global keys, then all local ones, but omitting duplicates.
"""
# NOTE: this means that in the "summary" view, attributes present in both
# locals+globals are listed first, amongst the globals, even though they appear
# with the *value* from locals.
# Otherwise follows order of insertion, as is normal for dicts.
return itertools.chain(
self.globals.keys(),
(x for x in self.locals.keys() if x not in self.globals),