-
Notifications
You must be signed in to change notification settings - Fork 19
/
utils.py
1723 lines (1318 loc) · 49.6 KB
/
utils.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
"""Worker functions for regridding."""
import logging
from operator import itemgetter
import numpy as np
from .. import _found_ESMF
from ..data import Data
from ..dimensioncoordinate import DimensionCoordinate
from ..functions import regrid_logging
if _found_ESMF:
try:
import ESMF
except Exception:
_found_ESMF = False
from .regridoperator import (
RegridOperator,
conservative_regridding_methods,
regrid_method_map,
regridding_methods,
)
logger = logging.getLogger(__name__)
def regrid_compute_mass_grid(
valuefield,
areafield,
dofrac=False,
fracfield=None,
uninitval=422397696.0,
):
"""Compute the mass of an `ESMF` Field.
:Parameters:
valuefield: `ESMF.Field`
This contains data values of a field built on the cells of
a grid.
areafield: `ESMF.Field`
This contains the areas associated with the grid cells.
fracfield: `ESMF.Field`
This contains the fractions of each cell which contributed
to a regridding operation involving 'valuefield.
dofrac: `bool`
This gives the option to not use the 'fracfield'.
uninitval: `float`
The value uninitialised cells take.
:Returns:
`float`
The mass of the data field.
"""
mass = 0.0
areafield.get_area()
ind = np.where(valuefield.data != uninitval)
if dofrac:
mass = np.sum(
areafield.data[ind] * valuefield.data[ind] * fracfield.data[ind]
)
else:
mass = np.sum(areafield.data[ind] * valuefield.data[ind])
return mass
def regrid_get_latlon(f, name, method, axes=None):
"""Get latitude and longitude coordinate information.
Retrieve the latitude and longitude coordinates of a field, as
well as some associated information. If 1-d lat/lon coordinates
are found then these are returned. Otherwise if 2-d lat/lon
coordinates found then these are returned.
:Parameters:
f: `Field`
The source or destination field from which to get the
information.
name: `str`
A name to identify the field in error messages. Either
``'source'`` or ``'destination'``.
method: `str`
The regridding method.
axes: `dict`, optional
A dictionary specifying the X and Y axes, with keys
``'X'`` and ``'Y'``.
*Parameter example:*
``axes={'X': 'ncdim%x', 'Y': 'ncdim%y'}``
*Parameter example:*
``axes={'X': 1, 'Y': 0}``
:Returns:
`list`, `list`, `list`, `list`, `bool`
* The keys of the X and Y dimension coordinates.
* The sizes of the X and Y dimension coordinates.
* The keys of the X and Y coordinate (1-d dimension
coordinate, or 2-d auxilliary coordinates).
* The X and Y coordinates (1-d dimension coordinates or
2-d auxilliary coordinates).
* True if 2-d auxiliary coordinates are returned or if 1-d
X and Y coordinates are returned, which are not
lon/lat.
"""
data_axes = f.constructs.data_axes()
if axes is None:
# Retrieve the field construct's X and Y dimension
# coordinates
x_key, x = f.dimension_coordinate(
"X",
item=True,
default=ValueError(
f"No unique X dimension coordinate found for the {name} "
f"field {f!r}. If none is present you "
"may need to specify the axes keyword."
),
)
y_key, y = f.dimension_coordinate(
"Y",
item=True,
default=ValueError(
f"No unique Y dimension coordinate found for the {name} "
f"field {f!r}. If none is present you "
"may need to specify the axes keyword."
),
)
x_axis = data_axes[x_key][0]
y_axis = data_axes[y_key][0]
x_size = x.size
y_size = y.size
else:
# --------------------------------------------------------
# Axes have been provided
# --------------------------------------------------------
for key in ("X", "Y"):
if key not in axes:
raise ValueError(
f"Key {key!r} must be specified for axes of {name} "
f"field {f!r}."
)
if axes["X"] in (1, 0) and axes["Y"] in (0, 1):
# Axes specified by integer position in dimensions of
# lat and lon 2-d auxiliary coordinates
if axes["X"] == axes["Y"]:
raise ValueError(
"The X and Y axes must be distinct, but they are the same "
"for {name} field {f!r}."
)
lon_key, lon = f.auxiliary_coordinate(
"X", item=True, filter_by_naxes=(2,), default=(None, None)
)
lat_key, lat = f.auxiliary_coordinate(
"Y", item=True, filter_by_naxes=(2,), default=(None, None)
)
if lon is None:
raise ValueError(
"The X axis does not correspond to a longitude coordinate "
f"for {name} field {f!r}."
)
if lat is None:
raise ValueError(
"The Y axis does not correspond to a latitude coordinate "
f"for {name} field {f!r}."
)
if lat.shape != lon.shape:
raise ValueError(
"The shape of the latitude and longitude coordinates "
"must be equal but they differ for {name} field {f!r}."
)
lon_axes = data_axes[lon_key]
lat_axes = data_axes[lat_key]
if lat_axes != lon_axes:
raise ValueError(
"The domain axis constructs spanned by the latitude and "
"longitude coordinates should be the same, but they "
"differ for {name} field {f!r}."
)
x_axis = lon_axes[axes["X"]]
y_axis = lat_axes[axes["Y"]]
else:
x_axis = f.domain_axis(
axes["X"],
key=True,
default=ValueError(
f"'X' axis specified for {name} {f!r} field not found."
),
)
y_axis = f.domain_axis(
axes["Y"],
key=True,
default=ValueError(
f"'Y' axis specified for {name} field {f!r} not found."
),
)
domain_axes = f.domain_axes(todict=True)
x_size = domain_axes[x_axis].get_size()
y_size = domain_axes[y_axis].get_size()
axis_keys = [x_axis, y_axis]
axis_sizes = [x_size, y_size]
# If 1-d latitude and longitude coordinates for the field are
# not found search for 2-d auxiliary coordinates.
if axes is not None or not x.Units.islongitude or not y.Units.islatitude:
lon_found = False
lat_found = False
for key, aux in f.auxiliary_coordinates(
filter_by_naxes=(2,), todict=True
).items():
if aux.Units.islongitude:
if lon_found:
raise ValueError(
"The 2-d auxiliary longitude coordinate "
f"of the {name} field {f!r} is not unique."
)
else:
lon_found = True
x = aux
x_key = key
if aux.Units.islatitude:
if lat_found:
raise ValueError(
"The 2-d auxiliary latitude coordinate "
f"of the {name} field {f!r} is not unique."
)
else:
lat_found = True
y = aux
y_key = key
if not lon_found or not lat_found:
raise ValueError(
"Both longitude and latitude coordinates "
f"were not found for the {name} field {f!r}."
)
if axes is not None:
if set(axis_keys) != set(data_axes[x_key]):
raise ValueError(
"Axes of longitude do not match "
f"those specified for {name} field {f!r}."
)
if set(axis_keys) != set(data_axes[y_key]):
raise ValueError(
"Axes of latitude do not match "
f"those specified for {name} field {f!r}."
)
coords_2D = True
else:
coords_2D = False
# Check for size 1 latitude or longitude dimensions if source grid
# (a size 1 dimension is only problematic for the source grid in ESMF)
if (
name == "source"
and method in ("linear", "bilinear", "patch")
and (x_size == 1 or y_size == 1)
):
raise ValueError(
f"Neither the longitude nor latitude dimensions of the {name}"
f"field {f!r} can be of size 1 for {method!r} regridding."
)
coord_keys = [x_key, y_key]
coords = [x, y]
return axis_keys, axis_sizes, coord_keys, coords, coords_2D
def get_cartesian_coords(f, name, axes):
"""Retrieve the specified cartesian dimension coordinates of the
field and their corresponding keys.
:Parameters:
f: `Field`
The field from which to get the coordinates.
name: `str`
A name to identify the field in error messages.
axes: sequence of `str`
Specifiers for the dimension coordinates to be
retrieved. See `cf.Field.domain_axes` for details.
:Returns:
`list`, `list`
A list of the keys of the dimension coordinates; and a
list of the dimension coordinates retrieved.
"""
axis_keys = []
for axis in axes:
key = f.domain_axis(axis, key=True)
axis_keys.append(key)
coords = []
for key in axis_keys:
d = f.dimension_coordinate(filter_by_axis=(key,), default=None)
if d is None:
raise ValueError(
f"No unique {name} dimension coordinate "
f"matches key {key!r}."
)
coords.append(d.copy())
return axis_keys, coords
def regrid_get_axis_indices(f, axis_keys):
"""Get axis indices and their orders in rank of this field.
:Parameters:
f: `Field`
The source or destination field. This field might get
size-1 dimensions inserted into its data in-place.
axis_keys: sequence
A sequence of domain axis identifiers for the axes being
regridded.
:Returns:
`list`, `list`, `numpy.ndarray`
* The indices of the specified axes.
* The indices of the non-specified field data axes .
* The rank order of the axes.
"""
data_axes = f.get_data_axes()
# Get the positions of the axes
axis_indices = []
for axis_key in axis_keys:
try:
axis_index = data_axes.index(axis_key)
except ValueError:
f.insert_dimension(axis_key, position=0, inplace=True)
axis_index = 0
axis_indices.append(axis_index)
# Get the rank order of the positions of the axes
tmp = np.array(axis_indices)
tmp = tmp.argsort()
n = len(tmp)
order = np.empty((n,), dtype=int)
order[tmp] = np.arange(n)
non_regridding_axis_indices = [
i for i in range(f.ndim) if i not in axis_indices
]
return axis_indices, non_regridding_axis_indices, order
def regrid_get_coord_order(f, axis_keys, coord_keys):
"""Get the ordering of the axes for each N-d auxiliary coordinate.
:Parameters:
f: `Field`
The source or destination field.
axis_keys: sequence
A sequence of axis keys.
coord_keys: sequence
A sequence of keys for each of the N-d auxiliary
coordinates.
:Returns:
`list`
A list of lists specifying the ordering of the axes for
each N-d auxiliary coordinate.
"""
coord_axes = [f.get_data_axes(coord_key) for coord_key in coord_keys]
coord_order = [
[coord_axis.index(axis_key) for axis_key in axis_keys]
for coord_axis in coord_axes
]
return coord_order
def regrid_get_section_shape(src, axis_sizes, axis_indices):
"""Get the shape of each regridded section.
:Parameters:
src: `Field`
The source field.
axis_sizes: sequence
A sequence of the sizes of each axis along which the
section. will be taken
axis_indices: sequence
A sequence of the same length giving the axis index of
each axis.
:Returns:
`list`
A list of integers defining the shape of each section.
"""
shape = [1] * src.ndim
for i, axis_index in enumerate(axis_indices):
shape[axis_index] = axis_sizes[i]
return shape
def regrid_check_bounds(src_coords, dst_coords, method, ext_coords=None):
"""Check the bounds of the coordinates for regridding.
:Parameters:
src_coords: sequence
A sequence of the source coordinates.
dst_coords: sequence
A sequence of the destination coordinates.
method: `str`
A string indicating the regrid method.
ext_coords: `None` or sequence
If a sequence of extension coordinates is present these
are also checked. Only used for cartesian regridding when
regridding only 1 (only 1!) dimension of an N>2
dimensional field. In this case we need to provided the
coordinates of the dimensions that aren't being regridded
(that are the same in both src and dst grids) so that we
can create a sensible ESMF grid object.
:Returns:
`None`
"""
if method not in conservative_regridding_methods:
# Bounds are only not needed for conservative methods
return
for name, coords in zip(
("Source", "Destination"), (src_coords, dst_coords)
):
for coord in coords:
if not coord.has_bounds():
raise ValueError(
f"{name} {coord!r} coordinates must have bounds "
"for conservative regridding."
)
if not coord.contiguous(overlap=False):
raise ValueError(
f"{name} {coord!r} coordinates must have "
"contiguous, non-overlapping bounds "
"for conservative regridding."
)
if ext_coords is not None:
for coord in ext_coords:
if not coord.has_bounds():
raise ValueError(
f"{coord!r} dimension coordinates must have "
"bounds for conservative regridding."
)
if not coord.contiguous(overlap=False):
raise ValueError(
f"{coord!r} dimension coordinates must have "
"contiguous, non-overlapping bounds "
"for conservative regridding."
)
def regrid_check_method(method):
"""Check that the regrid method is valid.
If it is not valid then an exception is raised.
:Parameters:
method: `str`
The regridding method.
:Returns:
`None`
"""
if method not in regridding_methods:
raise ValueError(
"Can't regrid: Must set a valid regridding method from "
f"{regridding_methods}. Got: {method!r}"
)
elif method == "bilinear":
logger.info(
"Note the 'bilinear' method argument has been renamed to "
"'linear' at version 3.2.0. It is still supported for now "
"but please use 'linear' in future. "
"'bilinear' will be removed at version 4.0.0."
)
def regrid_check_use_src_mask(use_src_mask, method):
"""Check the setting of the use_src_mask parameter.
An exception is raised is the setting is incorrect relative to the
regridding method.
:Parameters:
use_src_mask: `bool`
Whether to use the source mask in regridding.
method: `str`
The regridding method.
:Returns:
`None`
"""
if not use_src_mask and not method == "nearest_stod":
raise ValueError(
"The use_src_mask parameter can only be False when using the "
"'nearest_stod' regridding method."
)
def regrid_get_reordered_sections(
src, axis_order, regrid_axes, regrid_axis_indices
):
"""Get a dictionary of the data sections for regridding and a list
of its keys reordered if necessary so that they will be looped over
in the order specified in axis_order.
:Parameters:
src: `Field`
The source field.
axis_order: `None` or sequence of axes specifiers.
If `None` then the sections keys will not be reordered. If
a particular axis is one of the regridding axes or is not
found then a ValueError will be raised.
regrid_axes: sequence
A sequence of the keys of the regridding axes.
regrid_axis_indices: sequence
A sequence of the indices of the regridding axes.
:Returns:
`list`, `dict`
An ordered list of the section keys; and a dictionary of
the data sections for regridding.
"""
# If we had dynamic masking, we wouldn't need this method, we
# could simply replace it in the calling function with a call to
# Data.section. However, we don't have it, so this allows us to
# possibly reduce the number of transitions between different
# masks - each change is slow.
data_axes = src.get_data_axes()
axis_indices = []
if axis_order is not None:
for axis in axis_order:
axis_key = src.dimension_coordinate(
filter_by_axis=(axis,),
default=None,
key=True,
)
if axis_key is not None:
if axis_key in regrid_axes:
raise ValueError("Cannot loop over regridding axes.")
try:
axis_indices.append(data_axes.index(axis_key))
except ValueError:
# The axis has been squeezed so do nothing
pass
else:
raise ValueError(f"Source field axis not found: {axis!r}")
# Section the data
sections = src.data.section(regrid_axis_indices)
# Reorder keys correspondingly if required
if axis_indices:
section_keys = sorted(sections.keys(), key=itemgetter(*axis_indices))
else:
section_keys = sections.keys()
return section_keys, sections
def regrid_get_destination_mask(
f, dst_order, axes=("X", "Y"), cartesian=False, coords_ext=None
):
"""Get the mask of the destination field.
:Parameters:
f: `Field`
The destination field.
dst_order: sequence, optional
The order of the destination axes.
axes: optional
The axes the data is to be sectioned along.
cartesian: `bool`, optional
Whether the regridding is Cartesian or spherical.
coords_ext: sequence, optional
In the case of Cartesian regridding, extension coordinates
(see _regrid_check_bounds for details).
:Returns:
`numpy.ndarray`
The mask.
"""
data_axes = f.get_data_axes()
indices = {axis: [0] for axis in data_axes if axis not in axes}
g = f.subspace(**indices)
g = g.squeeze(tuple(indices)).transpose(dst_order)
dst_mask = g.mask.array
if cartesian:
tmp = []
for coord in coords_ext:
tmp.append(coord.size)
dst_mask = np.tile(dst_mask, tmp + [1] * dst_mask.ndim)
return dst_mask
def regrid_fill_fields(src_data, srcfield, dstfield, fill_value):
"""Fill the source and destination Fields.
Fill the source Field with data and the destination Field with
fill values.
:Parameters:
src_data: ndarray
The data to fill the source field with.
srcfield: `ESMF.Field`
The source field.
dstfield: `ESMF.Field`
The destination field. This get always gets initialised with
missing values.
fill_value:
The fill value with which to fill *dstfield*
:Returns:
`None`
"""
srcfield.data[...] = np.ma.MaskedArray(src_data, copy=False).filled(
fill_value
)
dstfield.data[...] = fill_value
def regrid_compute_field_mass(
f,
_compute_field_mass,
k,
srcgrid,
srcfield,
srcfracfield,
dstgrid,
dstfield,
):
"""Compute the field mass for conservative regridding.
The mass should be the same before and after regridding.
:Parameters:
f: `Field`
The source field.
_compute_field_mass: `dict`
A dictionary for the results.
k: `tuple`
A key identifying the section of the field being regridded.
srcgrid: `ESMF.Grid`
The source grid.
srcfield: `ESMF.Grid`
The source field.
srcfracfield: `ESMF.Field`
Information about the fraction of each cell of the source
field used in regridding.
dstgrid: `ESMF.Grid`
The destination grid.
dstfield: `ESMF.Field`
The destination field.
:Returns:
`None`
"""
if not isinstance(_compute_field_mass, dict):
raise ValueError("Expected _compute_field_mass to be a dictionary.")
fill_value = f.fill_value(default="netCDF")
# Calculate the mass of the source field
srcareafield = create_Field(srcgrid, "srcareafield")
srcmass = regrid_compute_mass_grid(
srcfield,
srcareafield,
dofrac=True,
fracfield=srcfracfield,
uninitval=fill_value,
)
# Calculate the mass of the destination field
dstareafield = create_Field(dstgrid, "dstareafield")
dstmass = regrid_compute_mass_grid(
dstfield, dstareafield, uninitval=fill_value
)
# Insert the two masses into the dictionary for comparison
_compute_field_mass[k] = (srcmass, dstmass)
# Release memory
srcareafield.destroy()
dstareafield.destroy()
def regrid_get_regridded_data(f, method, fracfield, dstfield, dstfracfield):
"""Get the regridded data.
:Parameters:
f: `Field`
The source field.
method: `str`
The regridding method.
fracfield: `bool`
Whether to return the frac field or not in the case of
conservative regridding.
dstfield: `ESMF.Field`
The destination field.
dstfracfield: `ESMF.Field`
Information about the fraction of each of the destination
field cells involved in the regridding. For conservative
regridding this must be taken into account.
:Returns:
`numpy.ndarray`
The regridded data.
"""
if method in conservative_regridding_methods:
frac = dstfracfield.data.copy()
if fracfield:
regridded_data = frac
else:
frac[frac == 0.0] = 1.0
regridded_data = np.ma.MaskedArray(
dstfield.data / frac,
mask=(dstfield.data == f.fill_value(default="netCDF")),
)
else:
regridded_data = np.ma.MaskedArray(
dstfield.data.copy(),
mask=(dstfield.data == f.fill_value(default="netCDF")),
)
return regridded_data
def regrid_update_coordinate_references(
f,
dst,
src_axis_keys,
dst_axis_sizes,
method,
use_dst_mask,
cartesian=False,
axes=("X", "Y"),
n_axes=2,
src_cyclic=False,
dst_cyclic=False,
):
"""Update the coordinate references of the regridded field.
:Parameters:
f: `Field`
The regridded field. Updated in-place.
dst: `Field` or `dict`
The object with the destination grid for regridding.
src_axis_keys: sequence of `str`
The keys of the source regridding axes.
dst_axis_sizes: sequence, optional
The sizes of the destination axes.
method: `bool`
The regridding method.
use_dst_mask: `bool`
Whether to use the destination mask in regridding.
cartesian: `bool`, optional
Whether to do Cartesian regridding or spherical
axes: sequence, optional
Specifiers for the regridding axes.
n_axes: `int`, optional
The number of regridding axes.
src_cyclic: `bool`, optional
Whether the source longitude is cyclic for spherical
regridding.
dst_cyclic: `bool`, optional
Whether the destination longitude is cyclic for spherical
regridding.
:Returns:
`None`
"""
domain_ancillaries = f.domain_ancillaries(todict=True)
# Initialise cached value for domain_axes
domain_axes = None
data_axes = f.constructs.data_axes()
for key, ref in f.coordinate_references(todict=True).items():
ref_axes = []
for k in ref.coordinates():
ref_axes.extend(data_axes[k])
if set(ref_axes).intersection(src_axis_keys):
f.del_construct(key)
continue
for (
term,
value,
) in ref.coordinate_conversion.domain_ancillaries().items():
if value not in domain_ancillaries:
continue
key = value
# If this domain ancillary spans both X and Y axes
# then regrid it, otherwise remove it
x = f.domain_axis("X", key=True)
y = f.domain_axis("Y", key=True)
if (
f.domain_ancillary(
filter_by_axis=(x, y),
axis_mode="exact",
key=True,
default=None,
)
is not None
):
# Convert the domain ancillary into an independent
# field
value = f.convert(key)
try:
if cartesian:
value.regridc(
dst,
axes=axes,
method=method,
use_dst_mask=use_dst_mask,
inplace=True,
)
else:
value.regrids(
dst,
src_cyclic=src_cyclic,
dst_cyclic=dst_cyclic,
method=method,
use_dst_mask=use_dst_mask,
inplace=True,
)
except ValueError:
ref.coordinate_conversion.set_domain_ancillary(term, None)
f.del_construct(key)
else:
ref.coordinate_conversion.set_domain_ancillary(term, key)
d_axes = data_axes[key]
domain_axes = f.domain_axes(
cached=domain_axes, todict=True
)
for k_s, new_size in zip(src_axis_keys, dst_axis_sizes):
domain_axes[k_s].set_size(new_size)
f.set_construct(
f._DomainAncillary(source=value),
key=key,
axes=d_axes,
copy=False,
)
def regrid_copy_coordinate_references(f, dst, dst_axis_keys):
"""Copy coordinate references from the destination field to the new,
regridded field.
:Parameters:
f: `Field`
The source field.
dst: `Field`
The destination field.
dst_axis_keys: sequence of `str`
The keys of the regridding axes in the destination field.