-
Notifications
You must be signed in to change notification settings - Fork 80
/
raster_array.py
1164 lines (1037 loc) · 40.4 KB
/
raster_array.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
"""
This module is an extension for xarray to provide rasterio capabilities
to xarray dataarrays.
Credits: The `reproject` functionality was adopted from https://github.com/opendatacube/datacube-core # noqa: E501
Source file:
- https://github.com/opendatacube/datacube-core/blob/084c84d78cb6e1326c7fbbe79c5b5d0bef37c078/datacube/api/geo_xarray.py # noqa: E501
datacube is licensed under the Apache License, Version 2.0:
- https://github.com/opendatacube/datacube-core/blob/1d345f08a10a13c316f81100936b0ad8b1a374eb/LICENSE # noqa: E501
"""
import copy
import importlib.metadata
import os
from pathlib import Path
from typing import (
Any,
Dict,
Hashable,
Iterable,
List,
Literal,
Mapping,
Optional,
Tuple,
Union,
)
import numpy as np
import rasterio
import rasterio.mask
import rasterio.warp
import xarray
from affine import Affine
from packaging import version
from rasterio.dtypes import dtype_rev
from rasterio.enums import Resampling
from rasterio.features import geometry_mask
from xarray.backends.file_manager import FileManager
from xarray.core.dtypes import get_fill_value
from rioxarray.crs import crs_from_user_input
from rioxarray.exceptions import (
MissingCRS,
NoDataInBounds,
OneDimensionalRaster,
RioXarrayError,
)
from rioxarray.raster_writer import (
FILL_VALUE_NAMES,
UNWANTED_RIO_ATTRS,
RasterioWriter,
_ensure_nodata_dtype,
)
from rioxarray.rioxarray import (
XRasterBase,
_get_data_var_message,
_make_coords,
_order_bounds,
)
_RASTERIO_GTE_12 = version.parse(
importlib.metadata.version("rasterio")
) >= version.parse("1.2")
# DTYPE TO NODATA MAP
# Based on: https://github.com/OSGeo/gdal/blob/
# dee861e7c91c2da7ef8ff849947713e4d9bd115c/
# swig/python/gdal-utils/osgeo_utils/gdal_calc.py#L61
_NODATA_DTYPE_MAP = {
1: 255, # GDT_Byte
2: 65535, # GDT_UInt16
3: -32768, # GDT_Int16
4: 4294967293, # GDT_UInt32
5: -2147483647, # GDT_Int32
6: 3.402823466e38, # GDT_Float32
7: 1.7976931348623158e308, # GDT_Float64
8: None, # GDT_CInt16
9: None, # GDT_CInt32
10: 3.402823466e38, # GDT_CFloat32
11: 1.7976931348623158e308, # GDT_CFloat64
12: None, # GDT_Int64
13: None, # GDT_UInt64
14: None, # GDT_Int8
}
def _generate_attrs(
src_data_array: xarray.DataArray, dst_nodata: Optional[float]
) -> Dict[str, Any]:
# add original attributes
new_attrs = copy.deepcopy(src_data_array.attrs)
# remove all nodata information
for unwanted_attr in FILL_VALUE_NAMES + UNWANTED_RIO_ATTRS:
new_attrs.pop(unwanted_attr, None)
# add nodata information
fill_value = (
src_data_array.rio.nodata
if src_data_array.rio.nodata is not None
else dst_nodata
)
if src_data_array.rio.encoded_nodata is None and fill_value is not None:
new_attrs["_FillValue"] = fill_value
return new_attrs
def _add_attrs_proj(
new_data_array: xarray.DataArray, src_data_array: xarray.DataArray
) -> xarray.DataArray:
"""Make sure attributes and projection correct"""
# make sure dimension information is preserved
if new_data_array.rio._x_dim is None:
new_data_array.rio._x_dim = src_data_array.rio.x_dim
if new_data_array.rio._y_dim is None:
new_data_array.rio._y_dim = src_data_array.rio.y_dim
# make sure attributes preserved
new_attrs = _generate_attrs(src_data_array, None)
# remove fill value if it already exists in the encoding
# this is for data arrays pulling the encoding from a
# source data array instead of being generated anew.
if "_FillValue" in new_data_array.encoding:
new_attrs.pop("_FillValue", None)
new_data_array.rio.set_attrs(new_attrs, inplace=True)
# make sure projection added
new_data_array.rio.write_grid_mapping(src_data_array.rio.grid_mapping, inplace=True)
new_data_array.rio.write_crs(src_data_array.rio.crs, inplace=True)
new_data_array.rio.write_coordinate_system(inplace=True)
new_data_array.rio.write_transform(inplace=True)
# make sure encoding added
new_data_array.encoding = src_data_array.encoding.copy()
return new_data_array
def _make_dst_affine(
src_data_array: xarray.DataArray,
src_crs: rasterio.crs.CRS,
dst_crs: rasterio.crs.CRS,
dst_resolution: Optional[Union[float, Tuple[float, float]]] = None,
dst_shape: Optional[Tuple[float, float]] = None,
**kwargs,
):
"""Determine the affine of the new projected `xarray.DataArray`"""
src_bounds = () if "gcps" in kwargs else src_data_array.rio.bounds()
src_height, src_width = src_data_array.rio.shape
dst_height, dst_width = dst_shape if dst_shape is not None else (None, None)
# pylint: disable=isinstance-second-argument-not-valid-type
if isinstance(dst_resolution, Iterable):
dst_resolution = tuple(abs(res_val) for res_val in dst_resolution) # type: ignore
elif dst_resolution is not None:
dst_resolution = abs(dst_resolution) # type: ignore
for key, value in (
("resolution", dst_resolution),
("dst_height", dst_height),
("dst_width", dst_width),
):
if value is not None:
kwargs[key] = value
dst_affine, dst_width, dst_height = rasterio.warp.calculate_default_transform(
src_crs,
dst_crs,
src_width,
src_height,
*src_bounds,
**kwargs,
)
return dst_affine, dst_width, dst_height
def _clip_from_disk(
xds: xarray.DataArray,
geometries: Iterable,
all_touched: bool,
drop: bool,
invert: bool,
) -> Optional[xarray.DataArray]:
"""
clip from disk if the file object is available
"""
try:
out_image, out_transform = rasterio.mask.mask(
xds.rio._manager.acquire(),
geometries,
all_touched=all_touched,
invert=invert,
crop=drop,
)
if xds.rio.encoded_nodata is not None and not np.isnan(xds.rio.encoded_nodata):
out_image = out_image.astype(np.float64)
out_image[out_image == xds.rio.encoded_nodata] = np.nan
height, width = out_image.shape[-2:]
cropped_ds = xarray.DataArray(
name=xds.name,
data=out_image,
coords=_make_coords(xds, out_transform, width, height),
dims=xds.dims,
attrs=xds.attrs,
)
cropped_ds.encoding = xds.encoding
return cropped_ds
except AttributeError:
return None
def _clip_xarray(
xds: xarray.DataArray,
geometries: Iterable,
all_touched: bool,
drop: bool,
invert: bool,
) -> xarray.DataArray:
"""
clip the xarray DataArray
"""
clip_mask_arr = geometry_mask(
geometries=geometries,
out_shape=(int(xds.rio.height), int(xds.rio.width)),
transform=xds.rio.transform(recalc=True),
invert=not invert,
all_touched=all_touched,
)
clip_mask_xray = xarray.DataArray(
clip_mask_arr,
dims=(xds.rio.y_dim, xds.rio.x_dim),
)
cropped_ds = xds.where(clip_mask_xray)
if drop:
cropped_ds.rio.set_spatial_dims(
x_dim=xds.rio.x_dim, y_dim=xds.rio.y_dim, inplace=True
)
cropped_ds = cropped_ds.rio.isel_window(
rasterio.windows.get_data_window(
np.ma.masked_array(clip_mask_arr, ~clip_mask_arr)
)
)
if xds.rio.nodata is not None and not np.isnan(xds.rio.nodata):
cropped_ds = cropped_ds.fillna(xds.rio.nodata)
return cropped_ds.astype(xds.dtype)
@xarray.register_dataarray_accessor("rio")
class RasterArray(XRasterBase):
"""This is the GIS extension for :obj:`xarray.DataArray`"""
def __init__(self, xarray_obj: xarray.DataArray):
super().__init__(xarray_obj)
self._obj: xarray.DataArray
# properties
self._nodata: Optional[float] = None
self._manager: Optional[
FileManager
] = None # https://github.com/corteva/rioxarray/issues/254
def set_nodata(
self, input_nodata: Optional[float], inplace: bool = True
) -> xarray.DataArray:
"""
Set the nodata value for the DataArray without modifying
the data array.
Parameters
----------
input_nodata: Optional[float]
Valid nodata for dtype.
inplace: bool, optional
If True, it will write to the existing dataset. Default is True.
Returns
-------
:obj:`xarray.DataArray`:
Dataset with nodata attribute set.
"""
obj: xarray.DataArray = self._get_obj(inplace=inplace) # type: ignore
obj.rio._nodata = input_nodata
return obj
def write_nodata(
self, input_nodata: Optional[float], encoded: bool = False, inplace=False
) -> xarray.DataArray:
"""
Write the nodata to the DataArray in a CF compliant manner.
Parameters
----------
input_nodata: Optional[float]
Nodata value for the DataArray.
If input_nodata is None, it will remove the _FillValue attribute.
encoded: bool, optional
If True, it will write the nodata value in the encoding and remove
the fill value from the attributes. This is useful for masking
with nodata. Default is False.
inplace: bool, optional
If True, it will write to the existing DataArray. Default is False.
Returns
-------
:obj:`xarray.DataArray`:
Modified DataArray with CF compliant nodata information.
Examples
--------
To write the nodata value if it is missing:
>>> raster.rio.write_nodata(-9999, inplace=True)
To write the nodata value on a copy:
>>> raster = raster.rio.write_nodata(-9999)
To mask with nodata:
>>> nodata = raster.rio.nodata
>>> raster = raster.where(raster != nodata)
>>> raster.rio.write_nodata(nodata, encoded=True, inplace=True)
"""
data_obj: xarray.DataArray = self._get_obj(inplace=inplace) # type: ignore
input_nodata = False if input_nodata is None else input_nodata
if input_nodata is not False:
input_nodata = _ensure_nodata_dtype(input_nodata, self._obj.dtype)
if encoded:
data_obj.rio.update_encoding(
dict(_FillValue=input_nodata), inplace=True
)
else:
data_obj.rio.update_attrs(dict(_FillValue=input_nodata), inplace=True)
if input_nodata is False or encoded:
new_attrs = dict(data_obj.attrs)
new_attrs.pop("_FillValue", None)
data_obj.rio.set_attrs(new_attrs, inplace=True)
if input_nodata is False and encoded:
new_encoding = dict(data_obj.encoding)
new_encoding.pop("_FillValue", None)
data_obj.rio.set_encoding(new_encoding, inplace=True)
if not encoded:
data_obj.rio.set_nodata(input_nodata, inplace=True)
return data_obj
@property
def encoded_nodata(self) -> Optional[float]:
"""Return the encoded nodata value for the dataset if encoded."""
encoded_nodata = self._obj.encoding.get("_FillValue")
if encoded_nodata is None:
return None
return _ensure_nodata_dtype(encoded_nodata, self._obj.dtype)
@property
def nodata(self) -> Optional[float]:
"""Get the nodata value for the dataset."""
if self._nodata is not None:
return None if self._nodata is False else self._nodata
if self.encoded_nodata is not None:
self._nodata = get_fill_value(self._obj.dtype)
else:
self._nodata = self._obj.attrs.get(
"_FillValue",
self._obj.attrs.get(
"missing_value",
self._obj.attrs.get("fill_value", self._obj.attrs.get("nodata")),
),
)
# look in places used by `xarray.open_rasterio`
if self._nodata is None:
try:
self._nodata = self._manager.acquire().nodata # type: ignore
except AttributeError:
try:
self._nodata = self._obj.attrs["nodatavals"][0]
except (KeyError, IndexError):
pass
if self._nodata is None:
self._nodata = False
return None
self._nodata = _ensure_nodata_dtype(self._nodata, self._obj.dtype)
return self._nodata
def reproject(
self,
dst_crs: Any,
resolution: Optional[Union[float, Tuple[float, float]]] = None,
shape: Optional[Tuple[int, int]] = None,
transform: Optional[Affine] = None,
resampling: Resampling = Resampling.nearest,
nodata: Optional[float] = None,
**kwargs,
) -> xarray.DataArray:
"""
Reproject :obj:`xarray.DataArray` objects
Powered by :func:`rasterio.warp.reproject`
.. note:: Only 2D/3D arrays with dimensions 'x'/'y' are currently supported.
Requires either a grid mapping variable with 'spatial_ref' or
a 'crs' attribute to be set containing a valid CRS.
If using a WKT (e.g. from spatiareference.org), make sure it is an OGC WKT.
.. versionadded:: 0.0.27 shape
.. versionadded:: 0.0.28 transform
.. versionadded:: 0.5.0 nodata, kwargs
Parameters
----------
dst_crs: str
OGC WKT string or Proj.4 string.
resolution: float or tuple(float, float), optional
Size of a destination pixel in destination projection units
(e.g. degrees or metres).
shape: tuple(int, int), optional
Shape of the destination in pixels (dst_height, dst_width). Cannot be used
together with resolution.
transform: Affine, optional
The destination transform.
resampling: rasterio.enums.Resampling, optional
See :func:`rasterio.warp.reproject` for more details.
nodata: float, optional
The nodata value used to initialize the destination;
it will remain in all areas not covered by the reprojected source.
Defaults to the nodata value of the source image if none provided
and exists or attempts to find an appropriate value by dtype.
**kwargs: dict
Additional keyword arguments to pass into :func:`rasterio.warp.reproject`.
To override:
- src_transform: `rio.write_transform`
- src_crs: `rio.write_crs`
- src_nodata: `rio.write_nodata`
Returns
-------
:obj:`xarray.DataArray`:
The reprojected DataArray.
"""
if resolution is not None and (shape is not None or transform is not None):
raise RioXarrayError("resolution cannot be used with shape or transform.")
if self.crs is None:
raise MissingCRS(
"CRS not found. Please set the CRS with 'rio.write_crs()'."
f"{_get_data_var_message(self._obj)}"
)
gcps = self.get_gcps()
if gcps:
kwargs.setdefault("gcps", gcps)
gcps_or_rpcs = "gcps" in kwargs or "rpcs" in kwargs
src_affine = None if gcps_or_rpcs else self.transform(recalc=True)
if transform is None:
dst_affine, dst_width, dst_height = _make_dst_affine(
self._obj, self.crs, dst_crs, resolution, shape, **kwargs
)
else:
dst_affine = transform
if shape is not None:
dst_height, dst_width = shape
else:
dst_height, dst_width = self.shape
dst_data = self._create_dst_data(dst_height, dst_width)
dst_nodata = self._get_dst_nodata(nodata)
rasterio.warp.reproject(
source=self._obj.values,
destination=dst_data,
src_transform=src_affine,
src_crs=self.crs,
src_nodata=self.nodata,
dst_transform=dst_affine,
dst_crs=dst_crs,
dst_nodata=dst_nodata,
resampling=resampling,
**kwargs,
)
# add necessary attributes
new_attrs = _generate_attrs(self._obj, dst_nodata)
# make sure dimensions with coordinates renamed to x,y
dst_dims: List[Hashable] = []
for dim in self._obj.dims:
if dim == self.x_dim:
dst_dims.append("x")
elif dim == self.y_dim:
dst_dims.append("y")
else:
dst_dims.append(dim)
xda = xarray.DataArray(
name=self._obj.name,
data=dst_data,
coords=_make_coords(
src_data_array=self._obj,
dst_affine=dst_affine,
dst_width=dst_width,
dst_height=dst_height,
force_generate=gcps_or_rpcs,
),
dims=tuple(dst_dims),
attrs=new_attrs,
)
xda.encoding = self._obj.encoding
xda.rio.write_transform(dst_affine, inplace=True)
xda.rio.write_crs(dst_crs, inplace=True)
xda.rio.write_coordinate_system(inplace=True)
return xda
def _get_dst_nodata(self, nodata: Optional[float]) -> Optional[float]:
default_nodata = (
_NODATA_DTYPE_MAP.get(dtype_rev[self._obj.dtype.name])
if self.nodata is None
else self.nodata
)
dst_nodata = default_nodata if nodata is None else nodata
return dst_nodata
def _create_dst_data(self, dst_height: int, dst_width: int) -> np.ndarray:
extra_dim = self._check_dimensions()
if extra_dim:
dst_data = np.zeros(
(self._obj[extra_dim].size, dst_height, dst_width),
dtype=self._obj.dtype.type,
)
else:
dst_data = np.zeros((dst_height, dst_width), dtype=self._obj.dtype.type)
return dst_data
def reproject_match(
self,
match_data_array: Union[xarray.DataArray, xarray.Dataset],
resampling: Resampling = Resampling.nearest,
**reproject_kwargs,
) -> xarray.DataArray:
"""
Reproject a DataArray object to match the resolution, projection,
and region of another DataArray.
Powered by :func:`rasterio.warp.reproject`
.. note:: Only 2D/3D arrays with dimensions 'x'/'y' are currently supported.
Requires either a grid mapping variable with 'spatial_ref' or
a 'crs' attribute to be set containing a valid CRS.
If using a WKT (e.g. from spatiareference.org), make sure it is an OGC WKT.
.. versionadded:: 0.9 reproject_kwargs
Parameters
----------
match_data_array: :obj:`xarray.DataArray` | :obj:`xarray.Dataset`
DataArray of the target resolution and projection.
resampling: rasterio.enums.Resampling, optional
See :func:`rasterio.warp.reproject` for more details.
**reproject_kwargs:
Other options to pass to :meth:`rioxarray.raster_array.RasterArray.reproject`
Returns
--------
:obj:`xarray.DataArray`:
Contains the data from the src_data_array, reprojected to match
match_data_array.
"""
reprojected_data_array = self.reproject(
match_data_array.rio.crs,
transform=match_data_array.rio.transform(recalc=True),
shape=match_data_array.rio.shape,
resampling=resampling,
**reproject_kwargs,
)
# hack to resolve: https://github.com/corteva/rioxarray/issues/298
# may be resolved in the future by flexible indexes:
# https://github.com/pydata/xarray/pull/4489#issuecomment-831809607
x_attrs = reprojected_data_array[reprojected_data_array.rio.x_dim].attrs.copy()
y_attrs = reprojected_data_array[reprojected_data_array.rio.y_dim].attrs.copy()
# ensure coords the same
reprojected_data_array = reprojected_data_array.assign_coords(
{
reprojected_data_array.rio.x_dim: copy.copy(
match_data_array[match_data_array.rio.x_dim].values
),
reprojected_data_array.rio.y_dim: copy.copy(
match_data_array[match_data_array.rio.y_dim].values
),
}
)
# ensure attributes copied
reprojected_data_array[reprojected_data_array.rio.x_dim].attrs = x_attrs
reprojected_data_array[reprojected_data_array.rio.y_dim].attrs = y_attrs
return reprojected_data_array
def pad_xy(
self,
minx: float,
miny: float,
maxx: float,
maxy: float,
constant_values: Union[
float, Tuple[int, int], Mapping[Any, Tuple[int, int]], None
] = None,
) -> xarray.DataArray:
"""Pad the array to x,y bounds.
.. versionadded:: 0.0.29
Parameters
----------
minx: float
Minimum bound for x coordinate.
miny: float
Minimum bound for y coordinate.
maxx: float
Maximum bound for x coordinate.
maxy: float
Maximum bound for y coordinate.
constant_values: scalar, tuple or mapping of hashable to tuple
The value used for padding. If None, nodata will be used if it is
set, and np.nan otherwise.
Returns
-------
:obj:`xarray.DataArray`:
The padded object.
"""
# pylint: disable=too-many-locals
left, bottom, right, top = self._internal_bounds()
resolution_x, resolution_y = self.resolution()
y_before = y_after = 0
x_before = x_after = 0
y_coord: Union[xarray.DataArray, np.ndarray] = self._obj[self.y_dim]
x_coord: Union[xarray.DataArray, np.ndarray] = self._obj[self.x_dim]
if top - resolution_y < maxy:
new_y_coord: np.ndarray = np.arange(bottom, maxy, -resolution_y)[::-1]
y_before = len(new_y_coord) - len(y_coord)
y_coord = new_y_coord
top = y_coord[0]
if bottom + resolution_y > miny:
new_y_coord = np.arange(top, miny, resolution_y)
y_after = len(new_y_coord) - len(y_coord)
y_coord = new_y_coord
bottom = y_coord[-1]
if left - resolution_x > minx:
new_x_coord: np.ndarray = np.arange(right, minx, -resolution_x)[::-1]
x_before = len(new_x_coord) - len(x_coord)
x_coord = new_x_coord
left = x_coord[0]
if right + resolution_x < maxx:
new_x_coord = np.arange(left, maxx, resolution_x)
x_after = len(new_x_coord) - len(x_coord)
x_coord = new_x_coord
right = x_coord[-1]
if constant_values is None:
constant_values = np.nan if self.nodata is None else self.nodata
superset = self._obj.pad(
pad_width={
self.x_dim: (x_before, x_after),
self.y_dim: (y_before, y_after),
},
constant_values=constant_values, # type: ignore
).rio.set_spatial_dims(x_dim=self.x_dim, y_dim=self.y_dim, inplace=True)
superset[self.x_dim] = x_coord
superset[self.y_dim] = y_coord
superset.rio.write_transform(inplace=True)
return superset
def pad_box(
self,
minx: float,
miny: float,
maxx: float,
maxy: float,
constant_values: Union[
float, Tuple[int, int], Mapping[Any, Tuple[int, int]], None
] = None,
) -> xarray.DataArray:
"""Pad the :obj:`xarray.DataArray` to a bounding box
.. versionadded:: 0.0.29
Parameters
----------
minx: float
Minimum bound for x coordinate.
miny: float
Minimum bound for y coordinate.
maxx: float
Maximum bound for x coordinate.
maxy: float
Maximum bound for y coordinate.
constant_values: scalar, tuple or mapping of hashable to tuple
The value used for padding. If None, nodata will be used if it is
set, and np.nan otherwise.
Returns
-------
:obj:`xarray.DataArray`:
The padded object.
"""
resolution_x, resolution_y = self.resolution()
pad_minx = minx - abs(resolution_x) / 2.0
pad_miny = miny - abs(resolution_y) / 2.0
pad_maxx = maxx + abs(resolution_x) / 2.0
pad_maxy = maxy + abs(resolution_y) / 2.0
pd_array = self.pad_xy(pad_minx, pad_miny, pad_maxx, pad_maxy, constant_values)
# make sure correct attributes preserved & projection added
_add_attrs_proj(pd_array, self._obj)
return pd_array
def clip_box(
self,
minx: float,
miny: float,
maxx: float,
maxy: float,
auto_expand: Union[bool, int] = False,
auto_expand_limit: int = 3,
crs: Optional[Any] = None,
) -> xarray.DataArray:
"""Clip the :obj:`xarray.DataArray` by a bounding box.
.. versionadded:: 0.12 crs
Parameters
----------
minx: float
Minimum bound for x coordinate.
miny: float
Minimum bound for y coordinate.
maxx: float
Maximum bound for x coordinate.
maxy: float
Maximum bound for y coordinate.
auto_expand: Union[bool, int]
If True, it will expand clip search if only 1D raster found with clip.
auto_expand_limit: int
maximum number of times the clip will be retried before raising
an exception.
crs: :obj:`rasterio.crs.CRS`, optional
The CRS of the bounding box. Default is to assume it is the same
as the dataset.
Returns
-------
xarray.DataArray:
The clipped object.
"""
if self.width == 1 or self.height == 1:
raise OneDimensionalRaster(
"At least one of the raster x,y coordinates has only one point."
f"{_get_data_var_message(self._obj)}"
)
if crs is not None and self.crs is None:
raise MissingCRS(
"CRS not found. Please set the CRS with 'rio.write_crs()'."
f"{_get_data_var_message(self._obj)}"
)
crs = crs_from_user_input(crs) if crs is not None else self.crs
if self.crs != crs:
minx, miny, maxx, maxy = rasterio.warp.transform_bounds(
src_crs=crs,
dst_crs=self.crs,
left=minx,
bottom=miny,
right=maxx,
top=maxy,
)
if (
self.crs is not None
and self.crs.is_geographic # pylint: disable=no-member
and minx > maxx
):
raise RioXarrayError(
"Transformed bounds crossed the antimeridian. "
"Please transform your bounds manually using "
"rasterio.warp.transform_bounds and clip using "
"the bounding box(es) desired."
)
resolution_x, resolution_y = self.resolution()
# make sure that if the coordinates are
# in reverse order that it still works
left, bottom, right, top = _order_bounds(
minx=minx,
miny=miny,
maxx=maxx,
maxy=maxy,
resolution_x=resolution_x,
resolution_y=resolution_y,
)
# pull the data out
window_error = None
try:
window = rasterio.windows.from_bounds(
left=np.array(left).item(),
bottom=np.array(bottom).item(),
right=np.array(right).item(),
top=np.array(top).item(),
transform=self.transform(recalc=True),
)
cl_array: xarray.DataArray = self.isel_window(window) # type: ignore
except rasterio.errors.WindowError as err:
window_error = err
# check that the window has data in it
if window_error or cl_array.rio.width <= 1 or cl_array.rio.height <= 1:
if auto_expand and auto_expand < auto_expand_limit:
return self.clip_box(
minx=minx - abs(resolution_x) / 2.0,
miny=miny - abs(resolution_y) / 2.0,
maxx=maxx + abs(resolution_x) / 2.0,
maxy=maxy + abs(resolution_y) / 2.0,
auto_expand=int(auto_expand) + 1,
auto_expand_limit=auto_expand_limit,
)
if window_error:
raise window_error
if cl_array.rio.width < 1 or cl_array.rio.height < 1:
raise NoDataInBounds(
f"No data found in bounds.{_get_data_var_message(self._obj)}"
)
if cl_array.rio.width == 1 or cl_array.rio.height == 1:
raise OneDimensionalRaster(
"At least one of the clipped raster x,y coordinates"
" has only one point."
f"{_get_data_var_message(self._obj)}"
)
# make sure correct attributes preserved & projection added
_add_attrs_proj(cl_array, self._obj)
return cl_array
def clip(
self,
geometries: Iterable,
crs: Optional[Any] = None,
all_touched: bool = False,
drop: bool = True,
invert: bool = False,
from_disk: bool = False,
) -> xarray.DataArray:
"""
Crops a :obj:`xarray.DataArray` by geojson like geometry dicts.
Powered by `rasterio.features.geometry_mask`.
Examples:
>>> geometry = ''' {"type": "Polygon",
... "coordinates": [
... [[-94.07955380199459, 41.69085871273774],
... [-94.06082436942204, 41.69103313774798],
... [-94.06063203899649, 41.67932439500822],
... [-94.07935807746362, 41.679150041277325],
... [-94.07955380199459, 41.69085871273774]]]}'''
>>> cropping_geometries = [geojson.loads(geometry)]
>>> xds = xarray.open_rasterio('cool_raster.tif')
>>> cropped = xds.rio.clip(geometries=cropping_geometries, crs=4326)
.. versionadded:: 0.2 from_disk
Parameters
----------
geometries: Iterable
A list of geojson geometry dicts or objects with __geom_interface__ with
if you have rasterio 1.2+.
crs: :obj:`rasterio.crs.CRS`, optional
The CRS of the input geometries. Default is to assume it is the same
as the dataset.
all_touched : bool, optional
If True, all pixels touched by geometries will be burned in. If
false, only pixels whose center is within the polygon or that
are selected by Bresenham's line algorithm will be burned in.
drop: bool, optional
If True, drop the data outside of the extent of the mask geoemtries
Otherwise, it will return the same raster with the data masked.
Default is True.
invert: boolean, optional
If False, pixels that do not overlap shapes will be set as nodata.
Otherwise, pixels that overlap the shapes will be set as nodata.
False by default.
from_disk: boolean, optional
If True, it will clip from disk using rasterio.mask.mask if possible.
This is beneficial when the size of the data is larger than memory.
Default is False.
Returns
-------
:obj:`xarray.DataArray`:
The clipped object.
"""
if self.crs is None:
raise MissingCRS(
"CRS not found. Please set the CRS with 'rio.write_crs()'."
f"{_get_data_var_message(self._obj)}"
)
crs = crs_from_user_input(crs) if crs is not None else self.crs
if self.crs != crs:
if _RASTERIO_GTE_12:
geometries = rasterio.warp.transform_geom(crs, self.crs, geometries)
else:
geometries = [
rasterio.warp.transform_geom(crs, self.crs, geometry)
for geometry in geometries
]
cropped_ds = None
if from_disk:
cropped_ds = _clip_from_disk(
self._obj,
geometries=geometries,
all_touched=all_touched,
drop=drop,
invert=invert,
)
if cropped_ds is None:
cropped_ds = _clip_xarray(
self._obj,
geometries=geometries,
all_touched=all_touched,
drop=drop,
invert=invert,
)
if (
cropped_ds.coords[self.x_dim].size < 1
or cropped_ds.coords[self.y_dim].size < 1
):
raise NoDataInBounds(
f"No data found in bounds.{_get_data_var_message(self._obj)}"
)
# make sure correct attributes preserved & projection added
_add_attrs_proj(cropped_ds, self._obj)
return cropped_ds
def _interpolate_na(
self, src_data: Any, method: Literal["linear", "nearest", "cubic"] = "nearest"
) -> np.ndarray:
"""
This method uses scipy.interpolate.griddata to interpolate missing data.
Parameters
----------
src_data: Any
Input data array.
method: {'linear', 'nearest', 'cubic'}, optional
The method to use for interpolation in `scipy.interpolate.griddata`.
Returns
-------
:class:`numpy.ndarray`:
An interpolated :class:`numpy.ndarray`.
"""
try:
from scipy.interpolate import ( # pylint: disable=import-outside-toplevel,import-error
griddata,
)
except ModuleNotFoundError as err:
raise ModuleNotFoundError(
"scipy is not found. Use rioxarray[interp] to install."
) from err
src_data_flat = src_data.flatten()
try:
data_isnan = np.isnan(self.nodata) # type: ignore
except TypeError:
data_isnan = False
if not data_isnan:
data_bool = src_data_flat != self.nodata
else:
data_bool = ~np.isnan(src_data_flat)
if not data_bool.any():
return src_data
x_coords, y_coords = np.meshgrid(
self._obj.coords[self.x_dim].values, self._obj.coords[self.y_dim].values
)
return griddata(
points=(x_coords.flatten()[data_bool], y_coords.flatten()[data_bool]),
values=src_data_flat[data_bool],