forked from NCAS-CMS/cf-python
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpropertiesdatabounds.py
More file actions
3876 lines (2942 loc) · 114 KB
/
propertiesdatabounds.py
File metadata and controls
3876 lines (2942 loc) · 114 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
import numpy as np
from cfdm import is_log_level_info
from ..data import Data
from ..decorators import (
_deprecated_kwarg_check,
_inplace_enabled,
_inplace_enabled_define_and_cleanup,
_manage_log_level_via_verbosity,
)
from ..functions import (
_DEPRECATION_ERROR_ATTRIBUTE,
_DEPRECATION_ERROR_KWARGS,
_DEPRECATION_ERROR_METHOD,
bounds_combination_mode,
)
from ..functions import equivalent as cf_equivalent
from ..functions import inspect as cf_inspect
from ..functions import (
parse_indices,
)
from ..functions import size as cf_size
from ..query import Query
from ..units import Units
from . import PropertiesData
_units_None = Units()
_month_units = ("month", "months")
_year_units = ("year", "years", "yr")
logger = logging.getLogger(__name__)
class PropertiesDataBounds(PropertiesData):
"""Mixin class for a data array with descriptive properties and cell
bounds."""
def __getitem__(self, indices):
"""Return a subspace of the field construct defined by indices.
x.__getitem__(indices) <==> x[indices]
"""
if indices is Ellipsis:
return self.copy()
# Parse the index
if not isinstance(indices, tuple):
indices = (indices,)
arg0 = indices[0]
if isinstance(arg0, str) and arg0 == "mask":
auxiliary_mask = indices[:2]
indices2 = indices[2:]
else:
auxiliary_mask = None
indices2 = indices
indices, roll = parse_indices(self.shape, indices2, cyclic=True)
if roll:
new = self
data = self.data
axes = data._axes
cyclic_axes = data._cyclic
for iaxis, shift in roll.items():
if axes[iaxis] not in cyclic_axes:
raise IndexError(
"Can't do a cyclic slice on a non-cyclic axis"
)
new = new.roll(iaxis, shift)
else:
new = self.copy() # data=False)
# data = self.data
if auxiliary_mask:
findices = tuple(auxiliary_mask) + tuple(indices)
else:
findices = tuple(indices)
data = self.get_data(None, _fill_value=False)
if data is not None:
new_data = data[findices]
new.set_data(new_data, copy=False)
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"
)
# Subspace the interior ring array, if there is one.
interior_ring = self.get_interior_ring(None)
if interior_ring is not None:
new.set_interior_ring(interior_ring[tuple(indices)], copy=False)
# Subspace the bounds, if there are any
bounds = self.get_bounds(None)
if bounds is not None:
bounds_data = bounds.get_data(None, _fill_value=False)
if bounds_data is not None:
findices = list(findices)
# if data.ndim <= 1 and not self.has_geometry():
if bounds.ndim <= 2:
index = indices[0]
if isinstance(index, slice):
if index.step and index.step < 0:
# This scalar or 1-d variable has been
# reversed so reverse its bounds (as per
# 7.1 of the conventions)
findices.append(slice(None, None, -1))
elif data.size > 1 and index[-1] < index[0]:
# This 1-d variable has been reversed so
# reverse its bounds (as per 7.1 of the
# conventions)
findices.append(slice(None, None, -1))
if auxiliary_mask:
findices[1] = [
mask.insert_dimension(-1) for mask in findices[1]
]
new.bounds.set_data(bounds_data[tuple(findices)], copy=False)
# Remove the direction, as it may now be wrong
new._custom.pop("direction", None)
# Return the new bounded variable
return new
def __setitem__(self, indices, value):
"""Called to implement assignment to x[indices]
x.__setitem__(indices, y) <==> x[indices] = y
**Bounds**
When assigning an object that has bounds to an object that also
has bounds, then the bounds are also assigned, if possible. This
is the only circumstance that allows bounds to be updated during
assignment by index.
Interior ring assignment can only occur if both ``x`` and ``y``
have interior ring arrays. An exception will be raised only one of
``x`` and ``y`` has an interior ring array.
"""
super().__setitem__(indices, value)
# Set the interior ring, if present (added at v3.8.0).
interior_ring = self.get_interior_ring(None)
try:
value_interior_ring = value.get_interior_ring(None)
except AttributeError:
value_interior_ring = None
if interior_ring is not None and value_interior_ring is not None:
indices = parse_indices(self.shape, indices)
indices.append(slice(None))
interior_ring[tuple(indices)] = value_interior_ring
elif interior_ring is not None:
raise ValueError(
f"Can't assign {value!r} without an interior ring array to "
f"{self!r} with an interior ring array"
)
elif value_interior_ring is not None:
raise ValueError(
f"Can't assign {value!r} with an interior ring array to "
f"{self!r} without an interior ring array"
)
# Set the bounds, if present (added at v3.8.0).
bounds = self.get_bounds(None)
if bounds is not None:
try:
value_bounds = value.get_bounds(None)
except AttributeError:
value_bounds = None
if value_bounds is not None:
indices = parse_indices(self.shape, indices)
indices.append(Ellipsis)
bounds[tuple(indices)] = value_bounds
def __eq__(self, y):
"""The rich comparison operator ``==``
x.__eq__(y) <==> x==y
"""
return self._binary_operation(y, "__eq__", False)
def __ne__(self, y):
"""The rich comparison operator ``!=``
x.__ne__(y) <==> x!=y
"""
return self._binary_operation(y, "__ne__", False)
def __ge__(self, y):
"""The rich comparison operator ``>=``
x.__ge__(y) <==> x>=y
"""
return self._binary_operation(y, "__ge__", False)
def __gt__(self, y):
"""The rich comparison operator ``>``
x.__gt__(y) <==> x>y
"""
return self._binary_operation(y, "__gt__", False)
def __le__(self, y):
"""The rich comparison operator ``<=``
x.__le__(y) <==> x<=y
"""
return self._binary_operation(y, "__le__", False)
def __lt__(self, y):
"""The rich comparison operator ``<``
x.__lt__(y) <==> x<y
"""
return self._binary_operation(y, "__lt__", False)
def __and__(self, other):
"""The binary bitwise operation ``&``
x.__and__(y) <==> x&y
"""
return self._binary_operation(other, "__and__", False)
def __iand__(self, other):
"""The augmented bitwise assignment ``&=``
x.__iand__(y) <==> x&=y
"""
return self._binary_operation(other, "__iand__", False)
def __rand__(self, other):
"""The binary bitwise operation ``&`` with reflected operands.
x.__rand__(y) <==> y&x
"""
return self._binary_operation(other, "__rand__", False)
def __or__(self, other):
"""The binary bitwise operation ``|``
x.__or__(y) <==> x|y
"""
return self._binary_operation(other, "__or__", False)
def __ior__(self, other):
"""The augmented bitwise assignment ``|=``
x.__ior__(y) <==> x|=y
"""
return self._binary_operation(other, "__ior__", False)
def __ror__(self, other):
"""The binary bitwise operation ``|`` with reflected operands.
x.__ror__(y) <==> y|x
"""
return self._binary_operation(other, "__ror__", False)
def __xor__(self, other):
"""The binary bitwise operation ``^``
x.__xor__(y) <==> x^y
"""
return self._binary_operation(other, "__xor__", False)
def __ixor__(self, other):
"""The augmented bitwise assignment ``^=``
x.__ixor__(y) <==> x^=y
"""
return self._binary_operation(other, "__ixor__", False)
def __rxor__(self, other):
"""The binary bitwise operation ``^`` with reflected operands.
x.__rxor__(y) <==> y^x
"""
return self._binary_operation(other, "__rxor__", False)
def __lshift__(self, y):
"""The binary bitwise operation ``<<``
x.__lshift__(y) <==> x<<y
"""
return self._binary_operation(y, "__lshift__", False)
def __ilshift__(self, y):
"""The augmented bitwise assignment ``<<=``
x.__ilshift__(y) <==> x<<=y
"""
return self._binary_operation(y, "__ilshift__", False)
def __rlshift__(self, y):
"""The binary bitwise operation ``<<`` with reflected operands.
x.__rlshift__(y) <==> y<<x
"""
return self._binary_operation(y, "__rlshift__", False)
def __rshift__(self, y):
"""The binary bitwise operation ``>>``
x.__lshift__(y) <==> x>>y
"""
return self._binary_operation(y, "__rshift__", False)
def __irshift__(self, y):
"""The augmented bitwise assignment ``>>=``
x.__irshift__(y) <==> x>>=y
"""
return self._binary_operation(y, "__irshift__", False)
def __rrshift__(self, y):
"""The binary bitwise operation ``>>`` with reflected operands.
x.__rrshift__(y) <==> y>>x
"""
return self._binary_operation(y, "__rrshift__", False)
def __abs__(self):
"""The unary arithmetic operation ``abs``
x.__abs__() <==> abs(x)
"""
return self._unary_operation("__abs__", bounds=True)
def __neg__(self):
"""The unary arithmetic operation ``-``
x.__neg__() <==> -x
"""
return self._unary_operation("__neg__", bounds=True)
def __invert__(self):
"""The unary bitwise operation ``~``
x.__invert__() <==> ~x
"""
return self._unary_operation("__invert__", bounds=True)
def __pos__(self):
"""The unary arithmetic operation ``+``
x.__pos__() <==> +x
"""
return self._unary_operation("__pos__", bounds=True)
def _binary_operation(self, other, method, bounds=True):
"""Implement binary arithmetic and comparison operations.
The operations act on the construct's data array with the numpy
broadcasting rules.
If the construct has bounds then they are operated on with the
same data as the construct's data.
It is intended to be called by the binary arithmetic and comparison
methods, such as `!__sub__` and `!__lt__`.
**Bounds**
The flag returned by ``cf.bounds_combination_mode()`` is used to
influence whether or not the result of a binary operation "op(x,
y)", such as ``x + y``, ``x -= y``, ``x << y``, etc., will contain
bounds, and if so how those bounds are calculated.
The behaviour for the different flag values is described in the
docstring of `cf.bounds_combination_mode`.
:Parameters:
other:
method: `str`
The binary arithmetic or comparison method name (such as
``'__imul__'`` or ``'__ge__'``).
bounds: `bool`, optional
If False then ignore the bounds and remove them from the
result. By default the bounds are operated on as described
above.
:Returns:
`{{class}}`
A new construct, or the same construct if the operation
was in-place.
"""
if getattr(other, "_NotImplemented_RHS_Data_op", False):
return NotImplemented
inplace = method[2] == "i"
bounds_AND = bounds and bounds_combination_mode() == "AND"
bounds_OR = (
bounds and not bounds_AND and bounds_combination_mode() == "OR"
)
bounds_XOR = (
bounds
and not bounds_AND
and not bounds_OR
and bounds_combination_mode() == "XOR"
)
bounds_NONE = (
not bounds
or not (bounds_AND or bounds_OR or bounds_XOR)
or bounds_combination_mode() == "NONE"
)
if not bounds_NONE:
geometry = self.get_geometry(None)
try:
other_geometry = other.get_geometry(None)
except AttributeError:
other_geometry = None
if geometry != other_geometry:
raise ValueError(
"Can't combine operands with different geometry types"
)
interior_ring = self.get_interior_ring(None)
try:
other_interior_ring = other.get_interior_ring(None)
except AttributeError:
other_interior_ring = None
if interior_ring is not None or other_interior_ring is not None:
raise ValueError(
"Can't combine operands with interior ring arrays"
)
has_bounds = self.has_bounds()
if bounds and has_bounds and inplace and other is self:
other = other.copy()
try:
other_bounds = other.get_bounds(None)
except AttributeError:
other_bounds = None
if (
(bounds_OR or bounds_XOR)
and not has_bounds
and other_bounds is not None
):
# --------------------------------------------------------
# If self has no bounds but other does, then copy self for
# use in constructing new bounds.
# --------------------------------------------------------
original_self = self.copy()
new = super()._binary_operation(other, method)
if bounds_NONE:
# --------------------------------------------------------
# Remove any bounds from the result
# --------------------------------------------------------
new.del_bounds(None)
elif has_bounds and other_bounds is not None:
if bounds_AND or bounds_OR:
# ----------------------------------------------------
# Both self and other have bounds, so combine them for
# the result.
# ----------------------------------------------------
new_bounds = self.bounds._binary_operation(
other_bounds, method
)
if not inplace:
new.set_bounds(new_bounds, copy=False)
elif bounds_XOR:
# ----------------------------------------------------
# Both self and other have bounds, so remove the
# bounds from the result
# ----------------------------------------------------
new.del_bounds(None)
elif bounds_AND:
# --------------------------------------------------------
# At most one of self and other has bounds, so remove the
# bounds from the result.
# --------------------------------------------------------
new.del_bounds(None)
elif has_bounds:
# --------------------------------------------------------
# Only self has bounds, so combine the self bounds with
# the other values.
# --------------------------------------------------------
if cf_size(other) > 1:
for i in range(self.bounds.ndim - self.ndim):
try:
other = other.insert_dimension(-1)
except AttributeError:
other = np.expand_dims(other, -1)
new_bounds = self.bounds._binary_operation(other, method)
if not inplace:
new.set_bounds(new_bounds, copy=False)
elif other_bounds is not None:
# --------------------------------------------------------
# Only other has bounds, so combine self values with the
# other bounds
# --------------------------------------------------------
new_bounds = self._Bounds(data=original_self.data, copy=True)
for i in range(other_bounds.ndim - other.ndim):
new_bounds = new_bounds.insert_dimension(-1)
if inplace:
# Can't do the operation in-place because we'll run
# foul of the broadcasting rules (e.g. "ValueError:
# non-broadcastable output operand with shape (12,1)
# doesn't match the broadcast shape (12,2)")
method2 = method.replace("__i", "__", 1)
else:
method2 = method
new_bounds = new_bounds._binary_operation(other_bounds, method2)
new.set_bounds(new_bounds, copy=False)
new._custom["direction"] = None
return new
@_manage_log_level_via_verbosity
def _equivalent_data(self, other, rtol=None, atol=None, verbose=None):
"""True if data is equivalent to other data, units considered.
Two real numbers ``x`` and ``y`` are considered equal if
``|x-y|<=atol+rtol|y|``, where ``atol`` (the tolerance on absolute
differences) and ``rtol`` (the tolerance on relative differences)
are positive, typically very small numbers. See the *atol* and
*rtol* parameters.
:Parameters:
atol: `float`, optional
The tolerance on absolute differences between real
numbers. The default value is set by the `atol` function.
rtol: `float`, optional
The tolerance on relative differences between real
numbers. The default value is set by the `rtol` function.
:Returns:
`bool`
"""
self_bounds = self.get_bounds(None)
other_bounds = other.get_bounds(None)
hasbounds = self_bounds is not None
if hasbounds != (other_bounds is not None):
# TODO: add traceback
# TODO: improve message below
if is_log_level_info(logger):
logger.info(
"One has bounds, the other does not"
) # pragma: no cover
return False
try:
direction0 = self.direction()
direction1 = other.direction()
if (
direction0 != direction1
and direction0 is not None
and direction1 is not None
):
other = other.flip()
except AttributeError:
pass
# Compare the data arrays
if not super()._equivalent_data(
other, rtol=rtol, atol=atol, verbose=verbose
):
if is_log_level_info(logger):
# TODO: improve message below
logger.info("Non-equivalent data arrays") # pragma: no cover
return False
if hasbounds:
# Compare the bounds
if not self_bounds._equivalent_data(
other_bounds, rtol=rtol, atol=atol, verbose=verbose
):
if is_log_level_info(logger):
logger.info(
f"{self.__class__.__name__}: Non-equivalent bounds "
f"data: {self_bounds.data!r}, {other_bounds.data!r}"
) # pragma: no cover
return False
# Still here? Then the data are equivalent.
return True
def _YMDhms(self, attr):
"""Return some datetime component of the data array elements."""
out = super()._YMDhms(attr)
out.del_bounds(None)
return out
def _matching_values(self, value0, value1, units=False, basic=False):
"""Whether two values match.
The definition of "match" depends on the types of *value0* and
*value1*.
:Parameters:
value0:
The first value to be matched.
value1:
The second value to be matched.
units: `bool`, optional
If True then the units must be the same for values to be
considered to match. By default, units are ignored in the
comparison.
:Returns:
`bool`
Whether or not the two values match.
"""
if value1 is None:
return False
if units and isinstance(value0, str):
return Units(value0).equals(Units(value1))
if isinstance(value0, Query):
return bool(value0.evaluate(value1)) # TODO vectors
else:
try:
return value0.search(value1)
except (AttributeError, TypeError):
return self._equals(value1, value0, basic=basic)
return False
def _apply_superclass_data_oper(
self,
v,
oper_name,
oper_args=(),
bounds=True,
interior_ring=False,
**oper_kwargs,
):
"""Define an operation that can be applied to the data array.
.. versionadded:: 3.1.0
:Parameters:
v: the data array to apply the operations to (possibly in-place)
oper_name: the string name for the desired operation, as it is
defined (its method name) under the PropertiesData class, e.g.
`sin` to apply PropertiesData.sin`.
Note: there is no (easy) way to determine the name of a
function/method within itself, without e.g. inspecting the stack
(see rejected PEP 3130), so even though functions are named
identically to those called (e.g. both `sin`) the same
name must be typed and passed into this method in each case.
TODO: is there a way to prevent/bypass the above?
oper_args, oper_kwargs: all of the arguments for `oper_name`.
bounds: `bool`
Whether or not there are cell bounds (to consider).
interior_ring: `bool`
Whether or not a geometry interior ring variable needs to
be operated on.
"""
v = getattr(super(), oper_name)(*oper_args, **oper_kwargs)
if v is None: # from inplace operation in superclass method
v = self
# Now okay to mutate oper_kwargs as no longer needed in original form
oper_kwargs.pop("inplace", None)
if bounds:
bounds = v.get_bounds(None)
if bounds is not None:
getattr(bounds, oper_name)(
*oper_args, inplace=True, **oper_kwargs
)
if interior_ring:
interior_ring = v.get_interior_ring(None)
if interior_ring is not None:
getattr(interior_ring, oper_name)(
*oper_args, inplace=True, **oper_kwargs
)
return v
def _unary_operation(self, method, bounds=True):
"""Implement unary arithmetic operations on the data array and
bounds.
:Parameters:
method: `str`
The unary arithmetic method name (such as "__abs__").
bounds: `bool`, optional
If False then ignore the bounds and remove them from the
result. By default the bounds are operated on as well.
:Returns:
`{{class}}`
A new construct, or the same construct if the operation
was in-place.
"""
new = super()._unary_operation(method)
self_bounds = self.get_bounds(None)
if self_bounds is not None:
if bounds:
new_bounds = self_bounds._unary_operation(method)
new.set_bounds(new_bounds)
else:
new.del_bounds()
return new
# ----------------------------------------------------------------
# Attributes
# ----------------------------------------------------------------
@property
def cellsize(self):
"""The cell sizes.
If there are no cell bounds then the cell sizes are all zero.
.. versionadded:: 2.0
**Examples**
>>> print(c.bounds.array)
[[-90. -87.]
[-87. -80.]
[-80. -67.]]
>>> c.cellsize
<CF Data(3,): [3.0, 7.0, 13.0] degrees_north>
>>> print(d.cellsize.array)
[ 3. 7. 13.]
>>> b = c.del_bounds()
>>> c.cellsize
<CF Data(3,): [0, 0, 0] degrees_north>
"""
data = self.get_bounds_data(None, _fill_value=None)
if data is not None:
if data.shape[-1] != 2:
raise ValueError(
"Can only calculate cell sizes from bounds when there are "
f"exactly two bounds per cell. Got {data.shape[-1]}"
)
out = abs(data[..., 1] - data[..., 0])
out.squeeze(-1, inplace=True)
return out
else:
data = self.get_data(None)
if data is not None:
# Convert to "difference" units
#
# TODO: Think about temperature units in relation to
# https://github.com/cf-convention/discuss/issues/101,
# whenever that issue is resolved.
units = self.Units
if units.isreftime:
units = Units(units._units_since_reftime)
return Data.zeros(self.shape, units=units)
raise AttributeError(
"Can't get cell sizes when there are no bounds nor coordinate data"
)
@property
def dtype(self):
"""Numpy data-type of the data array.
.. versionadded:: 2.0
**Examples**
>>> c.dtype
dtype('float64')
>>> import numpy
>>> c.dtype = numpy.dtype('float32')
"""
data = self.get_data(None, _fill_value=False)
if data is not None:
return data.dtype
bounds = self.get_bounds_data(None, _fill_value=None)
if bounds is not None:
return bounds.dtype
raise AttributeError(
f"{self.__class__.__name__} doesn't have attribute 'dtype'"
)
@dtype.setter
def dtype(self, value):
data = self.get_data(None, _fill_value=False)
if data is not None:
data.dtype = value
bounds = self.get_bounds_data(None, _fill_value=None)
if bounds is not None:
bounds.dtype = value
@property
def isperiodic(self):
"""True if a given axis is periodic.
.. versionadded:: 2.0
>>> print(c.period())
None
>>> c.isperiodic
False
>>> print(c.period(cf.Data(360, 'degeres_east')))
None
>>> c.isperiodic
True
>>> c.period(None)
<CF Data(): 360 degrees_east>
>>> c.isperiodic
False
"""
period = self.period()
if period is not None:
return True
bounds = self.get_bounds(None)
if bounds is not None:
return bounds.period is not None
# return self._custom.get('period', None) is not None
@property
def lower_bounds(self):
"""The lower bounds of cells.
If there are no cell bounds then the coordinates are used as the
lower bounds.
.. versionadded:: 2.0
.. seealso:: `upper_bounds`
**Examples**
>>> print(c.array)
[4 2 0]
>>> print(c.bounds.array)
[[ 5 3]
[ 3 1]
[ 1 -1]]
>>> c.lower_bounds
<CF Data(3): [3, 1, -1]>
>>> b = c.del_bounds()
>>> c.lower_bounds
<CF Data(3): [4, 2, 0]>
"""
data = self.get_bounds_data(None)
if data is not None:
out = data.minimum(-1)
out.squeeze(-1, inplace=True)
return out
else:
data = self.get_data(None)
if data is not None:
return data.copy()
raise AttributeError(
"Can't get lower bounds when there are no bounds nor coordinate "
"data"
)
@property
def Units(self):
"""The `cf.Units` object containing the units of the data array.
Stores the units and calendar CF properties in an internally
consistent manner. These are mirrored by the `units` and
`calendar` CF properties respectively.
**Examples**
>>> f.Units
<Units: K>
>>> f.Units
<Units: days since 2014-1-1 calendar=noleap>
"""
# return super().Units
data = self.get_data(None, _fill_value=False)
if data is not None:
# Return the units of the data
return data.Units
# print('TODO RECURISION HERE')
# bounds = self.get_bounds(None)
# if bounds is not None:
# data = bounds.get_data(None)
# if data is not None:
# # Return the units of the bounds data
# return data.Units
try:
return self._custom["Units"]
except KeyError:
# if bounds is None:
self._custom["Units"] = _units_None
return _units_None
# else:
# try:
# return bounds._custom['Units']
# except KeyError:
# bounds._custom['Units'] = _units_None
# return _units_None