-
Notifications
You must be signed in to change notification settings - Fork 279
/
maths.py
1230 lines (998 loc) · 36.4 KB
/
maths.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.
"""Basic mathematical and statistical operations."""
from functools import lru_cache
import inspect
import math
import operator
import cf_units
import dask.array as da
import numpy as np
from numpy import ma
from iris._deprecation import warn_deprecated
import iris.analysis
from iris.common import SERVICES, Resolve
from iris.common.lenient import _lenient_client
from iris.config import get_logger
import iris.coords
import iris.exceptions
from iris.exceptions import warn_once_at_level
import iris.util
# Configure the logger.
logger = get_logger(__name__)
@lru_cache(maxsize=128, typed=True)
def _output_dtype(op, first_dtype, second_dtype=None, in_place=False):
"""Get the numpy dtype.
Get the numpy dtype corresponding to the result of applying a unary or
binary operation to arguments of specified dtype.
Parameters
----------
op :
A unary or binary operator which can be applied to array-like objects.
first_dtype :
The dtype of the first or only argument to the operator.
second_dtype : optional
The dtype of the second argument to the operator.
in_place : bool, default=False
Whether the operation is to be performed in place.
Returns
-------
:class:`numpy.dtype`
Notes
-----
.. note::
The function always returns the dtype which would result if the
operation were successful, even if the operation could fail due to
casting restrictions for in place operations.
"""
if in_place:
# Always return the first dtype, even if the operation would fail due
# to failure to cast the result.
result = first_dtype
else:
operand_dtypes = (
(first_dtype, second_dtype) if second_dtype is not None else (first_dtype,)
)
arrays = [np.array([1], dtype=dtype) for dtype in operand_dtypes]
result = op(*arrays).dtype
return result
def _get_dtype(operand):
"""Get the numpy dtype corresponding to the numeric data in the object provided.
Parameters
----------
operand :
An instance of :class:`iris.cube.Cube` or :class:`iris.coords.Coord`,
or a number or :class:`numpy.ndarray`.
Returns
-------
:class:`numpy.dtype`
"""
return np.min_scalar_type(operand) if np.isscalar(operand) else operand.dtype
def abs(cube, in_place=False):
"""Calculate the absolute values of the data in the Cube provided.
Parameters
----------
cube :
An instance of :class:`iris.cube.Cube`.
in_place : bool, default=False
Whether to create a new Cube, or alter the given "cube".
Returns
-------
:class:`iris.cube.Cube`.
Notes
-----
This function maintains laziness when called; it does not realise data.
See more at :doc:`/userguide/real_and_lazy_data`.
"""
_assert_is_cube(cube)
new_dtype = _output_dtype(np.abs, cube.dtype, in_place=in_place)
op = da.absolute if cube.has_lazy_data() else np.abs
return _math_op_common(cube, op, cube.units, new_dtype=new_dtype, in_place=in_place)
def intersection_of_cubes(cube, other_cube):
"""Return the two Cubes of intersection given two Cubes.
.. note:: The intersection of cubes function will ignore all single valued
coordinates in checking the intersection.
Parameters
----------
cube :
An instance of :class:`iris.cube.Cube`.
other_cube :
An instance of :class:`iris.cube.Cube`.
Returns
-------
A paired tuple of :class:`iris.cube.Cube`
A pair of :class:`iris.cube.Cube` instances in a tuple corresponding to
the original cubes restricted to their intersection.
Notes
-----
.. deprecated:: 3.2.0
Instead use :meth:`iris.cube.CubeList.extract_overlapping`. For example,
rather than calling
.. code::
cube1, cube2 = intersection_of_cubes(cube1, cube2)
replace with
.. code::
cubes = CubeList([cube1, cube2])
coords = ["latitude", "longitude"] # Replace with relevant coords
intersections = cubes.extract_overlapping(coords)
cube1, cube2 = (intersections[0], intersections[1])
This function maintains laziness when called; it does not realise data.
See more at :doc:`/userguide/real_and_lazy_data`.
"""
wmsg = (
"iris.analysis.maths.intersection_of_cubes has been deprecated and will "
"be removed, please use iris.cube.CubeList.extract_overlapping "
"instead. See intersection_of_cubes docstring for more information."
)
warn_deprecated(wmsg)
# Take references of the original cubes (which will be copied when
# slicing later).
new_cube_self = cube
new_cube_other = other_cube
# This routine has not been written to cope with multi-dimensional
# coordinates.
for coord in cube.coords() + other_cube.coords():
if coord.ndim != 1:
raise iris.exceptions.CoordinateMultiDimError(coord)
coord_comp = iris.analysis._dimensional_metadata_comparison(cube, other_cube)
if coord_comp["ungroupable_and_dimensioned"]:
raise ValueError(
"Cubes do not share all coordinates in common, cannot intersect."
)
# cubes must have matching coordinates
for coord in cube.coords():
other_coord = other_cube.coord(coord)
# Only intersect coordinates which are different, single values
# coordinates may differ.
if coord.shape[0] > 1 and coord != other_coord:
intersected_coord = coord.intersect(other_coord)
new_cube_self = new_cube_self.subset(intersected_coord)
new_cube_other = new_cube_other.subset(intersected_coord)
return new_cube_self, new_cube_other
def _assert_is_cube(cube):
from iris.cube import Cube
if not isinstance(cube, Cube):
raise TypeError('The "cube" argument must be an instance of ' "iris.cube.Cube.")
@_lenient_client(services=SERVICES)
def add(cube, other, dim=None, in_place=False):
"""Calculate the sum.
Calculate the sum of two cubes, or the sum of a cube and a coordinate or
array or scalar value.
When summing two cubes, they must both have the same coordinate systems and
data resolution.
When adding a coordinate to a cube, they must both share the same number of
elements along a shared axis.
Parameters
----------
cube : iris.cube.Cube
First operand to add.
other: iris.cube.Cube, iris.coords.Coord, number, numpy.ndarray or dask.array.Array
Second operand to add.
dim : int, optional
If `other` is a coord which does not exist on the cube, specify the
dimension to which it should be mapped.
in_place : bool, default=False
If `True`, alters the input cube. Otherwise a new cube is created.
Returns
-------
iris.cube.Cube
Notes
-----
This function maintains laziness when called; it does not realise data.
See more at :doc:`/userguide/real_and_lazy_data`.
"""
_assert_is_cube(cube)
new_dtype = _output_dtype(
operator.add,
cube.dtype,
second_dtype=_get_dtype(other),
in_place=in_place,
)
if in_place:
_inplace_common_checks(cube, other, "addition")
op = operator.iadd
else:
op = operator.add
return _add_subtract_common(
op, "add", cube, other, new_dtype, dim=dim, in_place=in_place
)
@_lenient_client(services=SERVICES)
def subtract(cube, other, dim=None, in_place=False):
"""Calculate the difference.
Calculate the difference between two cubes, or the difference between
a cube and a coordinate or array or scalar value.
When differencing two cubes, they must both have the same coordinate systems
and data resolution.
When subtracting a coordinate from a cube, they must both share the same
number of elements along a shared axis.
Parameters
----------
cube : iris.cube.Cube
Cube from which to subtract.
other: iris.cube.Cube, iris.coords.Coord, number, numpy.ndarray or dask.array.Array
Object to subtract from the cube.
dim : int, optional
If `other` is a coord which does not exist on the cube, specify the
dimension to which it should be mapped.
in_place : bool, default=False
If `True`, alters the input cube. Otherwise a new cube is created.
Returns
-------
iris.cube.Cube
Notes
-----
This function maintains laziness when called; it does not realise data.
See more at :doc:`/userguide/real_and_lazy_data`.
"""
_assert_is_cube(cube)
new_dtype = _output_dtype(
operator.sub,
cube.dtype,
second_dtype=_get_dtype(other),
in_place=in_place,
)
if in_place:
_inplace_common_checks(cube, other, "subtraction")
op = operator.isub
else:
op = operator.sub
return _add_subtract_common(
op, "subtract", cube, other, new_dtype, dim=dim, in_place=in_place
)
def _add_subtract_common(
operation_function,
operation_name,
cube,
other,
new_dtype,
dim=None,
in_place=False,
):
"""Share common code between addition and subtraction of cubes.
Parameters
----------
operation_function :
function which does the operation (e.g. numpy.subtract)
operation_name :
The public name of the operation (e.g. 'divide')
cube :
The cube whose data is used as the first argument to `operation_function`
other :
The cube, coord, ndarray, dask array or number whose
data is used as the second argument
new_dtype :
The expected dtype of the output. Used in the case of scalar
masked arrays
dim : optional
Dimension along which to apply `other` if it's a coordinate that is not
found in `cube`
in_place : bool, default=False
Whether or not to apply the operation in place to `cube` and `cube.data`
"""
_assert_is_cube(cube)
if cube.units != getattr(other, "units", cube.units):
emsg = (
f"Cannot use {operation_name!r} with differing units "
f"({cube.units} & {other.units})"
)
raise iris.exceptions.NotYetImplementedError(emsg)
result = _binary_op_common(
operation_function,
operation_name,
cube,
other,
cube.units,
new_dtype=new_dtype,
dim=dim,
in_place=in_place,
)
return result
@_lenient_client(services=SERVICES)
def multiply(cube, other, dim=None, in_place=False):
"""Calculate the product.
Calculate the product of two cubes, or the product of a cube and a coordinate
or array or scalar value.
When multiplying two cubes, they must both have the same coordinate systems
and data resolution.
When mulplying a cube by a coordinate, they must both share the same number
of elements along a shared axis.
Parameters
----------
cube : iris.cube.Cube
First operand to multiply.
other: iris.cube.Cube, iris.coords.Coord, number, numpy.ndarray or dask.array.Array
Second operand to multiply.
dim : int, optional
If `other` is a coord which does not exist on the cube, specify the
dimension to which it should be mapped.
in_place : bool, default=False
If `True`, alters the input cube. Otherwise a new cube is created.
Returns
-------
iris.cube.Cube
Notes
-----
This function maintains laziness when called; it does not realise data.
See more at :doc:`/userguide/real_and_lazy_data`.
"""
_assert_is_cube(cube)
new_dtype = _output_dtype(
operator.mul,
cube.dtype,
second_dtype=_get_dtype(other),
in_place=in_place,
)
other_unit = getattr(other, "units", "1")
new_unit = cube.units * other_unit
if in_place:
_inplace_common_checks(cube, other, "multiplication")
op = operator.imul
else:
op = operator.mul
result = _binary_op_common(
op,
"multiply",
cube,
other,
new_unit,
new_dtype=new_dtype,
dim=dim,
in_place=in_place,
)
return result
def _inplace_common_checks(cube, other, math_op):
"""Check if an inplace math operation can take place.
Check whether an inplace math operation can take place between `cube` and
`other`. It cannot if `cube` has integer data and `other` has float data
as the operation will always produce float data that cannot be 'safely'
cast back to the integer data of `cube`.
"""
other_dtype = _get_dtype(other)
if not np.can_cast(other_dtype, cube.dtype, "same_kind"):
aemsg = (
"Cannot perform inplace {} between {!r} "
"with {} data and {!r} with {} data."
)
raise ArithmeticError(
aemsg.format(math_op, cube, cube.dtype, other, other_dtype)
)
@_lenient_client(services=SERVICES)
def divide(cube, other, dim=None, in_place=False):
"""Calculate the ratio.
Calculate the ratio of two cubes, or the ratio of a cube and a coordinate
or array or scalar value.
When dividing a cube by another cube, they must both have the same coordinate
systems and data resolution.
When dividing a cube by a coordinate, they must both share the same number
of elements along a shared axis.
Parameters
----------
cube : iris.cube.Cube
Numerator.
other: iris.cube.Cube, iris.coords.Coord, number, numpy.ndarray or dask.array.Array
Denominator.
dim : int, optional
If `other` is a coord which does not exist on the cube, specify the
dimension to which it should be mapped.
in_place : bool, default=False
If `True`, alters the input cube. Otherwise a new cube is created.
Returns
-------
iris.cube.Cube
Notes
-----
This function maintains laziness when called; it does not realise data.
See more at :doc:`/userguide/real_and_lazy_data`.
"""
_assert_is_cube(cube)
new_dtype = _output_dtype(
operator.truediv,
cube.dtype,
second_dtype=_get_dtype(other),
in_place=in_place,
)
other_unit = getattr(other, "units", "1")
new_unit = cube.units / other_unit
if in_place:
if cube.dtype.kind in "iu":
# Cannot coerce float result from inplace division back to int.
emsg = (
f"Cannot perform inplace division of cube {cube.name()!r} "
"with integer data."
)
raise ArithmeticError(emsg)
op = operator.itruediv
else:
op = operator.truediv
result = _binary_op_common(
op,
"divide",
cube,
other,
new_unit,
new_dtype=new_dtype,
dim=dim,
in_place=in_place,
)
return result
def exponentiate(cube, exponent, in_place=False):
"""Return the result of the given cube to the power of a scalar.
Parameters
----------
cube :
An instance of :class:`iris.cube.Cube`.
exponent :
The integer or floating point exponent.
.. note:: When applied to the cube's unit, the exponent must
result in a unit that can be described using only integer
powers of the basic units.
e.g. Unit('meter^-2 kilogram second^-1')
in_place : bool, default=False
Whether to create a new Cube, or alter the given "cube".
Returns
-------
:class:`iris.cube.Cube`.
Notes
-----
This function maintains laziness when called; it does not realise data.
See more at :doc:`/userguide/real_and_lazy_data`.
"""
_assert_is_cube(cube)
new_dtype = _output_dtype(
operator.pow,
cube.dtype,
second_dtype=_get_dtype(exponent),
in_place=in_place,
)
if cube.has_lazy_data():
def power(data):
return operator.pow(data, exponent)
else:
def power(data, out=None):
return np.power(data, exponent, out)
return _math_op_common(
cube,
power,
cube.units**exponent,
new_dtype=new_dtype,
in_place=in_place,
)
def exp(cube, in_place=False):
"""Calculate the exponential (exp(x)) of the cube.
Parameters
----------
cube :
An instance of :class:`iris.cube.Cube`.
in_place : bool, default=False
Whether to create a new Cube, or alter the given "cube".
Returns
-------
:class:`iris.cube.Cube`.
Notes
-----
Taking an exponential will return a cube with dimensionless units.
This function maintains laziness when called; it does not realise data.
See more at :doc:`/userguide/real_and_lazy_data`.
"""
_assert_is_cube(cube)
new_dtype = _output_dtype(np.exp, cube.dtype, in_place=in_place)
op = da.exp if cube.has_lazy_data() else np.exp
return _math_op_common(
cube, op, cf_units.Unit("1"), new_dtype=new_dtype, in_place=in_place
)
def log(cube, in_place=False):
"""Calculate the natural logarithm (base-e logarithm) of the cube.
Parameters
----------
cube :
An instance of :class:`iris.cube.Cube`.
in_place : bool, default=False
Whether to create a new Cube, or alter the given "cube".
Returns
-------
:class:`iris.cube.Cube`
Notes
-----
This function maintains laziness when called; it does not realise data.
See more at :doc:`/userguide/real_and_lazy_data`.
"""
_assert_is_cube(cube)
new_dtype = _output_dtype(np.log, cube.dtype, in_place=in_place)
op = da.log if cube.has_lazy_data() else np.log
return _math_op_common(
cube,
op,
cube.units.log(math.e),
new_dtype=new_dtype,
in_place=in_place,
)
def log2(cube, in_place=False):
"""Calculate the base-2 logarithm of the cube.
Parameters
----------
cube :
An instance of :class:`iris.cube.Cube`.
in_place : bool, default=False
Whether to create a new Cube, or alter the given "cube".
Returns
-------
:class:`iris.cube.Cube`
Notes
-----
This function maintains laziness when called; it does not realise data.
See more at :doc:`/userguide/real_and_lazy_data`.
"""
_assert_is_cube(cube)
new_dtype = _output_dtype(np.log2, cube.dtype, in_place=in_place)
op = da.log2 if cube.has_lazy_data() else np.log2
return _math_op_common(
cube, op, cube.units.log(2), new_dtype=new_dtype, in_place=in_place
)
def log10(cube, in_place=False):
"""Calculate the base-10 logarithm of the cube.
Parameters
----------
cube :
An instance of :class:`iris.cube.Cube`.
in_place : bool, default=False
Whether to create a new Cube, or alter the given "cube".
Returns
-------
:class:`iris.cube.Cube`.
Notes
-----
This function maintains laziness when called; it does not realise data.
See more at :doc:`/userguide/real_and_lazy_data`.
"""
_assert_is_cube(cube)
new_dtype = _output_dtype(np.log10, cube.dtype, in_place=in_place)
op = da.log10 if cube.has_lazy_data() else np.log10
return _math_op_common(
cube, op, cube.units.log(10), new_dtype=new_dtype, in_place=in_place
)
def apply_ufunc(ufunc, cube, other=None, new_unit=None, new_name=None, in_place=False):
"""Apply a `numpy universal function <https://docs.scipy.org/doc/numpy/reference/ufuncs.html>`_ to a cube.
Apply a `numpy universal function
<https://docs.scipy.org/doc/numpy/reference/ufuncs.html>`_ to a cube
or pair of cubes.
.. note:: Many of the numpy.ufunc have been implemented explicitly in Iris
e.g. :func:`numpy.abs`, :func:`numpy.add` are implemented in
:func:`iris.analysis.maths.abs`, :func:`iris.analysis.maths.add`.
It is usually preferable to use these functions rather than
:func:`iris.analysis.maths.apply_ufunc` where possible.
Parameters
----------
ufunc :
An instance of :func:`numpy.ufunc` e.g. :func:`numpy.sin`,
:func:`numpy.mod`.
cube :
An instance of :class:`iris.cube.Cube`.
other ::class:`iris.cube.Cube`, optional
An instance of :class:`iris.cube.Cube` to be given as the second
argument to :func:`numpy.ufunc`.
new_unit : optional
Unit for the resulting Cube.
new_name : optional
Name for the resulting Cube.
in_place : bool, default=False
Whether to create a new Cube, or alter the given "cube".
Returns
-------
:class:`iris.cube.Cube`.
Examples
--------
::
cube = apply_ufunc(numpy.sin, cube, in_place=True)
.. note::
This function maintains laziness when called; it does not realise data. This is dependent on `ufunc` argument
being a numpy operation that is compatible with lazy operation.
See more at :doc:`/userguide/real_and_lazy_data`.
"""
if not isinstance(ufunc, np.ufunc):
ufunc_name = getattr(ufunc, "__name__", "function passed to apply_ufunc")
emsg = f"{ufunc_name} is not recognised, it is not an instance of numpy.ufunc"
raise TypeError(emsg)
ufunc_name = ufunc.__name__
if ufunc.nout != 1:
emsg = (
f"{ufunc_name} returns {ufunc.nout} objects, apply_ufunc currently "
"only supports numpy.ufunc functions returning a single object."
)
raise ValueError(emsg)
if ufunc.nin == 1:
if other is not None:
dmsg = (
"ignoring surplus 'other' argument to apply_ufunc, "
f"provided ufunc {ufunc_name!r} only requires 1 input"
)
logger.debug(dmsg)
new_dtype = _output_dtype(ufunc, cube.dtype, in_place=in_place)
new_cube = _math_op_common(
cube, ufunc, new_unit, new_dtype=new_dtype, in_place=in_place
)
elif ufunc.nin == 2:
if other is None:
emsg = (
f"{ufunc_name} requires two arguments, another cube "
"must also be passed to apply_ufunc."
)
raise ValueError(emsg)
_assert_is_cube(other)
new_dtype = _output_dtype(
ufunc, cube.dtype, second_dtype=other.dtype, in_place=in_place
)
new_cube = _binary_op_common(
ufunc,
ufunc_name,
cube,
other,
new_unit,
new_dtype=new_dtype,
in_place=in_place,
)
else:
emsg = f"Provided ufunc '{ufunc_name}.nin' must be 1 or 2."
raise ValueError(emsg)
new_cube.rename(new_name)
return new_cube
def _binary_op_common(
operation_function,
operation_name,
cube,
other,
new_unit,
new_dtype=None,
dim=None,
in_place=False,
sanitise_metadata=True,
):
"""Share common code between binary operations.
Parameters
----------
operation_function :
Function which does the operation (e.g. numpy.divide)
operation_name :
The public name of the operation (e.g. 'divide')
cube :
The cube whose data is used as the first argument to `operation_function`
other :
The cube, coord, ndarray, dask array or number whose data is used
as the second argument
new_dtype :
The expected dtype of the output. Used in the case of scalar masked arrays
new_unit : optional
Unit for the resulting quantity
dim : optional
Dimension along which to apply `other` if it's a coordinate that is
not found in `cube`
in_place : bool, default=False
whether or not to apply the operation in place to `cube` and `cube.data`
sanitise_metadata : bool, default=True
Whether or not to remove metadata using _sanitise_metadata function
"""
from iris.cube import Cube
_assert_is_cube(cube)
# Flag to notify the _math_op_common function to simply wrap the resultant
# data of the maths operation in a cube with no metadata.
skeleton_cube = False
if isinstance(other, iris.coords.Coord):
# The rhs must be an array.
rhs = _broadcast_cube_coord_data(cube, other, operation_name, dim=dim)
elif isinstance(other, Cube):
# Prepare to resolve the cube operands and associated coordinate
# metadata into the resultant cube.
resolver = Resolve(cube, other)
# Get the broadcast, auto-transposed safe versions of the cube operands.
cube = resolver.lhs_cube_resolved
other = resolver.rhs_cube_resolved
# Flag that it's safe to wrap the resultant data of the math operation
# in a cube with no metadata, as all of the metadata of the resultant
# cube is being managed by the resolver.
skeleton_cube = True
# The rhs must be an array.
rhs = other.core_data()
else:
# The rhs must be an array.
if iris._lazy_data.is_lazy_data(other):
rhs = other
else:
rhs = np.asanyarray(other)
def unary_func(lhs):
data = operation_function(lhs, rhs)
if data is NotImplemented:
# Explicitly raise the TypeError, so it gets raised even if, for
# example, `iris.analysis.maths.multiply(cube, other)` is called
# directly instead of `cube * other`.
emsg = (
f"Cannot {operation_function.__name__} {type(lhs).__name__!r} "
f"and {type(rhs).__name__} objects."
)
raise TypeError(emsg)
return data
if in_place and not cube.has_lazy_data():
# In-place arithmetic doesn't work if array type of LHS is less complex
# than RHS.
if iris._lazy_data.is_lazy_data(rhs):
cube.data = cube.lazy_data()
elif ma.is_masked(rhs) and not isinstance(cube.data, ma.MaskedArray):
cube.data = ma.array(cube.data)
elif isinstance(cube.core_data(), ma.MaskedArray) and iris._lazy_data.is_lazy_data(
rhs
):
# Workaround for #2987. numpy#15200 discusses the general problem.
cube = cube.copy(cube.lazy_data())
result = _math_op_common(
cube,
unary_func,
new_unit,
new_dtype=new_dtype,
in_place=in_place,
skeleton_cube=skeleton_cube,
sanitise_metadata=sanitise_metadata,
)
if isinstance(other, Cube):
# Insert the resultant data from the maths operation
# within the resolved cube.
result = resolver.cube(result.core_data(), in_place=in_place)
if sanitise_metadata:
_sanitise_metadata(result, new_unit)
return result
def _broadcast_cube_coord_data(cube, other, operation_name, dim=None):
# What dimension are we processing?
data_dimension = None
if dim is not None:
# Ensure the given dim matches the coord
if other in cube.coords() and cube.coord_dims(other) != [dim]:
raise ValueError("dim provided does not match dim found for coord")
data_dimension = dim
else:
# Try and get a coord dim
if other.shape != (1,):
try:
coord_dims = cube.coord_dims(other)
data_dimension = coord_dims[0] if coord_dims else None
except iris.exceptions.CoordinateNotFoundError:
raise ValueError(
"Could not determine dimension for %s. "
"Use %s(cube, coord, dim=dim)" % (operation_name, operation_name)
)
if other.ndim != 1:
raise iris.exceptions.CoordinateMultiDimError(other)
if other.has_bounds():
warn_once_at_level(
"Using {!r} with a bounded coordinate is not well "
"defined; ignoring bounds.".format(operation_name),
category=iris.exceptions.IrisIgnoringBoundsWarning,
)
points = other.points
# If the `data_dimension` is defined then shape the provided points for
# proper array broadcasting
if data_dimension is not None:
points_shape = [1] * cube.ndim
points_shape[data_dimension] = -1
points = points.reshape(points_shape)
return points
def _sanitise_metadata(cube, unit):
"""Clear appropriate metadata from the resultant cube.
As part of the maths metadata contract, clear the necessary or
unsupported metadata from the resultant cube of the maths operation.
"""
# Clear the cube names.
cube.rename(None)
# Clear the cube cell methods.
cube.cell_methods = None
# Clear the cell measures.
for cm in cube.cell_measures():
cube.remove_cell_measure(cm)
# Clear the ancillary variables.
for av in cube.ancillary_variables():
cube.remove_ancillary_variable(av)
# Clear the STASH attribute, if present.
if "STASH" in cube.attributes:
del cube.attributes["STASH"]
# Set the cube units.
cube.units = unit
def _math_op_common(
cube,
operation_function,
new_unit,
new_dtype=None,
in_place=False,
skeleton_cube=False,
sanitise_metadata=True,
):
from iris.cube import Cube
_assert_is_cube(cube)