rioxarray 0.15.3.dev0__tar.gz → 0.18.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. {rioxarray-0.15.3.dev0 → rioxarray-0.18.2}/AUTHORS.rst +6 -1
  2. {rioxarray-0.15.3.dev0 → rioxarray-0.18.2}/CONTRIBUTING.rst +2 -2
  3. {rioxarray-0.15.3.dev0/rioxarray.egg-info → rioxarray-0.18.2}/PKG-INFO +6 -5
  4. {rioxarray-0.15.3.dev0 → rioxarray-0.18.2}/README.rst +1 -1
  5. {rioxarray-0.15.3.dev0 → rioxarray-0.18.2}/pyproject.toml +4 -3
  6. {rioxarray-0.15.3.dev0 → rioxarray-0.18.2}/rioxarray/_io.py +52 -27
  7. {rioxarray-0.15.3.dev0 → rioxarray-0.18.2}/rioxarray/merge.py +76 -65
  8. {rioxarray-0.15.3.dev0 → rioxarray-0.18.2}/rioxarray/raster_array.py +97 -41
  9. {rioxarray-0.15.3.dev0 → rioxarray-0.18.2}/rioxarray/raster_dataset.py +51 -19
  10. {rioxarray-0.15.3.dev0 → rioxarray-0.18.2}/rioxarray/raster_writer.py +44 -29
  11. {rioxarray-0.15.3.dev0 → rioxarray-0.18.2}/rioxarray/rioxarray.py +98 -30
  12. {rioxarray-0.15.3.dev0 → rioxarray-0.18.2}/rioxarray/xarray_plugin.py +1 -0
  13. {rioxarray-0.15.3.dev0 → rioxarray-0.18.2/rioxarray.egg-info}/PKG-INFO +6 -5
  14. {rioxarray-0.15.3.dev0 → rioxarray-0.18.2}/rioxarray.egg-info/requires.txt +2 -2
  15. {rioxarray-0.15.3.dev0 → rioxarray-0.18.2}/LICENSE +0 -0
  16. {rioxarray-0.15.3.dev0 → rioxarray-0.18.2}/LICENSE_datacube +0 -0
  17. {rioxarray-0.15.3.dev0 → rioxarray-0.18.2}/LICENSE_xarray +0 -0
  18. {rioxarray-0.15.3.dev0 → rioxarray-0.18.2}/MANIFEST.in +0 -0
  19. {rioxarray-0.15.3.dev0 → rioxarray-0.18.2}/rioxarray/__init__.py +0 -0
  20. {rioxarray-0.15.3.dev0 → rioxarray-0.18.2}/rioxarray/_options.py +0 -0
  21. {rioxarray-0.15.3.dev0 → rioxarray-0.18.2}/rioxarray/_show_versions.py +0 -0
  22. {rioxarray-0.15.3.dev0 → rioxarray-0.18.2}/rioxarray/crs.py +0 -0
  23. {rioxarray-0.15.3.dev0 → rioxarray-0.18.2}/rioxarray/exceptions.py +0 -0
  24. {rioxarray-0.15.3.dev0 → rioxarray-0.18.2}/rioxarray/py.typed +0 -0
  25. {rioxarray-0.15.3.dev0 → rioxarray-0.18.2}/rioxarray.egg-info/SOURCES.txt +0 -0
  26. {rioxarray-0.15.3.dev0 → rioxarray-0.18.2}/rioxarray.egg-info/dependency_links.txt +0 -0
  27. {rioxarray-0.15.3.dev0 → rioxarray-0.18.2}/rioxarray.egg-info/entry_points.txt +0 -0
  28. {rioxarray-0.15.3.dev0 → rioxarray-0.18.2}/rioxarray.egg-info/top_level.txt +0 -0
  29. {rioxarray-0.15.3.dev0 → rioxarray-0.18.2}/setup.cfg +0 -0
  30. {rioxarray-0.15.3.dev0 → rioxarray-0.18.2}/setup.py +0 -0
