-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathregrid.py
More file actions
3134 lines (2543 loc) · 103 KB
/
regrid.py
File metadata and controls
3134 lines (2543 loc) · 103 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
"""Worker functions for regridding."""
import logging
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any
import dask.array as da
import numpy as np
from cfdm import is_log_level_debug
from ..functions import DeprecationError, regrid_logging
from ..units import Units
from .regridoperator import RegridOperator
# ESMF renamed its Python module to `esmpy` at ESMF version 8.4.0. Allow
# either for now for backwards compatibility.
esmpy_imported = False
try:
import esmpy
esmpy_imported = True
except ImportError:
try:
# Take the new name to use in preference to the old one.
import ESMF as esmpy
esmpy_imported = True
except ImportError:
pass
logger = logging.getLogger(__name__)
# Mapping of regrid method strings to esmpy method codes. The values
# get replaced with `esmpy.RegridMethod` constants the first time
# `esmpy_initialise` is run.
esmpy_methods = {
"linear": None,
"bilinear": None,
"conservative": None,
"conservative_1st": None,
"conservative_2nd": None,
"nearest_dtos": None,
"nearest_stod": None,
"patch": None,
}
@dataclass()
class Grid:
"""A source or destination grid definition.
.. versionadded:: 3.14.0
"""
# Identify the grid as 'source' or 'destination'.
name: str = ""
# The coordinate system of the grid.
coord_sys: str = ""
# The type of the grid. E.g. 'structured grid'
type: str = ""
# The domain axis identifiers of the regrid axes, in the order
# expected by `Data._regrid`. E.g. ['domainaxis3', 'domainaxis2']
axis_keys: list = field(default_factory=list)
# The positions of the regrid axes, in the order expected by
# `Data._regrid`. E.g. [3, 2] or [3]
axis_indices: list = field(default_factory=list)
# The domain axis identifiers of the regridding axes. E.g. {'X':
# 'domainaxis2', 'Y': 'domainaxis1'} or ['domainaxis1',
# 'domainaxis2'], or {'X': 'domainaxis2', 'Y': 'domainaxis2'}
axes: Any = None
# The number of regrid axes.
n_regrid_axes: int = 0
# The dimensionality of the regridding on this grid. Generally the
# same as *n_regrid_axes*, but for a regridding a UGRID mesh axis
# *n_regrid_axes* is 1 and *dimensionality* is 2.
dimensionality: int = 0
# The shape of the regridding axes, in the same order as the
# 'axis_keys' attribute. E.g. (96, 73) or (1243,)
shape: tuple = None
# The regrid axis coordinates, in the order expected by
# `esmpy`. If the coordinates are 2-d (or more) then the axis
# order of each coordinate object must be as expected by `esmpy`.
coords: list = field(default_factory=list)
# The regrid axis coordinate bounds, in the order expected by
# `esmpy`. If the coordinates are 2-d (or more) then the axis
# order of each bounds object must be as expected by `esmpy`.
bounds: list = field(default_factory=list)
# Only used if `mesh` is False. For spherical regridding, whether
# or not the longitude axis is cyclic.
cyclic: Any = None
# The regridding method.
method: str = ""
# If True then, for 1-d regridding, the esmpy weights are generated
# for a 2-d grid for which one of the dimensions is a size 2 dummy
# dimension.
dummy_size_2_dimension: bool = False
# Whether or not the grid is a structured grid.
is_grid: bool = False
# Whether or not the grid is a UGRID mesh.
is_mesh: bool = False
# Whether or not the grid is a location stream.
is_locstream: bool = False
# The type of grid.
type: str = "unknown"
# The location on a UGRID mesh topology of the grid cells. An
# empty string means that the grid is not a UGRID mesh
# topology. E.g. '' or 'face'.
mesh_location: str = ""
# A domain topology construct that spans the regrid axis. A value
# of None means that the grid is not a UGRID mesh topology.
domain_topology: Any = None
# The featureType of a discrete sampling geometry grid. An empty
# string means that the grid is not a DSG. E.g. '' or
# 'trajectory'.
featureType: str = ""
# The domain axis identifiers of new axes that result from the
# regridding operation changing the number of data dimensions
# (e.g. by regridding a source UGRID (1-d) grid to a destination
# non-UGRID (2-d) grid, or vice versa). An empty list means that
# the regridding did not change the number of data axes. E.g. [],
# ['domainaxis3', 'domainaxis4'], ['domainaxis4']
new_axis_keys: list = field(default_factory=list)
# Specify vertical regridding coordinates. E.g. 'air_pressure',
# 'domainaxis0'
z: Any = None
# Whether or not to use ln(z) when calculating vertical weights
ln_z: bool = False
# The integer position in *coords* of a vertical coordinate. If
# `None` then there are no vertical coordinates.
z_index: Any = None
def regrid(
coord_sys,
src,
dst,
method=None,
src_cyclic=None,
dst_cyclic=None,
use_src_mask=True,
use_dst_mask=False,
src_axes=None,
dst_axes=None,
axes=None,
src_z=None,
dst_z=None,
z=None,
ln_z=None,
ignore_degenerate=True,
return_operator=False,
check_coordinates=False,
min_weight=None,
weights_file=None,
return_esmpy_regrid_operator=False,
inplace=False,
):
"""Regrid a field to a new spherical or Cartesian grid.
This is a worker function primarily intended to be called by
`cf.Field.regridc` and `cf.Field.regrids`.
.. versionadded:: 3.14.0
.. seealso:: `cf.Field.regridc`, `cf.Field.regrids`,
`cf.data.dask_regrid.regrid`.
:Parameters:
coord_sys: `str`
The name of the coordinate system of the source and
destination grids. Either ``'spherical'`` or
``'Cartesian'``.
src: `Field`
The source field to be regridded.
dst: `Field`, `Domain`, `RegridOperator` or sequence of `Coordinate`
The definition of the destination grid.
See `cf.Field.regrids` (for spherical regridding) or
`cf.Field.regridc` (for Cartesian regridding) for details.
method: `str`
Specify which interpolation method to use during
regridding. This parameter must be set unless *dst* is a
`RegridOperator`, when the *method* is ignored.
See `cf.Field.regrids` (for spherical regridding) or
`cf.Field.regridc` (for Cartesian regridding) for details.
src_cyclic: `None` or `bool`, optional
For spherical regridding, specifies whether or not the
source grid longitude axis is cyclic.
See `cf.Field.regrids` (for spherical regridding) or
`cf.Field.regridc` (for Cartesian regridding) for details.
dst_cyclic: `None` or `bool`, optional
For spherical regridding, specifies whether or not the
destination grid longitude axis is cyclic.
See `cf.Field.regrids` (for spherical regridding) or
`cf.Field.regridc` (for Cartesian regridding) for details.
use_src_mask: `bool`, optional
Whether or not to use the source grid mask.
See `cf.Field.regrids` (for spherical regridding) or
`cf.Field.regridc` (for Cartesian regridding) for details.
use_dst_mask: `bool`, optional
Whether or not to use the source grid mask.
See `cf.Field.regrids` (for spherical regridding) or
`cf.Field.regridc` (for Cartesian regridding) for details.
src_axes: `dict` or sequence or `None`, optional
Define the source grid axes to be regridded.
See `cf.Field.regrids` (for spherical regridding) or
`cf.Field.regridc` (for Cartesian regridding) for details.
dst_axes: `dict` or sequence or `None`, optional
Define the destination grid axes to be regridded.
See `cf.Field.regrids` (for spherical regridding) or
`cf.Field.regridc` (for Cartesian regridding) for details.
Ignored for Cartesian regridding.
axes: sequence, optional
Define the axes to be regridded for the source grid and,
if *dst* is a `Field` or `Domain`, the destination
grid. Ignored for spherical regridding.
See `cf.Field.regridc` for details.
ignore_degenerate: `bool`, optional
Whether or not to ignore degenerate cells.
See `cf.Field.regrids` (for spherical regridding) or
`cf.Field.regridc` (for Cartesian regridding) for details.
Ignored for Cartesian regridding.
return_operator: `bool`, optional
If True then do not perform the regridding, rather return
the `RegridOperator` instance that defines the regridding
operation, and which can be used in subsequent calls.
See `cf.Field.regrids` (for spherical regridding) or
`cf.Field.regridc` (for Cartesian regridding) for details.
check_coordinates: `bool`, optional
Whether or not to check the regrid operator source grid
coordinates. Ignored unless *dst* is a `RegridOperator`.
If True and then the source grid coordinates defined by
the regrid operator are checked for compatibility against
those of the *src* field. By default this check is not
carried out. See the *dst* parameter for details.
If False then only the computationally cheap tests are
performed (checking that the coordinate system, cyclicity
and grid shape are the same).
inplace: `bool`, optional
If True then modify *src* in-place and return `None`.
return_esmpy_regrid_operator: `bool`, optional
If True then *src* is not regridded, but the
`esmpy.Regrid` instance for the operation is returned
instead. This is useful for checking that the field has
been regridded correctly.
weights_file: `str` or `None`, optional
Provide a netCDF file that contains, or will contain, the
regridding weights.
See `cf.Field.regrids` (for spherical regridding) or
`cf.Field.regridc` (for Cartesian regridding) for details.
.. versionadded:: 3.15.2
src_z: optional
The identity of the source grid vertical coordinates used
to calculate the weights. If `None` then no vertical axis
is identified, and in the spherical case regridding will
be 2-d.
See `cf.Field.regrids` (for spherical regridding) or
`cf.Field.regridc` (for Cartesian regridding) for details.
.. versionadded:: 3.16.2
dst_z: optional
The identity of the destination grid vertical coordinates
used to calculate the weights. If `None` then no vertical
axis is identified, and in the spherical case regridding
will be 2-d.
See `cf.Field.regrids` (for spherical regridding) or
`cf.Field.regridc` (for Cartesian regridding) for details.
.. versionadded:: 3.16.2
z: optional
The *z* parameter is a convenience that may be used to
replace both *src_z* and *dst_z* when they would contain
identical values.
See `cf.Field.regrids` (for spherical regridding) or
`cf.Field.regridc` (for Cartesian regridding) for details.
.. versionadded:: 3.16.2
ln_z: `bool` or `None`, optional
Whether or not the weights are to be calculated with the
natural logarithm of vertical coordinates.
See `cf.Field.regrids` (for spherical regridding) or
`cf.Field.regridc` (for Cartesian regridding) for details.
.. versionadded:: 3.16.2
:Returns:
`Field` or `None` or `RegridOperator` or `esmpy.Regrid`
The regridded field construct; or `None` if the operation
was in-place; or the regridding operator if
*return_operator* is True.
If *return_esmpy_regrid_operator* is True then *src* is
not regridded, but the `esmpy.Regrid` instance for the
operation is returned instead.
"""
if not inplace:
src = src.copy()
spherical = coord_sys == "spherical"
cartesian = not spherical
# ----------------------------------------------------------------
# Parse and check parameters
# ----------------------------------------------------------------
if isinstance(dst, RegridOperator):
regrid_operator = dst
dst = regrid_operator.dst.copy()
method = regrid_operator.method
dst_cyclic = regrid_operator.dst_cyclic
dst_axes = regrid_operator.dst_axes
dst_z = regrid_operator.dst_z
src_z = regrid_operator.src_z
ln_z = regrid_operator.ln_z
if regrid_operator.coord_sys == "Cartesian":
src_axes = regrid_operator.src_axes
create_regrid_operator = False
else:
create_regrid_operator = True
# Parse the z, src_z, dst_z, and ln_z parameters
if z is not None:
if dst_z is None:
dst_z = z
else:
raise ValueError("Can't set both 'z' and 'dst_z'")
if src_z is None:
src_z = z
else:
raise ValueError("Can't set both 'z' and 'src_z'")
elif (src_z is None) != (dst_z is None):
raise ValueError(
"Must set both 'src_z' and 'dst_z', or neither of them"
)
if ln_z is None and src_z is not None:
raise ValueError(
"When 'z', 'src_z', or 'dst_z' have been set, "
"'ln_z' cannot be None."
)
ln_z = bool(ln_z)
if method not in esmpy_methods:
raise ValueError(
"Can't regrid: Must set a valid regridding method from "
f"{sorted(esmpy_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."
)
if not use_src_mask and not method == "nearest_stod":
raise ValueError(
"The 'use_src_mask' parameter can only be False when "
f"using the {method!r} regridding method."
)
if cartesian:
if isinstance(axes, str):
axes = (axes,)
if src_axes is None:
src_axes = axes
elif axes is not None:
raise ValueError(
"Can't set both the 'axes' and 'src_axes' parameters"
)
elif isinstance(src_axes, str):
src_axes = (src_axes,)
if dst_axes is None:
dst_axes = axes
elif axes is not None:
raise ValueError(
"Can't set both the 'axes' and 'dst_axes' parameters"
)
elif isinstance(dst_axes, str):
dst_axes = (dst_axes,)
if isinstance(dst, src._Domain):
use_dst_mask = False
dst = dst.copy()
elif isinstance(dst, src.__class__):
dst = dst.copy()
elif isinstance(dst, RegridOperator):
pass
else:
if isinstance(dst, dict):
raise DeprecationError(
"Setting the 'dst' parameter to a dictionary was "
"deprecated at version 3.14.0. Use a sequence of "
"Coordinate instances instead. See the docs for details."
)
try:
dst[0]
except TypeError:
raise TypeError(
"The 'dst' parameter must be one of Field, Domain, "
f"RegridOperator, or a sequence of Coordinate. Got: {dst!r}"
)
except IndexError:
# This error will get trapped in one of the following
# *_coords_to_domain calls
pass
# Convert a sequence of Coordinates that define the
# destination grid into a Domain object
use_dst_mask = False
if spherical:
dst, dst_axes, dst_z = spherical_coords_to_domain(
dst,
dst_axes=dst_axes,
cyclic=dst_cyclic,
dst_z=dst_z,
domain_class=src._Domain,
)
else:
# Cartesian
dst, dst_axes, dst_z = Cartesian_coords_to_domain(
dst, dst_z=dst_z, domain_class=src._Domain
)
# ----------------------------------------------------------------
# Create descriptions of the source and destination grids
# ----------------------------------------------------------------
dst_grid = get_grid(
coord_sys,
dst,
"destination",
method,
dst_cyclic,
axes=dst_axes,
z=dst_z,
ln_z=ln_z,
)
src_grid = get_grid(
coord_sys,
src,
"source",
method,
src_cyclic,
axes=src_axes,
z=src_z,
ln_z=ln_z,
)
if is_log_level_debug(logger):
logger.debug(
f"Source Grid:\n{src_grid}\n\nDestination Grid:\n{dst_grid}\n"
) # pragma: no cover
conform_coordinates(src_grid, dst_grid)
if method in ("conservative_2nd", "patch"):
if not (src_grid.dimensionality >= 2 and dst_grid.dimensionality >= 2):
raise ValueError(
f"{method!r} regridding is not available for 1-d regridding"
)
elif method in ("nearest_dtos", "nearest_stod"):
if not has_coordinate_arrays(src_grid) and not has_coordinate_arrays(
dst_grid
):
raise ValueError(
f"{method!r} regridding is only available when both the "
"source and destination grids have coordinate arrays"
)
if method == "nearest_dtos":
if src_grid.is_mesh is not dst_grid.is_mesh:
raise ValueError(
f"{method!r} regridding is (at the moment) only available "
"when neither or both the source and destination grids "
"are a UGRID mesh"
)
if dst_grid.is_locstream:
raise ValueError(
f"{method!r} regridding is (at the moment) not available "
"when the destination grid is a DSG featureType."
)
elif cartesian and (src_grid.is_mesh or dst_grid.is_mesh):
raise ValueError(
"Cartesian regridding is (at the moment) not available when "
"either the source or destination grid is a UGRID mesh"
)
elif cartesian and (src_grid.is_locstream or dst_grid.is_locstream):
raise ValueError(
"Cartesian regridding is (at the moment) not available when "
"either the source or destination grid is a DSG featureType"
)
if create_regrid_operator:
# ------------------------------------------------------------
# Create a new regrid operator
# ------------------------------------------------------------
esmpy_manager = esmpy_initialise() # noqa: F841
# Create a mask for the destination grid
dst_mask = None
grid_dst_mask = None
if use_dst_mask:
dst_mask = get_mask(dst, dst_grid)
if (
method in ("patch", "conservative_2nd", "nearest_stod")
or return_esmpy_regrid_operator
):
# For these regridding methods, the destination mask
# must be taken into account during the esmpy
# calculation of the regrid weights, rather than the
# mask being applied retrospectively to weights that
# have been calculated assuming no destination grid
# mask. See `cf.data.dask_regrid`.
grid_dst_mask = np.array(dst_mask.transpose())
dst_mask = None
# Create the destination esmpy.Grid
dst_esmpy_grid = create_esmpy_grid(dst_grid, grid_dst_mask)
del grid_dst_mask
# Create a mask for the source grid
src_mask = None
grid_src_mask = None
if use_src_mask and (
method in ("patch", "conservative_2nd", "nearest_stod")
or return_esmpy_regrid_operator
):
# For patch recovery and second-order conservative
# regridding, the source mask needs to be taken into
# account during the esmpy calculation of the regrid
# weights, rather than the mask being applied
# retrospectively to weights that have been calculated
# assuming no source grid mask. See `cf.data.dask_regrid`.
src_mask = get_mask(src, src_grid)
grid_src_mask = np.array(src_mask.transpose())
if not grid_src_mask.any():
# There are no masked source cells, so we can collapse
# the mask that gets stored in the regrid operator.
src_mask = np.array(False)
grid_src_mask = src_mask
# Create the source esmpy.Grid
src_esmpy_grid = create_esmpy_grid(src_grid, grid_src_mask)
del grid_src_mask
if is_log_level_debug(logger):
logger.debug(
f"Source ESMF Grid:\n{src_esmpy_grid}\n\nDestination ESMF Grid:\n{dst_esmpy_grid}\n"
) # pragma: no cover
esmpy_regrid_operator = [] if return_esmpy_regrid_operator else None
# Create regrid weights
weights, row, col, start_index, from_file = create_esmpy_weights(
method,
src_esmpy_grid,
dst_esmpy_grid,
src_grid=src_grid,
dst_grid=dst_grid,
ignore_degenerate=ignore_degenerate,
quarter=src_grid.dummy_size_2_dimension,
esmpy_regrid_operator=esmpy_regrid_operator,
weights_file=weights_file,
)
if return_esmpy_regrid_operator:
# Return the equivalent esmpy.Regrid operator
return esmpy_regrid_operator[-1]
# Still here? Then we've finished with esmpy, so finalise the
# esmpy manager. This is done to free up any Persistent
# Execution Threads (PETs) created by the esmpy Virtual
# Machine:
# https://earthsystemmodeling.org/esmpy_doc/release/latest/html/api.html#resource-allocation
del esmpy_manager
if src_grid.dummy_size_2_dimension:
# We have a dummy size_2 dimension, so remove its
# coordinates so that they don't end up in the regrid
# operator.
src_grid.coords.pop()
if src_grid.bounds:
src_grid.bounds.pop()
# Create regrid operator
regrid_operator = RegridOperator(
weights,
row,
col,
coord_sys=coord_sys,
method=method,
dimensionality=src_grid.dimensionality,
src_shape=src_grid.shape,
dst_shape=dst_grid.shape,
src_cyclic=src_grid.cyclic,
dst_cyclic=dst_grid.cyclic,
src_coords=src_grid.coords,
src_bounds=src_grid.bounds,
src_mask=src_mask,
dst_mask=dst_mask,
start_index=start_index,
src_axes=src_axes,
dst_axes=dst_axes,
dst=dst,
weights_file=weights_file if from_file else None,
src_mesh_location=src_grid.mesh_location,
src_featureType=src_grid.featureType,
dst_featureType=dst_grid.featureType,
src_z=src_grid.z,
dst_z=dst_grid.z,
ln_z=ln_z,
)
else:
if weights_file is not None:
raise ValueError(
"Can't provide a weights file when 'dst' is a RegridOperator"
)
# Check that the given regrid operator is compatible with the
# source field's grid
check_operator(
src, src_grid, regrid_operator, check_coordinates=check_coordinates
)
if return_operator:
# Note: The `RegridOperator.tosparse` method will also set
# 'dst_mask' to False for destination points with all
# zero weights.
regrid_operator.tosparse()
return regrid_operator
# ----------------------------------------------------------------
# Still here? Then do the regridding
# ----------------------------------------------------------------
if src_grid.n_regrid_axes == dst_grid.n_regrid_axes:
regridded_axis_sizes = {
src_iaxis: (dst_size,)
for src_iaxis, dst_size in zip(
src_grid.axis_indices, dst_grid.shape
)
}
elif src_grid.n_regrid_axes == 1:
# Fewer source grid axes than destination grid axes (e.g. mesh
# regridded to lat/lon).
regridded_axis_sizes = {src_grid.axis_indices[0]: dst_grid.shape}
elif dst_grid.n_regrid_axes == 1:
# More source grid axes than destination grid axes
# (e.g. lat/lon regridded to mesh).
src_axis_indices = sorted(src_grid.axis_indices)
regridded_axis_sizes = {src_axis_indices[0]: (dst_grid.shape[0],)}
for src_iaxis in src_axis_indices[1:]:
regridded_axis_sizes[src_iaxis] = ()
regridded_data = src.data._regrid(
method=method,
operator=regrid_operator,
regrid_axes=src_grid.axis_indices,
regridded_sizes=regridded_axis_sizes,
min_weight=min_weight,
)
# ----------------------------------------------------------------
# Update the regridded metadata
# ----------------------------------------------------------------
update_non_coordinates(src, dst, src_grid, dst_grid, regrid_operator)
update_coordinates(src, dst, src_grid, dst_grid)
# ----------------------------------------------------------------
# Insert regridded data into the new field
# ----------------------------------------------------------------
update_data(src, regridded_data, src_grid)
if coord_sys == "spherical" and dst_grid.is_grid:
# Set the cyclicity of the longitude axis of the new field
key, x = src.dimension_coordinate("X", default=(None, None), item=True)
if x is not None and x.Units.equivalent(Units("degrees")):
src.cyclic(
key, iscyclic=dst_grid.cyclic, period=360, config={"coord": x}
)
# Return the regridded source field
if inplace:
return
return src
def spherical_coords_to_domain(
dst, dst_axes=None, cyclic=None, dst_z=None, domain_class=None
):
"""Convert a sequence of `Coordinate` to spherical grid definition.
.. versionadded:: 3.14.0
:Parameters:
dst: sequence of `Coordinate`
Two 1-d dimension coordinate constructs or two 2-d
auxiliary coordinate constructs that define the spherical
latitude and longitude grid coordinates (in any order) of
the destination grid.
dst_axes: `dict` or `None`
When *d* contains 2-d latitude and longitude coordinates
then the X and Y dimensions must be identified with the
*dst_axes* dictionary, with keys ``'X'`` and ``'Y'``. The
dictionary values identify a unique domain axis by its
position in the 2-d coordinates' data arrays, i.e. the
dictionary values must be ``0`` and ``1``. Ignored if *d*
contains 1-d coordinates.
cyclic: `bool` or `None`
Specifies whether or not the destination grid longitude
axis is cyclic (i.e. the first and last cells of the axis
are adjacent). If `None` then the cyclicity will be
inferred from the coordinates, defaulting to `False` if it
can not be determined.
dst_z: optional
If `None`, the default, then it assumed that none of the
coordinate consructs in *dst* are vertical coordinates.
Otherwise identify the destination grid vertical
coordinate construct as the unique construct returned by
``d.coordinate(dst_z)``, where ``d`` is the `Domain`
returned by this function.
.. versionadded:: 3.16.2
domain_class: `Domain` class
The domain class used to create the new `Domain` instance.
:Returns:
3-`tuple`
* The new domain containing the grid
* A dictionary identifying the domain axis identifiers of
the regrid axes (as defined by the *dst_axes* parameter
of `cf.Field.regrids`)
* The value of *dst_z*. Either `None`, or replaced with
its construct identifier in the output `Domain`.
"""
if dst_z is None:
if len(dst) != 2:
raise ValueError(
"Expected a sequence of latitude and longitude "
f"coordinate constructs. Got: {dst!r}"
)
elif len(dst) != 3:
raise ValueError(
"Expected a sequence of latitude, longitude, and vertical "
f"coordinate constructs. Got: {dst!r}"
)
coords = {}
for c in dst:
try:
c = c.copy()
if c.Units.islatitude:
c.standard_name = "latitude"
coords["lat"] = c
elif c.Units.islongitude:
c.standard_name = "longitude"
coords["lon"] = c
elif dst_z is not None:
coords["Z"] = c
except AttributeError:
pass
if "lat" not in coords or "lon" not in coords:
raise ValueError(
"Expected a sequence that includes latitude and longitude "
f"coordinate constructs. Got: {dst!r}"
)
if dst_z is not None and "Z" not in coords:
raise ValueError(
"Expected a sequence that includes vertical "
f"coordinate constructs. Got: {dst!r}"
)
coords_1d = False
if coords["lat"].ndim == 1:
coords_1d = True
axis_sizes = [coords["lat"].size, coords["lon"].size]
if coords["lon"].ndim != 1:
raise ValueError(
"When 'dst' is a sequence containing latitude and "
"longitude coordinate constructs, they must have the "
f"same shape. Got: {dst!r}"
)
elif coords["lat"].ndim == 2:
message = (
"When 'dst' is a sequence containing 2-d latitude and longitude "
"coordinate constructs, 'dst_axes' must be dictionary with at "
"least the keys {'X': 0, 'Y': 1} or {'X': 1, 'Y': 0}. "
f"Got: {dst_axes!r}"
)
if dst_axes is None:
raise ValueError(message)
axis_sizes = coords["lat"].shape
if dst_axes.get("X") == 0 and dst_axes.get("Y") == 1:
axis_sizes = axis_sizes[::-1]
elif not (dst_axes.get("X") == 1 and dst_axes.get("Y") == 0):
raise ValueError(message)
if coords["lat"].shape != coords["lon"].shape:
raise ValueError(
"When 'dst' is a sequence of latitude and longitude "
f"coordinates, they must have the same shape. Got: {dst!r}"
)
elif coords["lat"].ndim > 2:
raise ValueError(
"When 'dst' is a sequence of latitude and longitude "
"coordinates, they must be either 1-d or 2-d."
)
d = domain_class()
# Set domain axes
axis_keys = []
for size in axis_sizes:
key = d.set_construct(d._DomainAxis(size), copy=False)
axis_keys.append(key)
coord_axes = []
if coords_1d:
# Set 1-d coordinates
coord_axes = []
for key, axis in zip(("lat", "lon"), axis_keys):
da_key = d.set_construct(coords[key], axes=axis, copy=False)
coord_axes.append(da_key)
if dst_axes and "X" in dst_axes and dst_axes["X"] == 0:
coord_axes = coord_axes[::-1]
else:
# Set 2-d coordinates
coord_axes = axis_keys
if dst_axes["X"] == 0:
coord_axes = coord_axes[::-1]
for coord in coords.values():
d.set_construct(coord, axes=coord_axes, copy=False)
if cyclic is not None:
# Reset X axis cyclicity
d.cyclic(axis_keys[1], iscyclic=cyclic, period=360)
dst_axes = {"Y": axis_keys[0], "X": axis_keys[1]}
if dst_z is not None:
# ------------------------------------------------------------
# Deal with Z coordinates
# ------------------------------------------------------------
z_coord = coords["Z"]
if z_coord.ndim == 1:
z_axis = d.set_construct(d._DomainAxis(z_coord.size), copy=False)
d.set_construct(z_coord, axes=z_axis, copy=False)
elif z_coord.ndim == 3:
if dst_axes is None or "Z" not in dst_axes or dst_axes["Z"] != 2:
raise ValueError(
"When 'dst' is a sequence containing a 3-d vertical "
"coordinate construct, 'dst_axes' must be either "
"{'X': 0, 'Y': 1, 'Z': 2} or {'X': 1, 'Y': 0, 'Z': 2}. "
f"Got: {dst_axes!r}"
)
z_axis = d.set_construct(
d._DomainAxis(z_coord.shape[2]), copy=False
)
z_key = d.set_construct(
z_coord, axes=coord_axes + (z_axis,), copy=False
)
# Check that z_coord is indeed a vertical coordinate
# construct, and replace 'dst_z' with its construct
# identifier.
key = d.coordinate(dst_z, key=True, default=None)
if key != z_key:
raise ValueError(
f"Could not find destination {dst_z!r} vertical coordinates"
)
dst_z = key
dst_axes["Z"] = z_axis
return d, dst_axes, dst_z
def Cartesian_coords_to_domain(dst, dst_z=None, domain_class=None):
"""Convert a sequence of `Coordinate` to Cartesian grid definition.
.. versionadded:: 3.14.0
:Parameters:
dst: sequence of `DimensionCoordinate`
Between one and three 1-d dimension coordinate constructs
that define the coordinates of the grid. The order of the
coordinate constructs **must** match the order of source
field regridding axes defined elsewhere by the *src_axes*
or *axes* parameter.
dst_z: optional
If `None`, the default, then it assumed that none of the
coordinate consructs in *dst* are vertical coordinates.
Otherwise identify the destination grid vertical
coordinate construct as the unique construct returned by
``d.coordinate(dst_z)``, where ``d`` is the `Domain`
returned by this function.
.. versionadded:: 3.16.2
domain_class: `Domain` class
The domain class used to create the new `Domain` instance.
:Returns:
3-`tuple`
* The new domain containing the grid
* A list identifying the domain axis identifiers of the
regrid axes (as defined by the *dst_axes* parameter of
`cf.Field.regridc`)
* The value of *dst_z*. Either `None`, or replaced with
its construct identifier in the output `Domain`.
"""
d = domain_class()
axis_keys = []
for coord in dst:
axis = d.set_construct(d._DomainAxis(coord.size), copy=False)
d.set_construct(coord, axes=axis, copy=True)
axis_keys.append(axis)
if dst_z is not None:
# Check that there are vertical coordinates, and replace
# 'dst_z' with the identifier of its domain axis construct.
z_key = d.coordinate(dst_z, key=True, default=None)
if z_key is None:
raise ValueError(
f"Could not find destination {dst_z!r} vertical coordinates"
)