-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path_regrid.py
More file actions
1573 lines (1335 loc) · 50.8 KB
/
Copy path_regrid.py
File metadata and controls
1573 lines (1335 loc) · 50.8 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
"""Horizontal and vertical regridding module."""
from __future__ import annotations
import functools
import importlib
import inspect
import logging
import os
import re
import ssl
from copy import deepcopy
from decimal import Decimal
from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal
import cordex as cx
import dask.array as da
import iris
import iris.coords
import ncdata.iris_xarray
import numpy as np
import stratify
import xarray as xr
from geopy.geocoders import Nominatim
from iris.analysis import (
AreaWeighted,
Linear,
Nearest,
)
from iris.coord_systems import RotatedGeogCS
from iris.cube import Cube
from iris.util import broadcast_to_shape
import esmvalcore.cmor.table
from esmvalcore.cmor._fixes.shared import (
add_altitude_from_plev,
add_plev_from_altitude,
)
from esmvalcore.iris_helpers import has_irregular_grid, has_unstructured_grid
from esmvalcore.preprocessor._shared import (
_rechunk_aux_factory_dependencies,
get_array_module,
get_dims_along_axes,
preserve_float_dtype,
)
from esmvalcore.preprocessor._supplementary_vars import (
add_ancillary_variable,
add_cell_measure,
)
from esmvalcore.preprocessor.regrid_schemes import (
GenericFuncScheme,
IrisESMFRegrid,
UnstructuredLinear,
UnstructuredNearest,
)
if TYPE_CHECKING:
from collections.abc import Iterable
from iris.analysis import Regridder, RegriddingScheme
from numpy.typing import ArrayLike
from esmvalcore.dataset import Dataset
logger = logging.getLogger(__name__)
# Regular expression to parse a "MxN" cell-specification.
_CELL_SPEC = re.compile(
r"""\A
\s*(?P<dlon>\d+(\.\d+)?)\s*
x
\s*(?P<dlat>\d+(\.\d+)?)\s*
\Z
""",
re.IGNORECASE | re.VERBOSE,
)
# Default fill-value.
_MDI = 1e20
# Stock cube - global grid extents (degrees).
_LAT_MIN = -90.0
_LAT_MAX = 90.0
_LAT_RANGE = _LAT_MAX - _LAT_MIN
_LON_MIN = 0.0
_LON_MAX = 360.0
_LON_RANGE = _LON_MAX - _LON_MIN
NamedPointInterpolationScheme = Literal[
"linear",
"nearest",
]
# Supported point interpolation schemes.
POINT_INTERPOLATION_SCHEMES = {
"linear": Linear(extrapolation_mode="mask"),
"nearest": Nearest(extrapolation_mode="mask"),
}
NamedHorizontalScheme = Literal[
"area_weighted",
"linear",
"nearest",
]
# Supported horizontal regridding schemes for regular grids (= rectilinear
# grids; i.e., grids that can be described with 1D latitude and 1D longitude
# coordinates orthogonal to each other)
HORIZONTAL_SCHEMES_REGULAR = {
"area_weighted": AreaWeighted(),
"linear": Linear(extrapolation_mode="mask"),
"nearest": Nearest(extrapolation_mode="mask"),
}
# Supported horizontal regridding schemes for irregular grids (= general
# curvilinear grids; i.e., grids that can be described with 2D latitude and 2D
# longitude coordinates with common dimensions)
HORIZONTAL_SCHEMES_IRREGULAR = {
"area_weighted": IrisESMFRegrid(method="conservative"),
"linear": IrisESMFRegrid(method="bilinear"),
"nearest": IrisESMFRegrid(method="nearest"),
}
# Supported horizontal regridding schemes for meshes
# https://scitools-iris.readthedocs.io/en/stable/further_topics/ugrid/index.html
HORIZONTAL_SCHEMES_MESH = {
"area_weighted": IrisESMFRegrid(method="conservative"),
"linear": IrisESMFRegrid(method="bilinear"),
"nearest": IrisESMFRegrid(method="nearest"),
}
# Supported horizontal regridding schemes for unstructured grids (i.e., grids,
# that can be described with 1D latitude and 1D longitude coordinate with
# common dimensions)
HORIZONTAL_SCHEMES_UNSTRUCTURED = {
"linear": UnstructuredLinear(),
"nearest": UnstructuredNearest(),
}
NamedVerticalScheme = Literal[
"linear",
"nearest",
"linear_extrapolate",
"nearest_extrapolate",
]
# Supported vertical interpolation schemes.
VERTICAL_SCHEMES: tuple[NamedVerticalScheme, ...] = (
"linear",
"nearest",
"linear_extrapolate",
"nearest_extrapolate",
)
def parse_cell_spec(spec: str) -> tuple[float, float]:
"""Parse an MxN cell specification string.
Parameters
----------
spec:
``MxN`` degree cell-specification for the global grid.
Returns
-------
tuple
tuple of (float, float) of parsed (lon, lat)
Raises
------
ValueError
if the MxN cell specification is malformed.
ValueError
invalid longitude and latitude delta in cell specification.
"""
cell_match = _CELL_SPEC.match(spec)
if cell_match is None:
emsg = "Invalid MxN cell specification for grid, got {!r}."
raise ValueError(emsg.format(spec))
cell_group = cell_match.groupdict()
dlon = float(cell_group["dlon"])
dlat = float(cell_group["dlat"])
if (np.trunc(_LON_RANGE / dlon) * dlon) != _LON_RANGE:
emsg = (
"Invalid longitude delta in MxN cell specification "
"for grid, got {!r}."
)
raise ValueError(emsg.format(dlon))
if (np.trunc(_LAT_RANGE / dlat) * dlat) != _LAT_RANGE:
emsg = (
"Invalid latitude delta in MxN cell specification "
"for grid, got {!r}."
)
raise ValueError(emsg.format(dlat))
return dlon, dlat
def is_cordex_domain(spec: str) -> bool:
"""Return ``True`` if ``spec`` is a known CORDEX domain name.
Parameters
----------
spec:
Candidate CORDEX domain identifier (e.g. ``EUR-11``).
Returns
-------
bool
Whether ``spec`` is recognised by :mod:`cordex`.
"""
try:
cx.domain_info(spec)
except KeyError:
return False
return True
@functools.lru_cache
def _cordex_stock_cube(domain_name: str) -> Cube:
"""Create a stock cube for a CORDEX domain target grid.
Parameters
----------
domain_name:
CORDEX domain identifier (e.g. ``EUR-11``).
Returns
-------
iris.cube.Cube
Dummy cube with rotated-pole dimension coordinates and geographical
auxiliary coordinates matching the official domain specification.
"""
domain = cx.cordex_domain(domain_name, bounds=True)
domain_info = cx.domain_info(domain_name)
data = xr.DataArray(
np.zeros((domain.sizes["rlat"], domain.sizes["rlon"]), dtype=np.int32),
dims=["rlat", "rlon"],
coords={
"rlat": domain["rlat"],
"rlon": domain["rlon"],
"lat": domain["lat"],
"lon": domain["lon"],
},
name="grid",
)
(cube,) = ncdata.iris_xarray.cubes_from_xarray(data.to_dataset())
coord_system = RotatedGeogCS(
grid_north_pole_latitude=domain_info["pollat"],
grid_north_pole_longitude=domain_info["pollon"],
)
for dim_coord in ("rlat", "rlon"):
coord = cube.coord(var_name=dim_coord)
coord.coord_system = coord_system
if not coord.has_bounds():
coord.guess_bounds()
for aux_coord in ("lat", "lon"):
coord = cube.coord(var_name=aux_coord)
coord.bounds = domain[f"{aux_coord}_vertices"].data
return cube
def _generate_cube_from_dimcoords(
latdata: np.ndarray | da.Array,
londata: np.ndarray | da.Array,
circular: bool = False,
) -> Cube:
"""Generate cube from lat/lon points.
Parameters
----------
latdata:
List of latitudes.
londata:
List of longitudes.
circular
Wrap longitudes around the full great circle. Bounds will not be
generated for circular coordinates.
Returns
-------
iris.cube.Cube
"""
lats = iris.coords.DimCoord(
latdata,
standard_name="latitude",
units="degrees_north",
var_name="lat",
circular=circular,
)
lons = iris.coords.DimCoord(
londata,
standard_name="longitude",
units="degrees_east",
var_name="lon",
circular=circular,
)
if not circular:
# cannot guess bounds for wrapped coordinates
lats.guess_bounds()
lons.guess_bounds()
# Construct the resultant stock cube, with dummy data.
shape = (latdata.size, londata.size)
dummy = np.empty(shape, dtype=np.int32)
coords_spec = [(lats, 0), (lons, 1)]
return Cube(dummy, dim_coords_and_dims=coords_spec)
@functools.lru_cache
def _global_stock_cube(
spec: str,
lat_offset: bool = True,
lon_offset: bool = True,
) -> Cube:
"""Create a stock cube.
Create a global cube with M degree-east by N degree-north regular grid
cells.
The longitude range is from 0 to 360 degrees. The latitude range is from
-90 to 90 degrees. Each cell grid point is calculated as the mid-point of
the associated MxN cell.
Parameters
----------
spec
Specifies the 'MxN' degree cell-specification for the global grid.
lat_offset
Offset the grid centers of the latitude coordinate w.r.t. the
pole by half a grid step. This argument is ignored if `target_grid`
is a cube or file.
lon_offset
Offset the grid centers of the longitude coordinate w.r.t. Greenwich
meridian by half a grid step.
This argument is ignored if `target_grid` is a cube or file.
Returns
-------
iris.cube.Cube
"""
dlon, dlat = parse_cell_spec(spec)
mid_dlon, mid_dlat = dlon / 2, dlat / 2
# Construct the latitude coordinate, with bounds.
if lat_offset:
latdata = np.linspace(
_LAT_MIN + mid_dlat,
_LAT_MAX - mid_dlat,
int(_LAT_RANGE / dlat),
)
else:
latdata = np.linspace(_LAT_MIN, _LAT_MAX, int(_LAT_RANGE / dlat) + 1)
# Construct the longitude coordinat, with bounds.
if lon_offset:
londata = np.linspace(
_LON_MIN + mid_dlon,
_LON_MAX - mid_dlon,
int(_LON_RANGE / dlon),
)
else:
londata = np.linspace(
_LON_MIN,
_LON_MAX - dlon,
int(_LON_RANGE / dlon),
)
return _generate_cube_from_dimcoords(latdata=latdata, londata=londata)
def _spec_to_latlonvals(
*,
start_latitude: float,
end_latitude: float,
step_latitude: float,
start_longitude: float,
end_longitude: float,
step_longitude: float,
) -> tuple[np.ndarray, np.ndarray]:
"""Define lat/lon values from spec.
Create a regional cube starting defined by the target specification.
The latitude must be between -90 and +90. The longitude is not bounded, but
wraps around the full great circle.
Parameters
----------
start_latitude:
Latitude value of the first grid cell center (start point). The grid
includes this value.
end_latitude:
Latitude value of the last grid cell center (end point). The grid
includes this value only if it falls on a grid point. Otherwise, it
cuts off at the previous value.
step_latitude:
Latitude distance between the centers of two neighbouring cells.
start_longitude:
Latitude value of the first grid cell center (start point). The grid
includes this value.
end_longitude:
Longitude value of the last grid cell center (end point). The grid
includes this value only if it falls on a grid point. Otherwise, it
cuts off at the previous value.
step_longitude:
Longitude distance between the centers of two neighbouring cells.
Returns
-------
tuple[np.ndarray, np.ndarray]
Longitudes, Latitudes.
"""
if step_latitude == 0:
msg = f"Latitude step cannot be 0, got step_latitude={step_latitude}."
raise ValueError(msg)
if step_longitude == 0:
msg = (
f"Longitude step cannot be 0, got step_longitude={step_longitude}."
)
raise ValueError(msg)
if (start_latitude < _LAT_MIN) or (end_latitude > _LAT_MAX):
msg = (
f"Latitude values must lie between {_LAT_MIN}:{_LAT_MAX}, "
f"got start_latitude={start_latitude}:end_latitude={end_latitude}."
)
raise ValueError(msg)
def get_points(start, stop, step):
"""Calculate grid points."""
# use Decimal to avoid floating point errors
num = int(Decimal(stop - start) // Decimal(str(step)))
stop = start + num * step
return np.linspace(start, stop, num + 1)
latitudes = get_points(start_latitude, end_latitude, step_latitude)
longitudes = get_points(start_longitude, end_longitude, step_longitude)
return latitudes, longitudes
def _regional_stock_cube(spec: dict[str, Any]) -> Cube:
"""Create a regional stock cube.
Returns
-------
iris.cube.Cube
"""
latdata, londata = _spec_to_latlonvals(**spec)
cube = _generate_cube_from_dimcoords(
latdata=latdata,
londata=londata,
circular=True,
)
def add_bounds_from_step(
coord: iris.coords.DimCoord | iris.coords.AuxCoord,
step: float,
) -> None:
"""Calculate bounds from the given step."""
bound = step / 2
points = coord.points
coord.bounds = np.vstack((points - bound, points + bound)).T
add_bounds_from_step(cube.coord("latitude"), spec["step_latitude"])
add_bounds_from_step(cube.coord("longitude"), spec["step_longitude"])
return cube
def extract_location(
cube: Cube,
location: str,
scheme: NamedPointInterpolationScheme,
) -> Cube:
"""Extract a point using a location name, with interpolation.
Extracts a single location point from a cube, according
to the interpolation scheme ``scheme``.
The function just retrieves the coordinates of the location and then calls
the ``extract_point`` preprocessor.
It can be used to locate cities and villages, but also mountains or other
geographical locations.
Note
----
The geolocator needs a working internet connection.
Parameters
----------
cube:
The source cube to extract a point from.
location:
The reference location. Examples: 'mount everest',
'romania','new york, usa'
scheme:
The interpolation scheme. 'linear' or 'nearest'. No default.
Returns
-------
iris.cube.Cube
Returns a cube with the extracted point, and with adjusted latitude and
longitude coordinates.
Raises
------
ValueError:
If location is not supplied as a preprocessor parameter.
ValueError:
If scheme is not supplied as a preprocessor parameter.
ValueError:
If given location cannot be found by the geolocator.
"""
if location is None:
msg = (
"Location needs to be specified."
" Examples: 'mount everest', 'romania',"
" 'new york, usa'"
)
raise ValueError(msg)
if scheme is None:
msg = (
"Interpolation scheme needs to be specified."
" Use either 'linear' or 'nearest'."
)
raise ValueError(msg)
try:
# Try to use the default SSL context, see
# https://github.com/ESMValGroup/ESMValCore/issues/2012 for more
# information.
ssl_context = ssl.create_default_context()
geolocator = Nominatim(
user_agent="esmvalcore",
ssl_context=ssl_context,
)
except ssl.SSLError:
logger.warning(
"ssl.create_default_context() encountered a problem, not using it.",
)
geolocator = Nominatim(user_agent="esmvalcore")
geolocation = geolocator.geocode(location)
if geolocation is None:
msg = f"Requested location {location} can not be found."
raise ValueError(msg)
logger.info(
"Extracting data for %s (%s °N, %s °E)",
geolocation,
geolocation.latitude,
geolocation.longitude,
)
return extract_point(
cube,
geolocation.latitude,
geolocation.longitude,
scheme,
)
def extract_point(
cube: Cube,
latitude: ArrayLike,
longitude: ArrayLike,
scheme: NamedPointInterpolationScheme,
) -> Cube:
"""Extract a point, with interpolation.
Extracts a single latitude/longitude point from a cube, according
to the interpolation scheme `scheme`.
Multiple points can also be extracted, by supplying an array of
latitude and/or longitude coordinates. The resulting point cube
will match the respective latitude and longitude coordinate to
those of the input coordinates. If the input coordinate is a
scalar, the dimension will be missing in the output cube (that is,
it will be a scalar).
If the point to be extracted has at least one of the coordinate point
values outside the interval of the cube's same coordinate values, then
no extrapolation will be performed, and the resulting extracted cube
will have fully masked data.
Parameters
----------
cube:
The source cube to extract a point from.
latitude:
The latitude of the point.
longitude:
The longitude of the point.
scheme:
The interpolation scheme. 'linear' or 'nearest'. No default.
Returns
-------
iris.cube.Cube
Returns a cube with the extracted point(s), and with adjusted
latitude and longitude coordinates (see above). If desired point
outside values for at least one coordinate, this cube will have fully
masked data.
Raises
------
ValueError:
If the interpolation scheme is None or unrecognized.
Examples
--------
With a cube that has the coordinates
- latitude: [1, 2, 3, 4]
- longitude: [1, 2, 3, 4]
- data values: [[[1, 2, 3, 4], [5, 6, ...], [...], [...],
... ]]]
>>> point = extract_point(cube, 2.5, 2.5, 'linear') # doctest: +SKIP
>>> point.data # doctest: +SKIP
array([ 8.5, 24.5, 40.5, 56.5])
Extraction of multiple points at once, with a nearest matching scheme.
The values for 0.1 will result in masked values, since this lies outside
the cube grid.
>>> point = extract_point(cube, [1.4, 2.1], [0.1, 1.1],
... 'nearest') # doctest: +SKIP
>>> point.data.shape # doctest: +SKIP
(4, 2, 2)
>>> # x, y, z indices of masked values
>>> np.where(~point.data.mask) # doctest: +SKIP
(array([0, 0, 1, 1, 2, 2, 3, 3]), array([0, 1, 0, 1, 0, 1, 0, 1]),
array([1, 1, 1, 1, 1, 1, 1, 1]))
>>> point.data[~point.data.mask].data # doctest: +SKIP
array([ 1, 5, 17, 21, 33, 37, 49, 53])
"""
msg = f"Unknown interpolation scheme, got {scheme!r}."
loaded_scheme = POINT_INTERPOLATION_SCHEMES.get(scheme.lower())
if not loaded_scheme:
raise ValueError(msg)
point = [("latitude", latitude), ("longitude", longitude)]
return cube.interpolate(point, scheme=loaded_scheme)
def is_dataset(
dataset: Any, # noqa: ANN401
) -> bool:
"""Test if something is an `esmvalcore.dataset.Dataset`."""
# Use this function to avoid circular imports
return hasattr(dataset, "facets")
def _get_target_grid_cube(
cube: Cube,
target_grid: Cube | Dataset | Path | str | dict,
lat_offset: bool = True,
lon_offset: bool = True,
) -> Cube:
"""Get target grid cube."""
if is_dataset(target_grid):
target_grid = target_grid.copy() # type: ignore
target_grid.supplementaries.clear() # type: ignore
target_grid.files = [target_grid.files[0]] # type: ignore
target_grid_cube = target_grid.load() # type: ignore
elif isinstance(target_grid, (str, Path)) and os.path.isfile(target_grid):
target_grid_cube = iris.load_cube(target_grid)
elif isinstance(target_grid, str):
if is_cordex_domain(target_grid):
target_grid_cube = _cordex_stock_cube(target_grid)
else:
# Generate a target grid from the provided cell-specification
target_grid_cube = _global_stock_cube(
target_grid,
lat_offset,
lon_offset,
)
# Align the target grid coordinate system to the source
# coordinate system.
src_cs = cube.coord_system()
xcoord = target_grid_cube.coord(axis="x", dim_coords=True)
ycoord = target_grid_cube.coord(axis="y", dim_coords=True)
xcoord.coord_system = src_cs
ycoord.coord_system = src_cs
elif isinstance(target_grid, dict):
# Generate a target grid from the provided specification,
target_grid_cube = _regional_stock_cube(target_grid)
else:
target_grid_cube = target_grid
if not isinstance(target_grid_cube, Cube):
msg = f"Expecting a cube, got {target_grid}."
raise TypeError(msg)
return target_grid_cube
def _load_scheme(
src_cube: Cube,
tgt_cube: Cube,
scheme: NamedHorizontalScheme | dict[str, Any],
) -> RegriddingScheme:
"""Return scheme that can be used in :meth:`iris.cube.Cube.regrid`."""
loaded_scheme: Any = None
if isinstance(scheme, dict):
# Scheme is a dict -> assume this describes a generic regridding scheme
loaded_scheme = _load_generic_scheme(scheme)
else:
# Scheme is a str -> load appropriate regridding scheme depending on
# the type of input data
if has_irregular_grid(src_cube) or has_irregular_grid(tgt_cube):
grid_type = "irregular"
elif src_cube.mesh is not None or tgt_cube.mesh is not None:
grid_type = "mesh"
elif has_unstructured_grid(src_cube):
grid_type = "unstructured"
else:
grid_type = "regular"
schemes = globals()[f"HORIZONTAL_SCHEMES_{grid_type.upper()}"]
if scheme not in schemes:
msg = (
f"Regridding scheme '{scheme}' not available for {grid_type} "
f"data, expected one of: {', '.join(schemes)}"
)
raise ValueError(msg)
loaded_scheme = schemes[scheme]
logger.debug("Loaded regridding scheme %s", loaded_scheme)
return loaded_scheme
def _load_generic_scheme(scheme: dict[str, Any]) -> RegriddingScheme:
"""Load generic regridding scheme."""
scheme = dict(scheme) # do not overwrite original scheme
try:
object_ref = scheme.pop("reference")
except KeyError as key_err:
msg = "No reference specified for generic regridding."
raise ValueError(msg) from key_err
module_name, separator, scheme_name = object_ref.partition(":")
try:
obj: Any = importlib.import_module(module_name)
except ImportError as import_err:
msg = (
f"Could not import specified generic regridding module "
f"'{module_name}'. Please double check spelling and that the "
f"required module is installed."
)
raise ValueError(msg) from import_err
if separator:
for attr in scheme_name.split("."):
obj = getattr(obj, attr)
# If `obj` is a function that requires `src_cube` and `grid_cube`, use
# GenericFuncScheme
scheme_args = inspect.getfullargspec(obj).args
if "src_cube" in scheme_args and "grid_cube" in scheme_args:
loaded_scheme = GenericFuncScheme(obj, **scheme)
else:
loaded_scheme = obj(**scheme)
return loaded_scheme
_CACHED_REGRIDDERS: dict[tuple, dict] = {}
def _get_regridder(
src_cube: Cube,
tgt_cube: Cube,
scheme: NamedHorizontalScheme | dict,
cache_weights: bool,
) -> Regridder:
"""Get regridder to actually perform regridding.
Note
----
If possible, this uses an existing regridder to reduce runtime (see also
https://scitools-iris.readthedocs.io/en/latest/userguide/
interpolation_and_regridding.html#caching-a-regridder.)
"""
# (1) Weights caching enabled
if cache_weights:
# To search for a matching regridder in the cache, first check the
# regridding scheme name and shapes of source and target coordinates.
# Only if these match, check coordinates themselves (this is much more
# expensive).
coord_key = _get_coord_key(src_cube, tgt_cube)
name_shape_key = _get_name_and_shape_key(src_cube, tgt_cube, scheme)
if name_shape_key in _CACHED_REGRIDDERS:
# We cannot simply do a test for `coord_key in
# _CACHED_REGRIDDERS[shape_key]` below since the hash() of a
# coordinate is simply its id() (thus, coordinates loaded from two
# different files would never be considered equal)
for key, regridder in _CACHED_REGRIDDERS[name_shape_key].items():
if key == coord_key:
return regridder
# Regridder is not in cached -> return a new one and cache it
loaded_scheme = _load_scheme(src_cube, tgt_cube, scheme)
regridder = loaded_scheme.regridder(src_cube, tgt_cube)
_CACHED_REGRIDDERS.setdefault(name_shape_key, {})
_CACHED_REGRIDDERS[name_shape_key][coord_key] = regridder
# (2) Weights caching disabled
else:
loaded_scheme = _load_scheme(src_cube, tgt_cube, scheme)
regridder = loaded_scheme.regridder(src_cube, tgt_cube)
return regridder
def _get_coord_key(
src_cube: Cube,
tgt_cube: Cube,
) -> tuple[iris.coords.DimCoord | iris.coords.AuxCoord, ...]:
"""Get dict key from coordinates."""
src_lat = src_cube.coord("latitude")
src_lon = src_cube.coord("longitude")
tgt_lat = tgt_cube.coord("latitude")
tgt_lon = tgt_cube.coord("longitude")
return (src_lat, src_lon, tgt_lat, tgt_lon)
def _get_name_and_shape_key(
src_cube: Cube,
tgt_cube: Cube,
scheme: NamedHorizontalScheme | dict,
) -> tuple[str, tuple[int, ...]]:
"""Get dict key from scheme name and coordinate shapes."""
name = str(scheme)
shapes = [c.shape for c in _get_coord_key(src_cube, tgt_cube)]
return (name, *shapes)
@preserve_float_dtype
def regrid(
cube: Cube,
target_grid: Cube | Dataset | Path | str | dict,
scheme: NamedHorizontalScheme | dict,
lat_offset: bool = True,
lon_offset: bool = True,
cache_weights: bool = False,
use_src_coords: Iterable[str] = ("latitude", "longitude"),
) -> Cube:
"""Perform horizontal regridding.
Note that the target grid can be a :class:`~iris.cube.Cube`, a
:class:`~esmvalcore.dataset.Dataset`, a path to a cube
(:class:`~pathlib.Path` or :obj:`str`), a grid spec (:obj:`str`) in the
form of `MxN`, or a :obj:`dict` specifying the target grid.
For the latter, the `target_grid` should be a :obj:`dict` with the
following keys:
- ``start_longitude``: longitude at the center of the first grid cell.
- ``end_longitude``: longitude at the center of the last grid cell.
- ``step_longitude``: constant longitude distance between grid cell
centers.
- ``start_latitude``: latitude at the center of the first grid cell.
- ``end_latitude``: longitude at the center of the last grid cell.
- ``step_latitude``: constant latitude distance between grid cell centers.
Parameters
----------
cube:
The source cube to be regridded.
target_grid:
The (location of a) cube that specifies the target or reference grid
for the regridding operation.
Alternatively, a :class:`~esmvalcore.dataset.Dataset` can be provided.
Alternatively, a string cell specification may be provided,
of the form ``MxN``, which specifies the extent of the cell, longitude
by latitude (degrees) for a global, regular target grid.
Alternatively, a dictionary with a regional target grid may
be specified (see above).
scheme:
The regridding scheme to perform. If the source grid is structured
(i.e., rectilinear or curvilinear), can be one of the built-in schemes
``linear``, ``nearest``, ``area_weighted``. If the source grid is
unstructured, can be one of the built-in schemes ``linear``,
``nearest``. Alternatively, a `dict` that specifies generic regridding
can be given (see below).
lat_offset:
Offset the grid centers of the latitude coordinate w.r.t. the pole by
half a grid step. This argument is ignored if `target_grid` is a cube
or file.
lon_offset:
Offset the grid centers of the longitude coordinate w.r.t. Greenwich
meridian by half a grid step. This argument is ignored if
`target_grid` is a cube or file.
cache_weights:
If ``True``, cache regridding weights for later usage. This can speed
up the regridding of different datasets with similar source and target
grids massively, but may take up a lot of memory for extremely
high-resolution data. This option is ignored for schemes that do not
support weights caching. More details on this are given in the section
on :ref:`caching_regridding_weights`. To clear the cache, use
:func:`esmvalcore.preprocessor.regrid.cache_clear`.
use_src_coords:
If there are multiple horizontal coordinates available in the source
cube, only use horizontal coordinates with these standard names.
Returns
-------
iris.cube.Cube
Regridded cube.
See Also
--------
extract_levels: Perform vertical regridding.
Notes
-----
This preprocessor allows for the use of arbitrary :doc:`Iris <iris:index>`
regridding schemes, that is anything that can be passed as a scheme to
:meth:`iris.cube.Cube.regrid` is possible. This enables the use of further
parameters for existing schemes, as well as the use of more advanced
schemes for example for unstructured grids.
To use this functionality, a dictionary must be passed for the scheme with
a mandatory entry of ``reference`` in the form specified for the object
reference of the `entry point data model <https://packaging.python.org/en/
latest/specifications/entry-points/#data-model>`_,
i.e. ``importable.module:object.attr``. This is used as a factory for the
scheme. Any further entries in the dictionary are passed as keyword
arguments to the factory.
For example, to use the familiar :class:`iris.analysis.Linear` regridding
scheme with a custom extrapolation mode, use
.. code-block:: yaml
my_preprocessor:
regrid:
target: 1x1
scheme:
reference: iris.analysis:Linear
extrapolation_mode: nanmask
To use the area weighted regridder available in
:class:`esmf_regrid.schemes.ESMFAreaWeighted` use
.. code-block:: yaml
my_preprocessor:
regrid:
target: 1x1
scheme:
reference: esmf_regrid.schemes:ESMFAreaWeighted
"""
# Remove unwanted coordinates from the source cube.
cube = cube.copy()
use_src_coords = set(use_src_coords)
for axis in ("X", "Y"):
coords = cube.coords(axis=axis)
if len(coords) > 1:
for coord in coords:
if coord.standard_name not in use_src_coords:
cube.remove_coord(coord)
target_grid_cube = _get_target_grid_cube(
cube,
target_grid,
lat_offset=lat_offset,
lon_offset=lon_offset,
)
# Horizontal grids from source and target (almost) match
# -> Return source cube with target coordinates
if cube.coords("latitude") and cube.coords("longitude"):
if _horizontal_grid_is_close(cube, target_grid_cube):
for coord in ["latitude", "longitude"]:
is_dim_coord = cube.coords(coord, dim_coords=True)
coord_dims = cube.coord_dims(coord)
cube.remove_coord(coord)
target_coord = target_grid_cube.coord(coord).copy()
if is_dim_coord:
cube.add_dim_coord(target_coord, coord_dims)
else:
cube.add_aux_coord(target_coord, coord_dims)
return cube