@@ -49,7 +49,7 @@ Thanks goes to these wonderful people (`emoji key <https://allcontributors.org/d
49
49
  </tr>
50
50
  <tr>
51
51
  <td align="center"><a href="https://github.com/JessicaS11"><img src="https://avatars.githubusercontent.com/u/11756442?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Jessica Scheick</b></sub></a><br /><a href="https://github.com/corteva/rioxarray/commits?author=JessicaS11" title="Documentation">📖</a></td>
52
- <td align="center"><a href="https://www.linkedin.com/in/micheleclaus/"><img src="https://avatars.githubusercontent.com/u/31700619?v=4?s=100" width="100px;" alt=""/><br /><sub><b>clausmichele</b></sub></a><br /><a href="https://github.com/corteva/rioxarray/pulls?q=is%3Apr+reviewed-by%3Aclausmichele" title="Reviewed Pull Requests">👀</a></td>
52
+ <td align="center"><a href="https://www.linkedin.com/in/micheleclaus/"><img src="https://avatars.githubusercontent.com/u/31700619?v=4?s=100" width="100px;" alt=""/><br /><sub><b>clausmichele</b></sub></a><br /><a href="https://github.com/corteva/rioxarray/pulls?q=is%3Apr+reviewed-by%3Aclausmichele" title="Reviewed Pull Requests">👀</a> <a href="https://github.com/corteva/rioxarray/commits?author=clausmichele" title="Documentation">📖</a></td>
53
53
  <td align="center"><a href="https://github.com/caldwellst"><img src="https://avatars.githubusercontent.com/u/8086547?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Seth Caldwell</b></sub></a><br /><a href="https://github.com/corteva/rioxarray/issues?q=author%3Acaldwellst" title="Bug reports">🐛</a> <a href="https://github.com/corteva/rioxarray/commits?author=caldwellst" title="Code">💻</a></td>
54
54
  <td align="center"><a href="https://github.com/stefank0"><img src="https://avatars.githubusercontent.com/u/32932217?v=4?s=100" width="100px;" alt=""/><br /><sub><b>stefank0</b></sub></a><br /><a href="https://github.com/corteva/rioxarray/commits?author=stefank0" title="Documentation">📖</a></td>
55
55
  <td align="center"><a href="https://itcarroll.github.io/"><img src="https://avatars.githubusercontent.com/u/3383837?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Ian Carroll</b></sub></a><br /><a href="#maintenance-itcarroll" title="Maintenance">🚧</a></td>
@@ -59,6 +59,11 @@ Thanks goes to these wonderful people (`emoji key <https://allcontributors.org/d
59
59
  <tr>
60
60
  <td align="center"><a href="https://github.com/xaviernogueira"><img src="https://avatars.githubusercontent.com/u/58796351?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Xavier Nogueira</b></sub></a><br /><a href="https://github.com/corteva/rioxarray/issues?q=author%3Axaviernogueira" title="Bug reports">🐛</a></td>
61
61
  <td align="center"><a href="https://github.com/valanm22"><img src="https://avatars.githubusercontent.com/u/84893551?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Valan Baptist Mathuranayagam</b></sub></a><br /><a href="https://github.com/corteva/rioxarray/commits?author=valanm22" title="Documentation">📖</a></td>
62
+ <td align="center"><a href="https://github.com/peterm790"><img src="https://avatars.githubusercontent.com/u/52179978?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Peter Marsh</b></sub></a><br /><a href="https://github.com/corteva/rioxarray/commits?author=peterm790" title="Code">💻</a> <a href="https://github.com/corteva/rioxarray/commits?author=peterm790" title="Tests">⚠️</a></td>
63
+ <td align="center"><a href="https://github.com/dluks"><img src="https://avatars.githubusercontent.com/u/4911680?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Daniel Lusk</b></sub></a><br /><a href="https://github.com/corteva/rioxarray/commits?author=dluks" title="Code">💻</a> <a href="https://github.com/corteva/rioxarray/commits?author=dluks" title="Documentation">📖</a></td>
64
+ <td align="center"><a href="https://github.com/DahnJ"><img src="https://avatars.githubusercontent.com/u/18722560?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Daniel Jahn (dahn)</b></sub></a><br /><a href="https://github.com/corteva/rioxarray/commits?author=DahnJ" title="Documentation">📖</a></td>
65
+ <td align="center"><a href="https://phofl.github.io/"><img src="https://avatars.githubusercontent.com/u/61934744?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Patrick Hoefler</b></sub></a><br /><a href="https://github.com/corteva/rioxarray/issues?q=author%3Aphofl" title="Bug reports">🐛</a></td>
66
+ <td align="center"><a href="https://github.com/dzanaga"><img src="https://avatars.githubusercontent.com/u/8113766?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Daniele Zanaga</b></sub></a><br /><a href="https://github.com/corteva/rioxarray/commits?author=dzanaga" title="Documentation">📖</a></td>
62
67
  </tr>
63
68
  </table>
64
69
 
@@ -78,9 +78,9 @@ Using python::
78
78
  $ python -m venv venv
79
79
  $ . venv/bin/activate
80
80
 
81
- 4. Install your local copy into a virtualenv.
81
+ 4. Install your local copy into a virtualenv::
82
82
 
83
- $ python -m pip install -e .[all]
83
+ $ python -m pip install -e ".[all]"
84
84
  $ python -m pip install -r requirements/dev.txt
85
85
 
86
86
  5. Setup pre-commit hooks::
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.2
2
2
  Name: rioxarray
3
- Version: 0.15.3.dev0
3
+ Version: 0.18.2
4
4
  Summary: geospatial xarray extension powered by rasterio
5
5
  Maintainer: rioxarray Contributors
6
6
  License: Apache
@@ -19,6 +19,7 @@ Classifier: Programming Language :: Python
19
19
  Classifier: Programming Language :: Python :: 3.10
20
20
  Classifier: Programming Language :: Python :: 3.11
21
21
  Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
22
23
  Classifier: Programming Language :: Python :: 3
23
24
  Classifier: Topic :: Software Development :: Libraries :: Python Modules
24
25
  Classifier: Typing :: Typed
@@ -29,8 +30,8 @@ License-File: LICENSE_datacube
29
30
  License-File: LICENSE_xarray
30
31
  License-File: AUTHORS.rst
31
32
  Requires-Dist: packaging
32
- Requires-Dist: rasterio>=1.3
33
- Requires-Dist: xarray>=2022.3.0
33
+ Requires-Dist: rasterio>=1.3.7
34
+ Requires-Dist: xarray>=2024.7.0
34
35
  Requires-Dist: pyproj>=3.3
35
36
  Requires-Dist: numpy>=1.23
36
37
  Provides-Extra: interp
@@ -49,7 +50,7 @@ rasterio xarray extension.
49
50
  :alt: Join the chat at https://gitter.im/rioxarray/community
50
51
  :target: https://gitter.im/rioxarray/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge
51
52
 
52
- .. image:: https://img.shields.io/badge/all_contributors-37-orange.svg?style=flat-square
53
+ .. image:: https://img.shields.io/badge/all_contributors-42-orange.svg?style=flat-square
53
54
  :alt: All Contributors
54
55
  :target: https://github.com/corteva/rioxarray/blob/master/AUTHORS.rst
55
56
 
@@ -9,7 +9,7 @@ rasterio xarray extension.
9
9
  :alt: Join the chat at https://gitter.im/rioxarray/community
10
10
  :target: https://gitter.im/rioxarray/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge
11
11
 
12
- .. image:: https://img.shields.io/badge/all_contributors-37-orange.svg?style=flat-square
12
+ .. image:: https://img.shields.io/badge/all_contributors-42-orange.svg?style=flat-square
13
13
  :alt: All Contributors
14
14
  :target: https://github.com/corteva/rioxarray/blob/master/AUTHORS.rst
15
15
 
@@ -4,7 +4,7 @@ requires = ["setuptools", "wheel"]
4
4
 
5
5
  [project]
6
6
  name = "rioxarray"
7
- version = "0.15.3.dev0"
7
+ version = "0.18.2"
8
8
  description = "geospatial xarray extension powered by rasterio"
9
9
  maintainers = [
10
10
  {name = "rioxarray Contributors"},
@@ -27,6 +27,7 @@ classifiers = [
27
27
  "Programming Language :: Python :: 3.10",
28
28
  "Programming Language :: Python :: 3.11",
29
29
  "Programming Language :: Python :: 3.12",
30
+ "Programming Language :: Python :: 3.13",
30
31
  "Programming Language :: Python :: 3",
31
32
  "Topic :: Software Development :: Libraries :: Python Modules",
32
33
  "Typing :: Typed",
@@ -34,8 +35,8 @@ classifiers = [
34
35
  requires-python = ">=3.10"
35
36
  dependencies = [
36
37
  "packaging",
37
- "rasterio>=1.3",
38
- "xarray>=2022.3.0",
38
+ "rasterio>=1.3.7",
39
+ "xarray>=2024.7.0",
39
40
  "pyproj>=3.3",
40
41
  "numpy>=1.23",
41
42
  ]
@@ -7,7 +7,6 @@ Source file: https://github.com/pydata/xarray/blob/1d7bcbdc75b6d556c04e2c7d7a042
7
7
  """
8
8
  # pylint: disable=too-many-lines
9
9
  import contextlib
10
- import functools
11
10
  import importlib.metadata
12
11
  import os
13
12
  import re
@@ -145,7 +144,11 @@ class SingleBandDatasetReader:
145
144
  """
146
145
  read data for the band
147
146
  """
148
- return self._riods.read(indexes=self._bidx + 1, **kwargs)
147
+ if numpy.isscalar(indexes):
148
+ indexes = self._bidx + 1
149
+ else:
150
+ indexes = [self._bidx + 1]
151
+ return self._riods.read(indexes=indexes, **kwargs)
149
152
 
150
153
  def tags(self, bidx=None, **kwargs): # pylint: disable=unused-argument
151
154
  """
@@ -292,6 +295,7 @@ class RasterioArrayWrapper(BackendArray):
292
295
 
293
296
  def __init__(
294
297
  self,
298
+ *,
295
299
  manager,
296
300
  lock,
297
301
  name,
@@ -309,7 +313,6 @@ class RasterioArrayWrapper(BackendArray):
309
313
  riods = _ensure_warped_vrt(manager.acquire(), vrt_params)
310
314
  self.vrt_params = vrt_params
311
315
  self._shape = (riods.count, riods.height, riods.width)
312
-
313
316
  self._dtype = None
314
317
  self._unsigned_dtype = None
315
318
  self._fill_value = riods.nodata
@@ -325,7 +328,7 @@ class RasterioArrayWrapper(BackendArray):
325
328
  )
326
329
  if self._unsigned_dtype is not None and self._fill_value is not None:
327
330
  self._fill_value = self._unsigned_dtype.type(self._fill_value)
328
- if self._unsigned_dtype is None and dtype.kind not in ("i", "u"):
331
+ if self._unsigned_dtype is None:
329
332
  warnings.warn(
330
333
  f"variable {name!r} has _Unsigned attribute but is not "
331
334
  "of integer type. Ignoring attribute.",
@@ -510,7 +513,7 @@ def _to_numeric(value: Any) -> float:
510
513
  return value
511
514
 
512
515
 
513
- def _parse_tag(key: str, value: Any) -> tuple[str, Any]:
516
+ def _parse_tag(*, key: str, value: Any) -> tuple[str, Any]:
514
517
  # NC_GLOBAL is appended to tags with netcdf driver and is not really needed
515
518
  key = key.split("NC_GLOBAL#")[-1]
516
519
  if value.startswith("{") and value.endswith("}"):
@@ -528,7 +531,7 @@ def _parse_tag(key: str, value: Any) -> tuple[str, Any]:
528
531
  def _parse_tags(tags: dict) -> dict:
529
532
  parsed_tags = {}
530
533
  for key, value in tags.items():
531
- key, value = _parse_tag(key, value)
534
+ key, value = _parse_tag(key=key, value=value)
532
535
  parsed_tags[key] = value
533
536
  return parsed_tags
534
537
 
@@ -550,7 +553,7 @@ NETCDF_DTYPE_MAP = {
550
553
  }
551
554
 
552
555
 
553
- def _load_netcdf_attrs(tags: dict, data_array: DataArray) -> None:
556
+ def _load_netcdf_attrs(*, tags: dict, data_array: DataArray) -> None:
554
557
  """
555
558
  Loads the netCDF attributes into the data array
556
559
 
@@ -558,7 +561,7 @@ def _load_netcdf_attrs(tags: dict, data_array: DataArray) -> None:
558
561
  - variable_name#attr_name: attr_value
559
562
  """
560
563
  for key, value in tags.items():
561
- key, value = _parse_tag(key, value)
564
+ key, value = _parse_tag(key=key, value=value)
562
565
  key_split = key.split("#")
563
566
  if len(key_split) != 2:
564
567
  continue
@@ -567,7 +570,7 @@ def _load_netcdf_attrs(tags: dict, data_array: DataArray) -> None:
567
570
  data_array.coords[variable_name].attrs.update({attr_name: value})
568
571
 
569
572
 
570
- def _parse_netcdf_attr_array(attr: Union[NDArray, str], dtype=None) -> NDArray:
573
+ def _parse_netcdf_attr_array(attr: Union[NDArray, str], *, dtype=None) -> NDArray:
571
574
  """
572
575
  Expected format: '{2,6}' or '[2. 6.]'
573
576
  """
@@ -667,7 +670,7 @@ def _get_rasterio_attrs(riods: RasterioReader):
667
670
  if len(set(riods.scales)) > 1:
668
671
  attrs["scales"] = riods.scales
669
672
  warnings.warn(
670
- "Offsets differ across bands. The 'scale_factor' attribute will "
673
+ "Scales differ across bands. The 'scale_factor' attribute will "
671
674
  "not be added. See the 'scales' attribute."
672
675
  )
673
676
  else:
@@ -773,7 +776,7 @@ def _pop_global_netcdf_attrs_from_vars(dataset_to_clean: Dataset) -> Dataset:
773
776
 
774
777
 
775
778
  def _subdataset_groups_to_dataset(
776
- dim_groups: dict[Hashable, dict[Hashable, DataArray]], global_tags: dict
779
+ *, dim_groups: dict[Hashable, dict[Hashable, DataArray]], global_tags: dict
777
780
  ) -> Union[Dataset, list[Dataset]]:
778
781
  if dim_groups:
779
782
  dataset: Union[Dataset, list[Dataset]] = []
@@ -798,6 +801,7 @@ def _subdataset_groups_to_dataset(
798
801
 
799
802
  def _load_subdatasets(
800
803
  riods: RasterioReader,
804
+ *,
801
805
  group: Optional[Union[str, list[str], tuple[str, ...]]],
802
806
  variable: Optional[Union[str, list[str], tuple[str, ...]]],
803
807
  parse_coordinates: bool,
@@ -843,6 +847,7 @@ def _load_subdatasets(
843
847
 
844
848
  def _load_bands_as_variables(
845
849
  riods: RasterioReader,
850
+ *,
846
851
  parse_coordinates: bool,
847
852
  chunks: Optional[Union[int, tuple, dict]],
848
853
  cache: Optional[bool],
@@ -894,10 +899,12 @@ def _load_bands_as_variables(
894
899
 
895
900
 
896
901
  def _prepare_dask(
902
+ *,
897
903
  result: DataArray,
898
904
  riods: RasterioReader,
899
905
  filename: Union[str, os.PathLike],
900
906
  chunks: Union[int, tuple, dict],
907
+ bidx: Optional[int] = None,
901
908
  ) -> DataArray:
902
909
  """
903
910
  Prepare the data for dask computations
@@ -922,14 +929,18 @@ def _prepare_dask(
922
929
  chunks=(1, "auto", "auto"),
923
930
  shape=(riods.count, riods.height, riods.width),
924
931
  dtype=_rasterio_to_numpy_dtype(riods.dtypes),
925
- previous_chunks=tuple((c,) for c in block_shape),
932
+ previous_chunks=block_shape,
926
933
  )
927
- token = tokenize(filename, mtime, chunks)
934
+ token_filename = filename
935
+ if bidx is not None:
936
+ token_filename = f"{filename}-{bidx}"
937
+ token = tokenize(token_filename, mtime, chunks)
928
938
  name_prefix = f"open_rasterio-{token}"
929
939
  return result.chunk(chunks, name_prefix=name_prefix, token=token)
930
940
 
931
941
 
932
942
  def _handle_encoding(
943
+ *,
933
944
  result: DataArray,
934
945
  mask_and_scale: bool,
935
946
  masked: bool,
@@ -946,8 +957,12 @@ def _handle_encoding(
946
957
  variables.pop_to(
947
958
  result.attrs, result.encoding, "scale_factor", name=da_name
948
959
  )
960
+ if "scales" in result.attrs:
961
+ variables.pop_to(result.attrs, result.encoding, "scales", name=da_name)
949
962
  if "add_offset" in result.attrs:
950
963
  variables.pop_to(result.attrs, result.encoding, "add_offset", name=da_name)
964
+ if "offsets" in result.attrs:
965
+ variables.pop_to(result.attrs, result.encoding, "offsets", name=da_name)
951
966
  if masked:
952
967
  if "_FillValue" in result.attrs:
953
968
  variables.pop_to(result.attrs, result.encoding, "_FillValue", name=da_name)
@@ -985,6 +1000,7 @@ def open_rasterio(
985
1000
  rasterio.vrt.WarpedVRT,
986
1001
  SingleBandDatasetReader,
987
1002
  ],
1003
+ *,
988
1004
  parse_coordinates: Optional[bool] = None,
989
1005
  chunks: Optional[Union[int, tuple, dict]] = None,
990
1006
  cache: Optional[bool] = None,
@@ -1004,10 +1020,7 @@ def open_rasterio(
1004
1020
 
1005
1021
  This should work with any file that rasterio can open (most often:
1006
1022
  geoTIFF). The x and y coordinates are generated automatically from the
1007
- file's geoinformation, shifted to the center of each pixel (see
1008
- `"PixelIsArea" Raster Space
1009
- <http://web.archive.org/web/20160326194152/http://remotesensing.org/geotiff/spec/geotiff2.5.html#2.5.2>`_
1010
- for more information).
1023
+ file's geoinformation and refer to the center of the pixel.
1011
1024
 
1012
1025
  .. versionadded:: 0.13 band_as_variable
1013
1026
 
@@ -1080,10 +1093,8 @@ def open_rasterio(
1080
1093
  vrt_params = None
1081
1094
  file_opener = rasterio.open
1082
1095
  if isinstance(filename, SingleBandDatasetReader):
1083
- file_opener = functools.partial(
1084
- _single_band_open,
1085
- bidx=filename._bidx,
1086
- )
1096
+ file_opener = _single_band_open
1097
+ open_kwargs.update(bidx=filename._bidx)
1087
1098
  vrt_params = filename._vrt_params
1088
1099
  if isinstance(filename, (rasterio.io.DatasetReader, SingleBandDatasetReader)):
1089
1100
  filename = filename.name
@@ -1202,7 +1213,9 @@ def open_rasterio(
1202
1213
  # Get geospatial coordinates
1203
1214
  if parse_coordinates:
1204
1215
  coords.update(
1205
- _generate_spatial_coords(riods.transform, riods.width, riods.height)
1216
+ _generate_spatial_coords(
1217
+ affine=riods.transform, width=riods.width, height=riods.height
1218
+ )
1206
1219
  )
1207
1220
 
1208
1221
  unsigned = None
@@ -1216,8 +1229,8 @@ def open_rasterio(
1216
1229
  da_name = attrs.pop("NETCDF_VARNAME", default_name)
1217
1230
  data: Any = indexing.LazilyOuterIndexedArray(
1218
1231
  RasterioArrayWrapper(
1219
- manager,
1220
- lock,
1232
+ manager=manager,
1233
+ lock=lock,
1221
1234
  name=da_name,
1222
1235
  vrt_params=vrt_params,
1223
1236
  masked=masked,
@@ -1237,7 +1250,7 @@ def open_rasterio(
1237
1250
  result.encoding = encoding
1238
1251
 
1239
1252
  # update attributes from NetCDF attributes
1240
- _load_netcdf_attrs(riods.tags(), result)
1253
+ _load_netcdf_attrs(tags=riods.tags(), data_array=result)
1241
1254
  result = _decode_datetime_cf(
1242
1255
  result, decode_times=decode_times, decode_timedelta=decode_timedelta
1243
1256
  )
@@ -1247,7 +1260,13 @@ def open_rasterio(
1247
1260
  result.attrs["_FillValue"] = result.dtype.type(result.attrs["_FillValue"])
1248
1261
 
1249
1262
  # handle encoding
1250
- _handle_encoding(result, mask_and_scale, masked, da_name, unsigned=unsigned)
1263
+ _handle_encoding(
1264
+ result=result,
1265
+ mask_and_scale=mask_and_scale,
1266
+ masked=masked,
1267
+ da_name=da_name,
1268
+ unsigned=unsigned,
1269
+ )
1251
1270
  # Affine transformation matrix (always available)
1252
1271
  # This describes coefficients mapping pixel coordinates to CRS
1253
1272
  # For serialization store as tuple of 6 floats, the last row being
@@ -1261,7 +1280,13 @@ def open_rasterio(
1261
1280
  result.rio.write_gcps(*riods.gcps, inplace=True)
1262
1281
 
1263
1282
  if chunks is not None:
1264
- result = _prepare_dask(result, riods, filename, chunks)
1283
+ result = _prepare_dask(
1284
+ result=result,
1285
+ riods=riods,
1286
+ filename=filename,
1287
+ chunks=chunks,
1288
+ bidx=open_kwargs.get("bidx"),
1289
+ )
1265
1290
  else:
1266
1291
  result.encoding["preferred_chunks"] = {
1267
1292
  result.rio.y_dim: riods.block_shapes[0][0],
@@ -2,7 +2,6 @@
2
2
  This module allows you to merge xarray Datasets/DataArrays
3
3
  geospatially with the `rasterio.merge` module.
4
4
  """
5
-
6
5
  from collections.abc import Sequence
7
6
  from typing import Callable, Optional, Union
8
7
 
@@ -12,7 +11,8 @@ from rasterio.io import MemoryFile
12
11
  from rasterio.merge import merge as _rio_merge
13
12
  from xarray import DataArray, Dataset
14
13
 
15
- from rioxarray.rioxarray import _get_nonspatial_coords, _make_coords
14
+ from rioxarray._io import open_rasterio
15
+ from rioxarray.rioxarray import _get_nonspatial_coords
16
16
 
17
17
 
18
18
  class RasterioDatasetDuck:
@@ -31,13 +31,29 @@ class RasterioDatasetDuck:
31
31
  self.count = int(xds.rio.count)
32
32
  self.dtypes = [xds.dtype]
33
33
  self.name = xds.name
34
- self.nodatavals = [xds.rio.nodata]
34
+ if xds.rio.encoded_nodata is not None:
35
+ self.nodatavals = [xds.rio.encoded_nodata]
36
+ else:
37
+ self.nodatavals = [xds.rio.nodata]
35
38
  res = xds.rio.resolution(recalc=True)
36
39
  self.res = (abs(res[0]), abs(res[1]))
37
40
  self.transform = xds.rio.transform(recalc=True)
38
- # profile is only used for writing to a file.
39
- # This never happens with rioxarray merge.
40
- self.profile: dict = {}
41
+ self.profile: dict = {
42
+ "crs": self.crs,
43
+ "nodata": self.nodatavals[0],
44
+ }
45
+ valid_scale_factor = self._xds.encoding.get("scale_factor", 1) != 1 or any(
46
+ scale != 1 for scale in self._xds.encoding.get("scales", (1,))
47
+ )
48
+ valid_offset = self._xds.encoding.get("add_offset", 0.0) != 0 or any(
49
+ offset != 0 for offset in self._xds.encoding.get("offsets", (0,))
50
+ )
51
+ self._mask_and_scale = (
52
+ self._xds.rio.encoded_nodata is not None
53
+ or valid_scale_factor
54
+ or valid_offset
55
+ or self._xds.encoding.get("_Unsigned") is not None
56
+ )
41
57
 
42
58
  def colormap(self, *args, **kwargs) -> None:
43
59
  """
@@ -52,26 +68,21 @@ class RasterioDatasetDuck:
52
68
  This method is meant to be used by the rasterio.merge.merge function.
53
69
  """
54
70
  with MemoryFile() as memfile:
55
- with memfile.open(
56
- driver="GTiff",
57
- height=int(self._xds.rio.height),
58
- width=int(self._xds.rio.width),
59
- count=self.count,
60
- dtype=self.dtypes[0],
61
- crs=self.crs,
62
- transform=self.transform,
63
- nodata=self.nodatavals[0],
64
- ) as dataset:
65
- data = self._xds.values
66
- if data.ndim == 2:
67
- dataset.write(data, 1)
68
- else:
69
- dataset.write(data)
70
- return dataset.read(*args, **kwargs)
71
+ self._xds.rio.to_raster(memfile.name)
72
+ with memfile.open() as dataset:
73
+ if self._mask_and_scale:
74
+ kwargs["masked"] = True
75
+ out = dataset.read(*args, **kwargs)
76
+ if self._mask_and_scale:
77
+ out = out.astype(self._xds.dtype)
78
+ for iii in range(self.count):
79
+ out[iii] = out[iii] * dataset.scales[iii] + dataset.offsets[iii]
80
+ return out
71
81
 
72
82
 
73
83
  def merge_arrays(
74
84
  dataarrays: Sequence[DataArray],
85
+ *,
75
86
  bounds: Optional[tuple] = None,
76
87
  res: Optional[tuple] = None,
77
88
  nodata: Optional[float] = None,
@@ -90,7 +101,7 @@ def merge_arrays(
90
101
  Parameters
91
102
  ----------
92
103
  dataarrays: list[xarray.DataArray]
93
- List of xarray.DataArray's with all geo attributes.
104
+ List of multiple xarray.DataArray with all geo attributes.
94
105
  The first one is assumed to have the same
95
106
  CRS, dtype, and dimensions as the others in the array.
96
107
  bounds: tuple, optional
@@ -144,45 +155,52 @@ def merge_arrays(
144
155
  rioduckarrays.append(RasterioDatasetDuck(dataarray))
145
156
 
146
157
  # use rasterio to merge
147
- merged_data, merged_transform = _rio_merge(
148
- rioduckarrays,
149
- **{key: val for key, val in input_kwargs.items() if val is not None},
150
- )
151
158
  # generate merged data array
152
159
  representative_array = rioduckarrays[0]._xds
153
- if parse_coordinates:
154
- coords = _make_coords(
155
- representative_array,
156
- merged_transform,
157
- merged_data.shape[-1],
158
- merged_data.shape[-2],
160
+ with MemoryFile() as memfile:
161
+ _rio_merge(
162
+ rioduckarrays,
163
+ **{key: val for key, val in input_kwargs.items() if val is not None},
164
+ dst_path=memfile.name,
159
165
  )
160
- else:
161
- coords = _get_nonspatial_coords(representative_array)
162
-
163
- # make sure the output merged data shape is 2D if the
164
- # original data was 2D. this can happen if the
165
- # xarray datasarray was squeezed.
166
- if len(merged_data.shape) == 3 and len(representative_array.shape) == 2:
167
- merged_data = merged_data.squeeze()
168
-
169
- xda = DataArray(
170
- name=representative_array.name,
171
- data=merged_data,
172
- coords=coords,
173
- dims=tuple(representative_array.dims),
174
- attrs=representative_array.attrs,
175
- )
176
- xda.rio.write_nodata(
177
- nodata if nodata is not None else representative_array.rio.nodata, inplace=True
178
- )
179
- xda.rio.write_crs(representative_array.rio.crs, inplace=True)
180
- xda.rio.write_transform(merged_transform, inplace=True)
181
- return xda
166
+ with open_rasterio( # type: ignore
167
+ memfile.name,
168
+ parse_coordinates=parse_coordinates,
169
+ mask_and_scale=rioduckarrays[0]._mask_and_scale,
170
+ ) as merged_data:
171
+ merged_data = merged_data.load()
172
+
173
+ # make sure old & new coorinate names match & dimensions are correct
174
+ rename_map = {}
175
+ original_extra_dim = representative_array.rio._check_dimensions()
176
+ new_extra_dim = merged_data.rio._check_dimensions()
177
+ # make sure the output merged data shape is 2D if the
178
+ # original data was 2D. this can happen if the
179
+ # xarray datasarray was squeezed.
180
+ if len(merged_data.shape) == 3 and len(representative_array.shape) == 2:
181
+ merged_data = merged_data.squeeze(
182
+ dim=new_extra_dim, drop=original_extra_dim is None
183
+ )
184
+ new_extra_dim = merged_data.rio._check_dimensions()
185
+ if (
186
+ original_extra_dim is not None
187
+ and new_extra_dim is not None
188
+ and original_extra_dim != new_extra_dim
189
+ ):
190
+ rename_map[new_extra_dim] = original_extra_dim
191
+ if representative_array.rio.x_dim != merged_data.rio.x_dim:
192
+ rename_map[merged_data.rio.x_dim] = representative_array.rio.x_dim
193
+ if representative_array.rio.y_dim != merged_data.rio.y_dim:
194
+ rename_map[merged_data.rio.y_dim] = representative_array.rio.y_dim
195
+ if rename_map:
196
+ merged_data = merged_data.rename(rename_map)
197
+ merged_data.coords.update(_get_nonspatial_coords(representative_array))
198
+ return merged_data # type: ignore
182
199
 
183
200
 
184
201
  def merge_datasets(
185
202
  datasets: Sequence[Dataset],
203
+ *,
186
204
  bounds: Optional[tuple] = None,
187
205
  res: Optional[tuple] = None,
188
206
  nodata: Optional[float] = None,
@@ -200,7 +218,7 @@ def merge_datasets(
200
218
  Parameters
201
219
  ----------
202
220
  datasets: list[xarray.Dataset]
203
- List of xarray.Dataset's with all geo attributes.
221
+ List of multiple xarray.Dataset with all geo attributes.
204
222
  The first one is assumed to have the same
205
223
  CRS, dtype, dimensions, and data_vars as the others in the array.
206
224
  bounds: tuple, optional
@@ -228,7 +246,7 @@ def merge_datasets(
228
246
 
229
247
  representative_ds = datasets[0]
230
248
  merged_data = {}
231
- for data_var in representative_ds.data_vars:
249
+ for iii, data_var in enumerate(representative_ds.data_vars):
232
250
  merged_data[data_var] = merge_arrays(
233
251
  [dataset[data_var] for dataset in datasets],
234
252
  bounds=bounds,
@@ -237,18 +255,11 @@ def merge_datasets(
237
255
  precision=precision,
238
256
  method=method,
239
257
  crs=crs,
240
- parse_coordinates=False,
258
+ parse_coordinates=iii == 0,
241
259
  )
242
260
  data_var = list(representative_ds.data_vars)[0]
243
261
  xds = Dataset(
244
262
  merged_data,
245
- coords=_make_coords(
246
- merged_data[data_var],
247
- merged_data[data_var].rio.transform(),
248
- merged_data[data_var].shape[-1],
249
- merged_data[data_var].shape[-2],
250
- force_generate=True,
251
- ),
252
263
  attrs=representative_ds.attrs,
253
264
  )
254
265
  xds.rio.write_crs(merged_data[data_var].rio.crs, inplace=True)