-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathfield.py
More file actions
14429 lines (11769 loc) · 549 KB
/
field.py
File metadata and controls
14429 lines (11769 loc) · 549 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import logging
from dataclasses import dataclass
from functools import reduce
from operator import mul as operator_mul
import cfdm
import numpy as np
from cfdm import is_log_level_debug, is_log_level_detail, is_log_level_info
from . import (
AuxiliaryCoordinate,
Bounds,
CellMeasure,
CellMethod,
Constructs,
Count,
DimensionCoordinate,
Domain,
DomainAncillary,
DomainAxis,
FieldList,
Flags,
Index,
List,
Quantization,
mixin,
)
from .constants import masked as cf_masked
from .data import Data
from .data.array import (
GatheredArray,
RaggedContiguousArray,
RaggedIndexedArray,
RaggedIndexedContiguousArray,
)
from .decorators import (
_deprecated_kwarg_check,
_inplace_enabled,
_inplace_enabled_define_and_cleanup,
_manage_log_level_via_verbosity,
)
from .formula_terms import FormulaTerms
from .functions import (
_DEPRECATION_ERROR,
_DEPRECATION_ERROR_ARG,
_DEPRECATION_ERROR_ATTRIBUTE,
_DEPRECATION_ERROR_KWARG_VALUE,
_DEPRECATION_ERROR_KWARGS,
_DEPRECATION_ERROR_METHOD,
DeprecationError,
_section,
flat,
parse_indices,
)
from .functions import relaxed_identities as cf_relaxed_identities
from .functions import size as cf_size
from .query import Query, eq, ge, gt, le, lt
from .subspacefield import SubspaceField
from .timeduration import TimeDuration
from .units import Units
logger = logging.getLogger(__name__)
# --------------------------------------------------------------------
# Commonly used units
# --------------------------------------------------------------------
# _units_degrees = Units("degrees")
_units_radians = Units("radians")
_units_metres = Units("m")
_units_1 = Units("1")
# --------------------------------------------------------------------
# Map each allowed input collapse method name to its corresponding
# Data method. Input collapse methods not in this sictionary are
# assumed to have a corresponding Data method with the same name.
# --------------------------------------------------------------------
_collapse_methods = {
**{
name: name
for name in [
"mean", # results in 'mean': 'mean' entry, etc.
"mean_absolute_value",
"mean_of_upper_decile",
"max",
"maximum_absolute_value",
"min",
"max",
"minimum_absolute_value",
"mid_range",
"range",
"median",
"sd",
"sum",
"sum_of_squares",
"integral",
"root_mean_square",
"var",
"sample_size",
"sum_of_weights",
"sum_of_weights2",
]
},
**{ # non-identical mapped names:
"avg": "mean",
"average": "mean",
"maximum": "max",
"minimum": "min",
"standard_deviation": "sd",
"variance": "var",
},
}
# --------------------------------------------------------------------
# Map each allowed input collapse method name to its corresponding CF
# cell method.
# --------------------------------------------------------------------
_collapse_cell_methods = {
**{
name: name
for name in [
"point",
"mean",
"mean_absolute_value",
"mean_of_upper_decile",
"maximum",
"maximum_absolute_value",
"minimum",
"minimum_absolute_value",
"mid_range",
"range",
"median",
"standard_deviation",
"sum",
"root_mean_square",
"sum_of_squares",
"variance",
]
},
**{ # non-identical mapped names:
"avg": "mean",
"average": "mean",
"max": "maximum",
"min": "minimum",
"sd": "standard_deviation",
"integral": "sum",
"var": "variance",
"sample_size": "point",
"sum_of_weights": "sum",
"sum_of_weights2": "sum",
},
}
# --------------------------------------------------------------------
# These Data methods may be weighted
# --------------------------------------------------------------------
_collapse_weighted_methods = set(
(
"mean",
"mean_absolute_value",
"mean_of_upper_decile",
"avg",
"average",
"sd",
"standard_deviation",
"sum",
"var",
"variance",
"sum_of_weights",
"sum_of_weights2",
"integral",
"root_mean_square",
)
)
# --------------------------------------------------------------------
# These Data methods may specify a number of degrees of freedom
# --------------------------------------------------------------------
_collapse_ddof_methods = set(("sd", "var"))
_earth_radius = 6371229.0
_relational_methods = (
"__eq__",
"__ne__",
"__lt__",
"__le__",
"__gt__",
"__ge__",
)
@dataclass()
class _Axis_characterisation:
"""Characterise a domain axis.
Used by `_binary_operation` to help with ascertaining if there is
a common axis in two fields.
.. versionaddedd:: 3.16.3
"""
# The size of the axis, an integer.
size: int = -1
# The domain axis identifier. E.g. 'domainaxis0'
axis: str = ""
# The coordinate constructs that characterize the axis
coords: tuple = ()
# The identifiers of the coordinate
# constructs. E.g. ('dimensioncoordinate1',)
keys: tuple = ()
# Whether or not the axis is spanned by the field's data array
axis_in_data_axes: bool = True
class Field(mixin.FieldDomain, mixin.PropertiesData, cfdm.Field):
"""A field construct of the CF data model.
The field construct is central to the CF data model, and includes
all the other constructs. A field corresponds to a CF-netCDF data
variable with all of its metadata. All CF-netCDF elements are
mapped to a field construct or some element of the CF field
construct. The field construct contains all the data and metadata
which can be extracted from the file using the CF conventions.
The field construct consists of a data array and the definition of
its domain (that describes the locations of each cell of the data
array), field ancillary constructs containing metadata defined
over the same domain, and cell method constructs to describe how
the cell values represent the variation of the physical quantity
within the cells of the domain. The domain is defined collectively
by the following constructs of the CF data model: domain axis,
dimension coordinate, auxiliary coordinate, cell measure,
coordinate reference and domain ancillary constructs.
The field construct also has optional properties to describe
aspects of the data that are independent of the domain. These
correspond to some netCDF attributes of variables (e.g. units,
long_name and standard_name), and some netCDF global file
attributes (e.g. history and institution).
**NetCDF interface**
{{netCDF variable}}
{{netCDF global attributes}}
{{netCDF group attributes}}
{{netCDF geometry group}}
Some components exist within multiple constructs, but when written
to a netCDF dataset the netCDF names associated with such
components will be arbitrarily taken from one of them. The netCDF
variable, dimension and sample dimension names and group
structures for such components may be set or removed consistently
across all such components with the `nc_del_component_variable`,
`nc_set_component_variable`, `nc_set_component_variable_groups`,
`nc_clear_component_variable_groups`,
`nc_del_component_dimension`, `nc_set_component_dimension`,
`nc_set_component_dimension_groups`,
`nc_clear_component_dimension_groups`,
`nc_del_component_sample_dimension`,
`nc_set_component_sample_dimension`,
`nc_set_component_sample_dimension_groups`,
`nc_clear_component_sample_dimension_groups` methods.
CF-compliance issues for field constructs read from a netCDF
dataset may be accessed with the `dataset_compliance` method.
"""
def __new__(cls, *args, **kwargs):
"""Store component classes."""
instance = super().__new__(cls)
instance._AuxiliaryCoordinate = AuxiliaryCoordinate
instance._DimensionCoordinate = DimensionCoordinate
instance._Bounds = Bounds
instance._Constructs = Constructs
instance._Domain = Domain
instance._DomainAncillary = DomainAncillary
instance._DomainAxis = DomainAxis
instance._Quantization = Quantization
instance._RaggedContiguousArray = RaggedContiguousArray
instance._RaggedIndexedArray = RaggedIndexedArray
instance._RaggedIndexedContiguousArray = RaggedIndexedContiguousArray
instance._GatheredArray = GatheredArray
instance._Count = Count
instance._Index = Index
instance._List = List
return instance
_special_properties = mixin.PropertiesData._special_properties
_special_properties += ("flag_values", "flag_masks", "flag_meanings")
def __init__(
self, properties=None, source=None, copy=True, _use_data=True
):
"""**Initialisation**
:Parameters:
properties: `dict`, optional
Set descriptive properties. The dictionary keys are
property names, with corresponding values. Ignored if the
*source* parameter is set.
*Parameter example:*
``properties={'standard_name': 'air_temperature'}``
Properties may also be set after initialisation with the
`set_properties` and `set_property` methods.
{{init source: optional}}
{{init copy: `bool`, optional}}
"""
super().__init__(
properties=properties,
source=source,
copy=copy,
_use_data=_use_data,
)
if source:
flags = getattr(source, "Flags", None)
if flags is not None:
self.Flags = flags.copy()
def __getitem__(self, indices):
"""Return a subspace of the field construct defined by indices.
f.__getitem__(indices) <==> f[indices]
Subspacing by indexing uses rules that are very similar to the
numpy indexing rules, the only differences being:
* An integer index i specified for a dimension reduces the size of
this dimension to unity, taking just the i-th element, but keeps
the dimension itself, so that the rank of the array is not
reduced.
* When two or more dimensions’ indices are sequences of integers
then these indices work independently along each dimension
(similar to the way vector subscripts work in Fortran). This is
the same indexing behaviour as on a Variable object of the
netCDF4 package.
* For a dimension that is cyclic, a range of indices specified by
a `slice` that spans the edges of the data (such as ``-2:3`` or
``3:-2:-1``) is assumed to "wrap" around, rather then producing
a null result.
.. seealso:: `indices`, `squeeze`, `subspace`, `where`
**Examples**
>>> f.shape
(12, 73, 96)
>>> f[0].shape
(1, 73, 96)
>>> f[3, slice(10, 0, -2), 95:93:-1].shape
(1, 5, 2)
>>> f.shape
(12, 73, 96)
>>> f[:, [0, 72], [5, 4, 3]].shape
(12, 2, 3)
>>> f.shape
(12, 73, 96)
>>> f[...].shape
(12, 73, 96)
>>> f[slice(0, 12), :, 10:0:-2].shape
(12, 73, 5)
>>> f[[True, True, False, True, True, False, False, True, True, True,
... True, True]].shape
(9, 64, 128)
>>> f[..., :6, 9:1:-2, [1, 3, 4]].shape
(6, 4, 3)
"""
if indices is Ellipsis:
return self.copy()
data = self.data
shape = data.shape
# Parse the index
if not isinstance(indices, tuple):
indices = (indices,)
if isinstance(indices[0], str) and indices[0] == "mask":
ancillary_mask = indices[:2]
indices2 = indices[2:]
else:
ancillary_mask = None
indices2 = indices
indices, roll = parse_indices(shape, indices2, cyclic=True)
if roll:
new = self
axes = data._axes
cyclic_axes = data._cyclic
for iaxis, shift in roll.items():
axis = axes[iaxis]
if axis not in cyclic_axes:
_ = self.get_data_axes()[iaxis]
raise IndexError(
"Can't take a cyclic slice from non-cyclic "
f"{self.constructs.domain_axis_identity(_)!r} axis"
)
new = new.roll(axis=iaxis, shift=shift)
else:
new = self.copy()
data = new.data
# ------------------------------------------------------------
# Subspace the field construct's data
# ------------------------------------------------------------
if ancillary_mask:
ancillary_mask = list(ancillary_mask)
findices = ancillary_mask + indices
else:
findices = indices
new_data = data[tuple(findices)]
if 0 in new_data.shape:
raise IndexError(
f"Indices {findices!r} result in a subspaced shape of "
f"{new_data.shape}, but can't create a subspace of "
f"{self.__class__.__name__} that has a size 0 axis"
)
# Set sizes of domain axes
data_axes = new.get_data_axes()
domain_axes = new.domain_axes(todict=True)
for axis, size in zip(data_axes, new_data.shape):
domain_axes[axis].set_size(size)
# Record which axes were cyclic before the subspace
org_cyclic = [data_axes.index(axis) for axis in new.cyclic()]
# Set the subspaced data
new.set_data(new_data, axes=data_axes, copy=False)
# Update axis cylcicity. Note that this can only entail
# setting an originally cyclic axis to be non-cyclic. Doing
# this now enables us to disable the (possibly very slow)
# automatic check for cyclicity on the 'set_construct' calls
# below.
if org_cyclic:
new_cyclic = new_data.cyclic()
[
new.cyclic(i, iscyclic=False)
for i in org_cyclic
if i not in new_cyclic
]
# ------------------------------------------------------------
# Subspace constructs with data
# ------------------------------------------------------------
if data_axes:
construct_data_axes = new.constructs.data_axes()
for key, construct in new.constructs.filter_by_axis(
*data_axes, axis_mode="or", todict=True
).items():
construct_axes = construct_data_axes[key]
dice = []
needs_slicing = False
for axis in construct_axes:
if axis in data_axes:
needs_slicing = True
dice.append(indices[data_axes.index(axis)])
else:
dice.append(slice(None))
# Generally we do not apply an ancillary mask to the
# metadata items, but for DSGs we do.
if ancillary_mask and new.DSG:
item_mask = []
for mask in ancillary_mask[1]:
iaxes = [
data_axes.index(axis)
for axis in construct_axes
if axis in data_axes
]
for i, (axis, size) in enumerate(
zip(data_axes, mask.shape)
):
if axis not in construct_axes:
if size > 1:
iaxes = None
break
mask = mask.squeeze(i)
if iaxes is None:
item_mask = None
break
else:
mask1 = mask.transpose(iaxes)
for i, axis in enumerate(construct_axes):
if axis not in data_axes:
mask1.inset_dimension(i)
item_mask.append(mask1)
if item_mask:
needs_slicing = True
dice = [ancillary_mask[0], item_mask] + dice
# Replace existing construct with its subspace
if needs_slicing:
new.set_construct(
construct[tuple(dice)],
key=key,
axes=construct_axes,
copy=False,
autocyclic={"no-op": True},
)
return new
def __setitem__(self, indices, value):
"""Called to implement assignment to x[indices]=value.
x.__setitem__(indices, value) <==> x[indices]=value
.. versionadded:: 2.0
"""
if isinstance(value, self.__class__):
value = self._conform_for_assignment(value)
try:
data = value.get_data(None, _fill_value=False)
except AttributeError:
pass
else:
if data is None:
raise ValueError(
f"Can't assign to a {self.__class__.__name__} from a "
f"{value.__class__.__name__} with no data"
)
value = data
data = self.get_data(_fill_value=False)
data[indices] = value
# @property
# def _cyclic(self):
# """Storage for axis cyclicity.
#
# Do not change the value in-place.
#
# """
# return self._custom.get("_cyclic", _empty_set)
#
# @_cyclic.setter
# def _cyclic(self, value):
# """value must be a set.
#
# Do not change the value in-place.
#
# """
# self._custom["_cyclic"] = value
#
# @_cyclic.deleter
# def _cyclic(self):
# self._custom["_cyclic"] = _empty_set
def analyse_items(self, relaxed_identities=None):
"""Analyse a domain.
:Returns:
`dict`
A description of the domain.
**Examples**
>>> print(f)
Axes : time(3) = [1979-05-01 12:00:00, ..., 1979-05-03 12:00:00] gregorian
: air_pressure(5) = [850.000061035, ..., 50.0000038147] hPa
: grid_longitude(106) = [-20.5400109887, ..., 25.6599887609] degrees
: grid_latitude(110) = [23.3200002313, ..., -24.6399995089] degrees
Aux coords : latitude(grid_latitude(110), grid_longitude(106)) = [[67.1246607722, ..., 22.8886948065]] degrees_N
: longitude(grid_latitude(110), grid_longitude(106)) = [[-45.98136251, ..., 35.2925499052]] degrees_E
Coord refs : <CF CoordinateReference: rotated_latitude_longitude>
>>> f.analyse_items()
{
'dim_coords': {'dim0': <CF Dim ....>,
'aux_coords': {'N-d': {'aux0': <CF AuxiliaryCoordinate: latitude(110, 106) degrees_N>,
'aux1': <CF AuxiliaryCoordinate: longitude(110, 106) degrees_E>},
'dim0': {'1-d': {},
'N-d': {},},
'dim1': {'1-d': {},
'N-d': {},},
'dim2': {'1-d': {},
'N-d': {'aux0': <CF AuxiliaryCoordinate: latitude(110, 106) degrees_N>,
'aux1': <CF AuxiliaryCoordinate: longitude(110, 106) degrees_E>},},
'dim3': {'1-d': {},
'N-d': {'aux0': <CF AuxiliaryCoordinate: latitude(110, 106) degrees_N>,
'aux1': <CF AuxiliaryCoordinate: longitude(110, 106) degrees_E>},},},
'axis_to_coord': {'dim0': <CF DimensionCoordinate: time(3) gregorian>,
'dim1': <CF DimensionCoordinate: air_pressure(5) hPa>,
'dim2': <CF DimensionCoordinate: grid_latitude(110) degrees>,
'dim3': <CF DimensionCoordinate: grid_longitude(106) degrees>},
'axis_to_id': {'dim0': 'time',
'dim1': 'air_pressure',
'dim2': 'grid_latitude',
'dim3': 'grid_longitude'},
'cell_measures': {'N-d': {},
'dim0': {'1-d': {},
'N-d': {},},
'dim1': {'1-d': {},
'N-d': {},},
'dim2': {'1-d': {},
'N-d': {},},
'dim3': {'1-d': {},
'N-d': {},},
},
'id_to_aux': {},
'id_to_axis': {'air_pressure': 'dim1',
'grid_latitude': 'dim2',
'grid_longitude': 'dim3',
'time': 'dim0'},
'id_to_coord': {'air_pressure': <CF DimensionCoordinate: air_pressure(5) hPa>,
'grid_latitude': <CF DimensionCoordinate: grid_latitude(110) degrees>,
'grid_longitude': <CF DimensionCoordinate: grid_longitude(106) degrees>,
'time': <CF DimensionCoordinate: time(3) gregorian>},
'id_to_key': {'air_pressure': 'dim1',
'grid_latitude': 'dim2',
'grid_longitude': 'dim3',
'time': 'dim0'},
'undefined_axes': [],
'warnings': [],
}
"""
# ------------------------------------------------------------
# Map each axis identity to its identifier, if such a mapping
# exists.
#
# For example:
# >>> id_to_axis
# {'time': 'dim0', 'height': dim1'}
# ------------------------------------------------------------
id_to_axis = {}
# ------------------------------------------------------------
# For each dimension that is identified by a 1-d auxiliary
# coordinate, map its dimension's its identifier.
#
# For example:
# >>> id_to_aux
# {'region': 'aux0'}
# ------------------------------------------------------------
id_to_aux = {}
# ------------------------------------------------------------
# The keys of the coordinate items which provide axis
# identities
#
# For example:
# >>> id_to_key
# {'region': 'aux0'}
# ------------------------------------------------------------
# id_to_key = {}
axis_to_id = {}
# ------------------------------------------------------------
# Map each dimension's identity to the coordinate which
# provides that identity.
#
# For example:
# >>> id_to_coord
# {'time': <CF Coordinate: time(12)>}
# ------------------------------------------------------------
id_to_coord = {}
axis_to_coord = {}
# ------------------------------------------------------------
# List the dimensions which are undefined, in that no unique
# identity can be assigned to them.
#
# For example:
# >>> undefined_axes
# ['dim2']
# ------------------------------------------------------------
undefined_axes = []
# ------------------------------------------------------------
#
# ------------------------------------------------------------
warnings = []
id_to_dim = {}
axis_to_aux = {}
axis_to_dim = {}
if relaxed_identities is None:
relaxed_identities = cf_relaxed_identities()
# dimension_coordinates = self.dimension_coordinates(view=True)
# auxiliary_coordinates = self.auxiliary_coordinates(view=True)
for axis in self.domain_axes(todict=True):
# dims = self.constructs.chain(
# "filter_by_type",
# ("dimension_coordinate",), "filter_by_axis", (axis,)
# mode="and", todict=True
# )
key, dim = self.dimension_coordinate(
item=True, default=(None, None), filter_by_axis=(axis,)
)
if dim is not None:
# This axis of the domain has a dimension coordinate
identity = dim.identity(strict=True, default=None)
if identity is None:
# Dimension coordinate has no identity, but it may
# have a recognised axis.
for ctype in ("T", "X", "Y", "Z"):
if getattr(dim, ctype, False):
identity = ctype
break
if identity is None and relaxed_identities:
identity = dim.identity(relaxed=True, default=None)
if identity:
if identity in id_to_axis:
warnings.append("Field has multiple {identity!r} axes")
axis_to_id[axis] = identity
id_to_axis[identity] = axis
axis_to_coord[axis] = key
id_to_coord[identity] = key
axis_to_dim[axis] = key
id_to_dim[identity] = key
continue
else:
key, aux = self.auxiliary_coordinate(
filter_by_axis=(axis,),
axis_mode="and", # TODO check this "and"
item=True,
default=(None, None),
)
if aux is not None:
# This axis of the domain does not have a
# dimension coordinate but it does have exactly
# one 1-d auxiliary coordinate, so that will do.
identity = aux.identity(strict=True, default=None)
if identity is None and relaxed_identities:
identity = aux.identity(relaxed=True, default=None)
if identity and aux.has_data():
if identity in id_to_axis:
warnings.append(
f"Field has multiple {identity!r} axes"
)
axis_to_id[axis] = identity
id_to_axis[identity] = axis
axis_to_coord[axis] = key
id_to_coord[identity] = key
axis_to_aux[axis] = key
id_to_aux[identity] = key
continue
# Still here? Then this axis is undefined
undefined_axes.append(axis)
return {
"axis_to_id": axis_to_id,
"id_to_axis": id_to_axis,
"axis_to_coord": axis_to_coord,
"axis_to_dim": axis_to_dim,
"axis_to_aux": axis_to_aux,
"id_to_coord": id_to_coord,
"id_to_dim": id_to_dim,
"id_to_aux": id_to_aux,
"undefined_axes": undefined_axes,
"warnings": warnings,
}
def _is_broadcastable(self, shape):
"""Checks the field's data array is broadcastable to a shape.
:Parameters:
shape: sequence of `int`
:Returns:
`bool`
"""
shape0 = getattr(self, "shape", None)
if shape is None:
return False
shape1 = shape
if tuple(shape1) == tuple(shape0):
# Same shape
return True
ndim0 = len(shape0)
ndim1 = len(shape1)
if not ndim0 or not ndim1:
# Either or both is scalar
return True
for setN in set(shape0), set(shape1):
if setN == {1}:
return True
if ndim1 > ndim0:
return False
for n, m in zip(shape1[::-1], shape0[::-1]):
if n != m and n != 1:
return False
return True
def _axis_positions(self, axes, parse=True, return_axes=False):
"""Convert the given axes to their positions in the data.
Any domain axes that are not spanned by the data are ignored.
If there is no data then an empty list is returned.
.. versionadded:: 3.9.0
:Parameters:
axes: (sequence of) `str` or `int`
The axes to be converted. TODO domain axis selection
parse: `bool`, optional
If False then do not parse the *axes*. Parsing should
always occur unless the given *axes* are the output of
a previous call to `parse_axes`. By default *axes* is
parsed by `_parse_axes`.
return_axes: `bool`, optional
If True then also return the domain axis identifiers
corresponding to the positions.
:Returns:
`list` [, `list`]
The domain axis identifiers. If *return_axes* is True
then also return the corresponding domain axis
identifiers.
"""
data_axes = self.get_data_axes(default=None)
if data_axes is None:
return []
if parse:
axes = self._parse_axes(axes)
axes = [a for a in axes if a in data_axes]
positions = [data_axes.index(a) for a in axes]
if return_axes:
return positions, axes
return positions
def _binary_operation(self, other, method):
"""Implement binary arithmetic and comparison operations on the
master data array with metadata-aware broadcasting.
It is intended to be called by the binary arithmetic and
comparison methods, such as `__sub__`, `__imul__`, `__rdiv__`,
`__lt__`, etc.
:Parameters:
other: `Field` or `Query` or any object that broadcasts to the field construct's data
method: `str`
The binary arithmetic or comparison method name (such as
``'__idiv__'`` or ``'__ge__'``).
:Returns:
`Field`
The new field, or the same field if the operation was an
in place augmented arithmetic assignment.
**Examples**
>>> h = f._binary_operation(g, '__add__')
>>> h = f._binary_operation(g, '__ge__')
>>> f._binary_operation(g, '__isub__')
>>> f._binary_operation(g, '__rdiv__')
"""
debug = is_log_level_debug(logger)
if isinstance(other, Query):
# --------------------------------------------------------
# Combine the field with a Query object
# --------------------------------------------------------
return NotImplemented
if not isinstance(other, self.__class__):
# --------------------------------------------------------
# Combine the field with anything other than a Query
# object or another field construct
# --------------------------------------------------------
if cf_size(other) == 1:
# ----------------------------------------------------
# No changes to the field metadata constructs are
# required so can use the metadata-unaware parent
# method
# ----------------------------------------------------
if other is None:
other = np.array(None, dtype=object)
other = Data(other)
if other.ndim > 0:
other.squeeze(inplace=True)
return super()._binary_operation(other, method)
if self._is_broadcastable(np.shape(other)):
return super()._binary_operation(other, method)
raise ValueError(
f"Can't combine {self.__class__.__name__!r} with "
f"{other.__class__.__name__!r} due to incompatible data "
f"shapes: {self.shape}, {np.shape(other)})"
)
# ============================================================
# Still here? Then combine the field with another field
# ============================================================
relaxed_identities = cf_relaxed_identities()
units = self.Units
sn = self.get_property("standard_name", None)
ln = self.get_property("long_name", None)
other_sn = other.get_property("standard_name", None)
other_ln = other.get_property("long_name", None)
field1 = other.copy()
inplace = method[2] == "i"
if not inplace:
field0 = self.copy()
else:
field0 = self
# Analyse the two fields' data array dimensions
out0 = {}
out1 = {}
for i, (f, out) in enumerate(zip((field0, field1), (out0, out1))):
data_axes = f.get_data_axes()
for axis in f.domain_axes(todict=True):
identity = None
if f.is_discrete_axis(axis):
# This is a discrete axis whose identity is
# inferred from all of its auxiliary coordinates
x = {}
for key, aux_coord in f.auxiliary_coordinates(
filter_by_axis=(axis,),
axis_mode="and",
todict=True,
).items():
identity = aux_coord.identity(
strict=True, default=None
)
if identity is None and relaxed_identities:
identity = aux_coord.identity(
relaxed=True, default=None
)