/
frontend.py
1372 lines (1130 loc) · 52.6 KB
/
frontend.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
"""
Frontend for xESMF, exposed to users.
"""
import warnings
import cf_xarray as cfxr
import numpy as np
import sparse as sps
import xarray as xr
from shapely.geometry import LineString
from xarray import DataArray, Dataset
from .backend import Grid, LocStream, Mesh, add_corner, esmf_regrid_build, esmf_regrid_finalize
from .smm import (
_combine_weight_multipoly,
_parse_coords_and_values,
add_nans_to_weights,
apply_weights,
check_shapes,
read_weights,
)
from .util import LAT_CF_ATTRS, LON_CF_ATTRS, split_polygons_and_holes
try:
import dask.array as da
dask_array_type = (da.Array,) # for isinstance checks
except ImportError:
dask_array_type = ()
def subset_regridder(
ds_out, ds_in, method, in_dims, out_dims, locstream_in, locstream_out, periodic, **kwargs
):
"""Compute subset of weights"""
kwargs.pop('filename', None) # Don't save subset of weights
kwargs.pop('reuse_weights', None)
# Renaming dims to original names for the subset regridding
if locstream_in:
ds_in = ds_in.rename({'x_in': in_dims[0]})
else:
ds_in = ds_in.rename({'y_in': in_dims[0], 'x_in': in_dims[1]})
if locstream_out:
ds_out = ds_out.rename({'x_out': out_dims[1]})
else:
ds_out = ds_out.rename({'y_out': out_dims[0], 'x_out': out_dims[1]})
regridder = Regridder(
ds_in, ds_out, method, locstream_in, locstream_out, periodic, parallel=False, **kwargs
)
return regridder.w
def as_2d_mesh(lon, lat):
if (lon.ndim, lat.ndim) == (2, 2):
assert lon.shape == lat.shape, 'lon and lat should have same shape'
elif (lon.ndim, lat.ndim) == (1, 1):
lon, lat = np.meshgrid(lon, lat)
else:
raise ValueError('lon and lat should be both 1D or 2D')
return lon, lat
def _get_lon_lat(ds):
"""Return lon and lat extracted from ds."""
if ('lat' in ds and 'lon' in ds) or ('lat' in ds.coords and 'lon' in ds.coords):
# Old way.
return ds['lon'], ds['lat']
# else : cf-xarray way
try:
lon = ds.cf['longitude']
lat = ds.cf['latitude']
except (KeyError, AttributeError, ValueError):
# KeyError if cfxr doesn't detect the coords
# AttributeError if ds is a dict
raise ValueError('dataset must include lon/lat or be CF-compliant')
return lon, lat
def _get_lon_lat_bounds(ds):
"""Return bounds of lon and lat extracted from ds."""
if 'lat_b' in ds and 'lon_b' in ds:
# Old way.
return ds['lon_b'], ds['lat_b']
# else : cf-xarray way
if 'longitude' not in ds.cf.coordinates:
# If we are here, _get_lon_lat() didn't fail, thus we should be able to guess the coords.
ds = ds.cf.guess_coord_axis()
try:
lon_bnds = ds.cf.get_bounds('longitude')
lat_bnds = ds.cf.get_bounds('latitude')
except KeyError: # bounds are not already present
if ds.cf['longitude'].ndim > 1:
# We cannot infer 2D bounds, raise KeyError as custom "lon_b" is missing.
raise KeyError('lon_b')
lon_name = ds.cf['longitude'].name
lat_name = ds.cf['latitude'].name
ds = ds.cf.add_bounds([lon_name, lat_name])
lon_bnds = ds.cf.get_bounds('longitude')
lat_bnds = ds.cf.get_bounds('latitude')
# Convert from CF bounds to xESMF bounds.
# order=None is because we don't want to assume the dimension order for 2D bounds.
lon_b = cfxr.bounds_to_vertices(lon_bnds, ds.cf.get_bounds_dim_name('longitude'), order=None)
lat_b = cfxr.bounds_to_vertices(lat_bnds, ds.cf.get_bounds_dim_name('latitude'), order=None)
return lon_b, lat_b
def ds_to_ESMFgrid(ds, need_bounds=False, periodic=None, append=None):
"""
Convert xarray DataSet or dictionary to ESMF.Grid object.
Parameters
----------
ds : xarray DataSet or dictionary
Contains variables ``lon``, ``lat``,
and optionally ``lon_b``, ``lat_b`` if need_bounds=True.
Shape should be ``(n_lat, n_lon)`` or ``(n_y, n_x)``,
as normal C or Python ordering. Will be then tranposed to F-ordered.
need_bounds : bool, optional
Need cell boundary values?
periodic : bool, optional
Periodic in longitude?
Returns
-------
grid
ESMF.Grid object
shape
Shape of the grid
dim_names
Dimension names of the grid
"""
# use np.asarray(dr) instead of dr.values, so it also works for dictionary
lon, lat = _get_lon_lat(ds)
if hasattr(lon, 'dims'):
if lon.ndim == 1:
dim_names = lat.dims + lon.dims
else:
dim_names = lon.dims
else:
dim_names = None
lon, lat = as_2d_mesh(np.asarray(lon), np.asarray(lat))
if 'mask' in ds:
mask = np.asarray(ds['mask'])
else:
mask = None
# tranpose the arrays so they become Fortran-ordered
if mask is not None:
grid = Grid.from_xarray(lon.T, lat.T, periodic=periodic, mask=mask.T)
else:
grid = Grid.from_xarray(lon.T, lat.T, periodic=periodic, mask=None)
if need_bounds:
lon_b, lat_b = _get_lon_lat_bounds(ds)
lon_b, lat_b = as_2d_mesh(np.asarray(lon_b), np.asarray(lat_b))
add_corner(grid, lon_b.T, lat_b.T)
return grid, lon.shape, dim_names
def ds_to_ESMFlocstream(ds):
"""
Convert xarray DataSet or dictionary to ESMF.LocStream object.
Parameters
----------
ds : xarray DataSet or dictionary
Contains variables ``lon``, ``lat``.
Returns
-------
locstream : ESMF.LocStream object
"""
lon, lat = _get_lon_lat(ds)
if hasattr(lon, 'dims'):
dim_names = lon.dims
else:
dim_names = None
lon, lat = np.asarray(lon), np.asarray(lat)
if len(lon.shape) > 1:
raise ValueError('lon can only be 1d')
if len(lat.shape) > 1:
raise ValueError('lat can only be 1d')
assert lon.shape == lat.shape
locstream = LocStream.from_xarray(lon, lat)
return locstream, (1,) + lon.shape, dim_names
def polys_to_ESMFmesh(polys):
"""
Convert a sequence of shapely Polygons to a ESMF.Mesh object.
MultiPolygons are split in their polygon parts and holes are ignored.
Parameters
----------
polys : sequence of shapely Polygon or MultiPolygon
Returns
-------
exterior : ESMF.Mesh
A mesh where elements are the exterior rings of the polygons
tuple
The shape of the mesh : (1, N_elements)
"""
ext, holes, _, _ = split_polygons_and_holes(polys)
if len(holes) > 0:
warnings.warn(
'Some passed polygons have holes, those are not represented in the returned Mesh.'
)
return Mesh.from_polygons(ext), (1, len(ext))
class BaseRegridder(object):
def __init__(
self,
grid_in,
grid_out,
method,
filename=None,
reuse_weights=False,
extrap_method=None,
extrap_dist_exponent=None,
extrap_num_src_pnts=None,
weights=None,
ignore_degenerate=None,
input_dims=None,
output_dims=None,
unmapped_to_nan=False,
parallel=False,
):
"""
Base xESMF regridding class supporting ESMF objects: `Grid`, `Mesh` and `LocStream`.
Create or use existing subclasses to support other types of input objects. See for example `Regridder`
to regrid `xarray.DataArray` objects, or `SpatialAverager`
to average grids over regions defined by polygons.
Parameters
----------
grid_in, grid_out : ESMF Grid or Locstream or Mesh
Input and output grid structures as ESMFpy objects.
method : str
Regridding method. Options are
- 'bilinear'
- 'conservative', **need grid corner information**
- 'conservative_normed', **need grid corner information**
- 'patch'
- 'nearest_s2d'
- 'nearest_d2s'
filename : str, optional
Name for the weight file. The default naming scheme is::
{method}_{Ny_in}x{Nx_in}_{Ny_out}x{Nx_out}.nc
e.g. bilinear_400x600_300x400.nc
reuse_weights : bool, optional
Whether to read existing weight file to save computing time.
False by default (i.e. re-compute, not reuse).
extrap_method : str, optional
Extrapolation method. Options are
- 'inverse_dist'
- 'nearest_s2d'
extrap_dist_exponent : float, optional
The exponent to raise the distance to when calculating weights for the
extrapolation method. If none are specified, defaults to 2.0
extrap_num_src_pnts : int, optional
The number of source points to use for the extrapolation methods
that use more than one source point. If none are specified, defaults to 8
weights : None, coo_matrix, dict, str, Dataset, Path,
Regridding weights, stored as
- a scipy.sparse COO matrix,
- a dictionary with keys `row_dst`, `col_src` and `weights`,
- an xarray Dataset with data variables `col`, `row` and `S`,
- or a path to a netCDF file created by ESMF.
If None, compute the weights.
ignore_degenerate : bool, optional
If False (default), raise error if grids contain degenerated cells
(i.e. triangles or lines, instead of quadrilaterals)
input_dims : tuple of str, optional
A tuple of dimension names to look for when regridding DataArrays or Datasets.
If not given or if those are not found on the regridded object, regridding
uses the two last dimensions of the object (or the last one for input LocStreams and Meshes).
output_dims : tuple of str, optional
A tuple of dimension names to look for when regridding DataArrays or Datasets.
If not given or if those are not found on the regridded object, regridding
uses the two last dimensions of the object (or the last one for output LocStreams and Meshes)
unmapped_to_nan: boolean, optional
Set values of unmapped points to `np.nan` instead of zero (ESMF default). This is useful for
target cells lying outside of the source domain when no output mask is defined.
If an output mask is defined, or regridding method is `nearest_s2d` or `nearest_d2s`,
this option has no effect.
parallel: bool, optional
Are the weights generated in parallel with Dask. Default is False. When True, the weight
generation in the BaseRegridder is skipped and weights are generated in paralell in the
subsest_regridder instead.
Returns
-------
baseregridder : xESMF BaseRegridder object
"""
self.grid_in = grid_in
self.grid_out = grid_out
self.method = method
self.reuse_weights = reuse_weights
self.extrap_method = extrap_method
self.extrap_dist_exponent = extrap_dist_exponent
self.extrap_num_src_pnts = extrap_num_src_pnts
self.ignore_degenerate = ignore_degenerate
self.periodic = getattr(self.grid_in, 'periodic_dim', None) is not None
self.sequence_in = isinstance(self.grid_in, (LocStream, Mesh))
self.sequence_out = isinstance(self.grid_out, (LocStream, Mesh))
if input_dims is not None and len(input_dims) != int(not self.sequence_in) + 1:
raise ValueError(f'Wrong number of dimension names in `input_dims` ({len(input_dims)}.')
self.in_horiz_dims = input_dims
if output_dims is not None and len(output_dims) != int(not self.sequence_out) + 1:
raise ValueError(
f'Wrong number of dimension names in `output dims` ({len(output_dims)}.'
)
self.out_horiz_dims = output_dims
# record grid shape information
# We need to invert Grid shapes to respect xESMF's convention (y, x).
self.shape_in = self.grid_in.get_shape()[::-1]
self.shape_out = self.grid_out.get_shape()[::-1]
self.n_in = self.shape_in[0] * self.shape_in[1]
self.n_out = self.shape_out[0] * self.shape_out[1]
# some logic about reusing weights with either filename or weights args
if reuse_weights and (filename is None) and (weights is None):
raise ValueError('To reuse weights, you need to provide either filename or weights.')
if not parallel:
if not reuse_weights and weights is None:
weights = self._compute_weights() # Dictionary of weights
else:
weights = filename if filename is not None else weights
assert weights is not None
# Convert weights, whatever their format, to a sparse coo matrix
self.weights = read_weights(weights, self.n_in, self.n_out)
# replace zeros by NaN for weight matrix entries of unmapped target cells if specified or a mask is present
if (
(self.grid_out.mask is not None) and (self.grid_out.mask[0] is not None)
) or unmapped_to_nan is True:
self.weights = add_nans_to_weights(self.weights)
# follows legacy logic of writing weights if filename is provided
if filename is not None and not reuse_weights:
self.to_netcdf(filename=filename)
# set default weights filename if none given
self.filename = self._get_default_filename() if filename is None else filename
@property
def A(self):
message = (
'regridder.A is deprecated and will be removed in future versions. '
'Use regridder.weights instead.'
)
warnings.warn(message, DeprecationWarning)
# DeprecationWarning seems to be ignored by certain Python environments
# Also print to make sure users notice this.
print(message)
return self.weights
@property
def w(self) -> xr.DataArray:
"""Return weights as a 4D DataArray with dimensions (y_out, x_out, y_in, x_in).
ESMF stores the weights in a 2D array with dimensions (out_dim, in_dim), the size of the output and input
grids respectively (ny x nx). This property returns the weights reshaped as a 4D array to simplify
comparisons with the original grids.
"""
# TODO: Add coords ?
s = self.shape_out + self.shape_in
data = self.weights.data.reshape(s)
dims = 'y_out', 'x_out', 'y_in', 'x_in'
return xr.DataArray(data, dims=dims)
def _get_default_filename(self):
# e.g. bilinear_400x600_300x400.nc
filename = '{0}_{1}x{2}_{3}x{4}'.format(
self.method,
self.shape_in[0],
self.shape_in[1],
self.shape_out[0],
self.shape_out[1],
)
if self.periodic:
filename += '_peri.nc'
else:
filename += '.nc'
return filename
def _compute_weights(self):
regrid = esmf_regrid_build(
self.grid_in,
self.grid_out,
self.method,
extrap_method=self.extrap_method,
extrap_dist_exponent=self.extrap_dist_exponent,
extrap_num_src_pnts=self.extrap_num_src_pnts,
ignore_degenerate=self.ignore_degenerate,
)
w = regrid.get_weights_dict(deep_copy=True)
esmf_regrid_finalize(regrid) # only need weights, not regrid object
return w
def __call__(self, indata, keep_attrs=False, skipna=False, na_thres=1.0, output_chunks=None):
"""
Apply regridding to input data.
Parameters
----------
indata : numpy array, dask array, xarray DataArray or Dataset.
If not an xarray object or if `input_dìms` was not given in the init,
the rightmost two dimensions must be the same as ``ds_in``.
Can have arbitrary additional dimensions.
Examples of valid shapes
- (n_lat, n_lon), if ``ds_in`` has shape (n_lat, n_lon)
- (n_time, n_lev, n_y, n_x), if ``ds_in`` has shape (Ny, n_x)
Either give `input_dims` or transpose your input data
if the horizontal dimensions are not the rightmost two dimensions
Variables without the regridded dimensions are silently skipped when passing a Dataset.
keep_attrs : bool, optional
Keep attributes for xarray DataArrays or Datasets.
Defaults to False.
skipna: bool, optional
Whether to skip missing values when regridding.
When set to False, an output value is masked when a single
input value is missing and no grid mask is provided.
When set to True, missing values do not contaminate the regridding
since only valid values are taken into account.
In this case, a given output point is set to NaN only if the ratio
of missing values exceeds the level set by `na_thres`:
for instance, when the center of a cell is computed linearly
from its four corners, one of which is missing, the output value
is set to NaN if `na_thres` is smaller than 0.25.
na_thres: float, optional
A value within the [0., 1.] interval that defines the maximum
ratio of missing grid points involved in the regrdding over which
the output value is set to NaN. For instance, if `na_thres` is set
to 0, the output value is NaN if a single NaN is found in the input
values that are used to compute the output value; similarly,
if `na_thres` is set to 1, all input values must be missing to
mask the output value.
output_chunks: dict or tuple, optional
The desired chunks to have on the output along the spatial axes, if indata is a dask array.
Other non-spatial axes inherit the same chunks as indata.
Default behavior depends on the chunking of indata. If it is not chunked along
the spatial dimension, the output will also not be chunked,
equivalent to passing ``output_chunks=(-1, -1)``.
If it is chunked, the output will preserve the chunk sizes,
equivalent to passing ``output_chunks=ìndata.chunks``.
Chunks have to be specified for all spatial dimensions
of the output data otherwise regridding will fail. output_chunks can
either be a tuple the same size as the spatial axes of outdata or it
can be a dict with defined dims. If output_chunks is a dict, the
keys must match the dims of the output grid passed when initializing this Regridder.
Returns
-------
outdata : Data type is the same as input data type, except for datasets.
On the same horizontal grid as ``ds_out``,
with extra dims in ``dr_in``.
Assuming ``ds_out`` has the shape of (n_y_out, n_x_out),
examples of returning shapes are
- (n_y_out, n_x_out), if ``dr_in`` is 2D
- (n_time, n_lev, n_y_out, n_x_out), if ``dr_in`` has shape
(n_time, n_lev, n_y, n_x)
Datasets with dask-backed variables will have modified dtypes.
If all input variables are 'float32', all output will be 'float32',
for any other case, all outputs will be 'float64'.
"""
if isinstance(indata, dask_array_type + (np.ndarray,)):
return self.regrid_array(
indata,
self.weights.data,
skipna=skipna,
na_thres=na_thres,
output_chunks=output_chunks,
)
elif isinstance(indata, xr.DataArray):
return self.regrid_dataarray(
indata,
keep_attrs=keep_attrs,
skipna=skipna,
na_thres=na_thres,
output_chunks=output_chunks,
)
elif isinstance(indata, xr.Dataset):
return self.regrid_dataset(
indata,
keep_attrs=keep_attrs,
skipna=skipna,
na_thres=na_thres,
output_chunks=output_chunks,
)
else:
raise TypeError('input must be numpy array, dask array, xarray DataArray or Dataset!')
@staticmethod
def _regrid(indata, weights, *, shape_in, shape_out, skipna, na_thres):
# skipna: set missing values to zero
if skipna:
missing = np.isnan(indata)
indata = np.where(missing, 0.0, indata)
# apply weights
outdata = apply_weights(weights, indata, shape_in, shape_out)
# skipna: Compute the influence of missing data at each interpolation point and filter those not meeting acceptable threshold.
if skipna:
fraction_valid = apply_weights(weights, (~missing).astype('d'), shape_in, shape_out)
tol = 1e-6
bad = fraction_valid < np.clip(1 - na_thres, tol, 1 - tol)
fraction_valid[bad] = 1
outdata = np.where(bad, np.nan, outdata / fraction_valid)
return outdata
def regrid_array(self, indata, weights, skipna=False, na_thres=1.0, output_chunks=None):
"""See __call__()."""
if self.sequence_in:
indata = np.reshape(indata, (*indata.shape[:-1], 1, indata.shape[-1]))
# If output_chunk is dict, order output chunks to match order of out_horiz_dims and convert to tuple
if isinstance(output_chunks, dict):
output_chunks = tuple([output_chunks.get(key) for key in self.out_horiz_dims])
kwargs = {
'shape_in': self.shape_in,
'shape_out': self.shape_out,
}
check_shapes(indata, weights, **kwargs)
kwargs.update(skipna=skipna, na_thres=na_thres)
weights = self.weights.data.reshape(self.shape_out + self.shape_in)
if isinstance(indata, dask_array_type): # dask
if output_chunks is None:
# Default : same chunk size as the input to preserve chunksize
# Unless the input is not chunked along the dimension (shape_in == in_chunk_size), in which case we do not chunk along the dimension
# This preserves the pre-0.8 behaviour.
output_chunks = tuple(
min(chnkin, shpout) if shpin != chnkin else shpout
for shpout, shpin, chnkin in zip(
self.shape_out, self.shape_in, indata.chunksize[-2:]
)
)
fac = np.prod(
[np.ceil(shp / chnk) for shp, chnk in zip(self.shape_out, output_chunks)]
)
if fac > 4: # Dask's built-in threshold is 10
warnings.warn(
(
f'Regridding is increasing the number of chunks by a factor of {fac}, '
'you might want to specify sizes in `output_chunks` in the regridder call. '
f'Default behaviour is to preserve the chunk sizes from the input {indata.chunksize[-2:]}.'
),
da.core.PerformanceWarning,
stacklevel=3,
)
if len(output_chunks) != len(self.shape_out):
if len(output_chunks) == 1 and self.sequence_out:
output_chunks = (1, output_chunks[0])
else:
raise ValueError(
f'output_chunks must have same dimension as ds_out,'
f' output_chunks dimension ({len(output_chunks)}) does not '
f'match ds_out dimension ({len(self.shape_out)})'
)
weights = da.from_array(weights, chunks=(output_chunks + indata.chunksize[-2:]))
outdata = self._regrid(indata, weights, **kwargs)
else: # numpy
outdata = self._regrid(indata, weights, **kwargs)
return outdata
def regrid_numpy(self, indata, **kwargs):
warnings.warn(
'`regrid_numpy()` will be removed in xESMF 0.7, please use `regrid_array` instead.',
category=FutureWarning,
)
return self.regrid_array(indata, self.weights.data, **kwargs)
def regrid_dask(self, indata, **kwargs):
warnings.warn(
'`regrid_dask()` will be removed in xESMF 0.7, please use `regrid_array` instead.',
category=FutureWarning,
)
return self.regrid_array(indata, self.weights.data, **kwargs)
def regrid_dataarray(
self, dr_in, keep_attrs=False, skipna=False, na_thres=1.0, output_chunks=None
):
"""See __call__()."""
input_horiz_dims, temp_horiz_dims = self._parse_xrinput(dr_in)
kwargs = dict(skipna=skipna, na_thres=na_thres, output_chunks=output_chunks)
dr_out = xr.apply_ufunc(
self.regrid_array,
dr_in,
self.weights,
kwargs=kwargs,
input_core_dims=[input_horiz_dims, ('out_dim', 'in_dim')],
output_core_dims=[temp_horiz_dims],
dask='allowed',
keep_attrs=keep_attrs,
)
return self._format_xroutput(dr_out, temp_horiz_dims)
def regrid_dataset(
self, ds_in, keep_attrs=False, skipna=False, na_thres=1.0, output_chunks=None
):
"""See __call__()."""
# get the first data variable to infer input_core_dims
input_horiz_dims, temp_horiz_dims = self._parse_xrinput(ds_in)
kwargs = dict(skipna=skipna, na_thres=na_thres, output_chunks=output_chunks)
non_regriddable = [
name
for name, data in ds_in.data_vars.items()
if not set(input_horiz_dims).issubset(data.dims)
]
ds_in = ds_in.drop_vars(non_regriddable)
ds_out = xr.apply_ufunc(
self.regrid_array,
ds_in,
self.weights,
kwargs=kwargs,
input_core_dims=[input_horiz_dims, ('out_dim', 'in_dim')],
output_core_dims=[temp_horiz_dims],
dask='allowed',
keep_attrs=keep_attrs,
)
return self._format_xroutput(ds_out, temp_horiz_dims)
def _parse_xrinput(self, dr_in):
# dr could be a DataArray or a Dataset
# Get input horiz dim names and set output horiz dim names
if self.in_horiz_dims is not None and all(dim in dr_in.dims for dim in self.in_horiz_dims):
input_horiz_dims = self.in_horiz_dims
else:
if isinstance(dr_in, Dataset):
name, dr_in = next(iter(dr_in.items()))
else:
# For warning purposes
name = dr_in.name
if self.sequence_in:
input_horiz_dims = dr_in.dims[-1:]
else:
input_horiz_dims = dr_in.dims[-2:]
# help user debugging invalid horizontal dimensions
warnings.warn(
(
f'Using dimensions {input_horiz_dims} from data variable {name} '
'as the horizontal dimensions for the regridding.'
),
UserWarning,
)
if self.sequence_out:
temp_horiz_dims = ['dummy', 'locations']
else:
temp_horiz_dims = [s + '_new' for s in input_horiz_dims]
if self.sequence_in and not self.sequence_out:
temp_horiz_dims = ['dummy_new'] + temp_horiz_dims
return input_horiz_dims, temp_horiz_dims
def _format_xroutput(self, out, new_dims=None):
out.attrs['regrid_method'] = self.method
return out
def __repr__(self):
info = (
'xESMF Regridder \n'
'Regridding algorithm: {} \n'
'Weight filename: {} \n'
'Reuse pre-computed weights? {} \n'
'Input grid shape: {} \n'
'Output grid shape: {} \n'
'Periodic in longitude? {}'.format(
self.method,
self.filename,
self.reuse_weights,
self.shape_in,
self.shape_out,
self.periodic,
)
)
return info
def to_netcdf(self, filename=None):
"""Save weights to disk as a netCDF file."""
if filename is None:
filename = self.filename
w = self.weights.data
dim = 'n_s'
ds = xr.Dataset(
{'S': (dim, w.data), 'col': (dim, w.coords[1, :] + 1), 'row': (dim, w.coords[0, :] + 1)}
)
ds.to_netcdf(filename)
return filename
class Regridder(BaseRegridder):
def __init__(
self,
ds_in,
ds_out,
method,
locstream_in=False,
locstream_out=False,
periodic=False,
parallel=False,
**kwargs,
):
"""
Make xESMF regridder
Parameters
----------
ds_in, ds_out : xarray Dataset, DataArray, or dictionary
Contain input and output grid coordinates.
All variables that the cf-xarray accessor understand are accepted.
Otherwise, look for ``lon``, ``lat``,
optionally ``lon_b``, ``lat_b`` for conservative methods,
and ``mask``. Note that for `mask`, the ESMF convention is used,
where masked values are identified by 0, and non-masked values by 1.
For conservative methods, if bounds are not present, they will be
computed using `cf-xarray` (only 1D coordinates are currently supported).
Shape can be 1D (n_lon,) and (n_lat,) for rectilinear grids,
or 2D (n_y, n_x) for general curvilinear grids.
Shape of bounds should be (n+1,) or (n_y+1, n_x+1).
CF-bounds (shape (n, 2) or (n, m, 4)) are also accepted if they are
accessible through the cf-xarray accessor.
If either dataset includes a 2d mask variable, that will also be
used to inform the regridding.
If DataArrays are passed, the are simply converted to Datasets.
method : str
Regridding method. Options are
- 'bilinear'
- 'conservative', **need grid corner information**
- 'conservative_normed', **need grid corner information**
- 'patch'
- 'nearest_s2d'
- 'nearest_d2s'
periodic : bool, optional
Periodic in longitude? Default to False.
Only useful for global grids with non-conservative regridding.
Will be forced to False for conservative regridding.
parallel : bool, optional
Compute the weights in parallel with Dask. Default to False.
If True, weights are computed in parallel with Dask on subsets of the output grid using
chunks of the output grid.
filename : str, optional
Name for the weight file. The default naming scheme is::
{method}_{Ny_in}x{Nx_in}_{Ny_out}x{Nx_out}.nc
e.g. bilinear_400x600_300x400.nc
reuse_weights : bool, optional
Whether to read existing weight file to save computing time.
False by default (i.e. re-compute, not reuse).
extrap_method : str, optional
Extrapolation method. Options are
- 'inverse_dist'
- 'nearest_s2d'
extrap_dist_exponent : float, optional
The exponent to raise the distance to when calculating weights for the
extrapolation method. If none are specified, defaults to 2.0
extrap_num_src_pnts : int, optional
The number of source points to use for the extrapolation methods
that use more than one source point. If none are specified, defaults to 8
weights : None, coo_matrix, dict, str, Dataset, Path,
Regridding weights, stored as
- a scipy.sparse COO matrix,
- a dictionary with keys `row_dst`, `col_src` and `weights`,
- an xarray Dataset with data variables `col`, `row` and `S`,
- or a path to a netCDF file created by ESMF.
If None, compute the weights.
ignore_degenerate : bool, optional
If False (default), raise error if grids contain degenerated cells
(i.e. triangles or lines, instead of quadrilaterals)
unmapped_to_nan: boolean, optional
Set values of unmapped points to `np.nan` instead of zero (ESMF default). This is useful for
target cells lying outside of the source domain when no output mask is defined.
If an output mask is defined, or regridding method is `nearest_s2d` or `nearest_d2s`,
this option has no effect.
Returns
-------
regridder : xESMF regridder object
"""
methods_avail_ls_in = ['nearest_s2d', 'nearest_d2s']
methods_avail_ls_out = ['bilinear', 'patch'] + methods_avail_ls_in
if locstream_in and method not in methods_avail_ls_in:
raise ValueError(
f'locstream input is only available for method in {methods_avail_ls_in}'
)
if locstream_out and method not in methods_avail_ls_out:
raise ValueError(
f'locstream output is only available for method in {methods_avail_ls_out}'
)
reuse_weights = kwargs.get('reuse_weights', False)
weights = kwargs.get('weights', None)
if parallel and (reuse_weights or weights is not None):
parallel = False
warnings.warn(
'Cannot use parallel=True when reuse_weights=True or when weights is not None. Building Regridder normally.'
)
# Record basic switches
if method in ['conservative', 'conservative_normed']:
need_bounds = True
periodic = False # bound shape will not be N+1 for periodic grid
else:
need_bounds = False
# Ensure we have Datasets and not DataArrays.
if isinstance(ds_in, xr.DataArray):
ds_in = ds_in._to_temp_dataset()
if isinstance(ds_out, xr.DataArray):
ds_out = ds_out._to_temp_dataset()
# Construct ESMF grid, with some shape checking
if locstream_in:
grid_in, shape_in, input_dims = ds_to_ESMFlocstream(ds_in)
else:
grid_in, shape_in, input_dims = ds_to_ESMFgrid(
ds_in, need_bounds=need_bounds, periodic=periodic
)
if locstream_out:
grid_out, shape_out, output_dims = ds_to_ESMFlocstream(ds_out)
else:
grid_out, shape_out, output_dims = ds_to_ESMFgrid(ds_out, need_bounds=need_bounds)
# Create the BaseRegridder
super().__init__(
grid_in,
grid_out,
method,
input_dims=input_dims,
output_dims=output_dims,
parallel=parallel,
**kwargs,
)
# Record output grid and metadata
lon_out, lat_out = _get_lon_lat(ds_out)
if not isinstance(lon_out, DataArray):
if lon_out.ndim == 2:
dims = [('y', 'x'), ('y', 'x')]
elif self.sequence_out:
dims = [('locations',), ('locations',)]
else:
dims = [('lon',), ('lat',)]
lon_out = xr.DataArray(lon_out, dims=dims[0], name='lon', attrs=LON_CF_ATTRS)
lat_out = xr.DataArray(lat_out, dims=dims[1], name='lat', attrs=LAT_CF_ATTRS)
if lat_out.ndim == 2:
self.out_horiz_dims = lat_out.dims
elif self.sequence_out:
if lat_out.dims != lon_out.dims:
raise ValueError(
'Regridder expects a locstream output, but the passed longitude '
'and latitude are not specified along the same dimension. '
f'(lon: {lon_out.dims}, lat: {lat_out.dims})'
)
self.out_horiz_dims = ('dummy',) + lat_out.dims
else:
self.out_horiz_dims = (lat_out.dims[0], lon_out.dims[0])
if isinstance(ds_out, Dataset):
self.out_coords = {
name: crd
for name, crd in ds_out.coords.items()
if set(self.out_horiz_dims).issuperset(crd.dims)
}
grid_mapping = {
var.attrs['grid_mapping']
for var in ds_out.data_vars.values()
if 'grid_mapping' in var.attrs
}
if grid_mapping:
self.out_coords.update({gm: ds_out[gm] for gm in grid_mapping if gm in ds_out})
else:
self.out_coords = {lat_out.name: lat_out, lon_out.name: lon_out}
if parallel:
self._init_para_regrid(ds_in, ds_out, kwargs)
def _init_para_regrid(self, ds_in, ds_out, kwargs):
# Check if we have bounds as variable and not coords, and add them to coords in both datasets
if 'lon_b' in ds_out.data_vars:
ds_out = ds_out.set_coords(['lon_b', 'lat_b'])
if 'lon_b' in ds_in.data_vars:
ds_in = ds_in.set_coords(['lon_b', 'lat_b'])
if not (set(self.out_horiz_dims) - {'dummy'}).issubset(ds_out.chunksizes.keys()):
raise ValueError(
'Using `parallel=True` requires the output grid to have chunks along all spatial dimensions. '
'If the dataset has no variables, consider adding an all-True spatial mask with appropriate chunks.'
)
# Drop everything in ds_out except mask or create mask if None. This is to prevent map_blocks loading unnecessary large data
if self.sequence_out:
ds_out_dims_drop = set(ds_out.variables).difference(ds_out.data_vars)
ds_out = ds_out.drop_dims(ds_out_dims_drop)
else:
if 'mask' in ds_out:
mask = ds_out.mask
ds_out = ds_out.coords.to_dataset()