Repository: dlr-eoc/ukis-pysat

Issue:
Add nbits option to write_to_file
The GeoTIFF specific nbits option allows to create a file with less than 8 bits per sample by passing a value from 1 to 7. This becomes particularly useful when writing binary masks as it can save significant disk memory. Related to #46 Therefore, suggest to add this option to the write_to_file method.

Discussion:
codecov-commenter: # [Codecov](https://codecov.io/gh/dlr-eoc/ukis-pysat/pull/75?src=pr&el=h1) Report
> Merging [#75](https://codecov.io/gh/dlr-eoc/ukis-pysat/pull/75?src=pr&el=desc) into [master](https://codecov.io/gh/dlr-eoc/ukis-pysat/commit/7c0df7351299c1e94cf2c5b4f8ab69295121d709&el=desc) will **increase** coverage by `0.07%`.
> The diff coverage is `100.00%`.

[![Impacted file tree graph](https://codecov.io/gh/dlr-eoc/ukis-pysat/pull/75/graphs/tree.svg?width=650&height=150&src=pr&token=6LYPGRGMXV)](https://codecov.io/gh/dlr-eoc/ukis-pysat/pull/75?src=pr&el=tree)

```diff
@@            Coverage Diff             @@
##           master      #75      +/-   ##
==========================================
+ Coverage   93.16%   93.23%   +0.07%     
==========================================
  Files           8        8              
  Lines         746      754       +8     
==========================================
+ Hits          695      703       +8     
  Misses         51       51              
```

| Flag | Coverage Δ | |
|---|---|---|
| #unittests | `93.23% <100.00%> (+0.07%)` | :arrow_up: |

Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags#carryforward-flags-in-the-pull-request-comment) to find out more.

| [Impacted Files](https://codecov.io/gh/dlr-eoc/ukis-pysat/pull/75?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [tests/test\_raster.py](https://codecov.io/gh/dlr-eoc/ukis-pysat/pull/75/diff?src=pr&el=tree#diff-dGVzdHMvdGVzdF9yYXN0ZXIucHk=) | `99.36% <100.00%> (+0.02%)` | :arrow_up: |
| [ukis\_pysat/raster.py](https://codecov.io/gh/dlr-eoc/ukis-pysat/pull/75/diff?src=pr&el=tree#diff-dWtpc19weXNhdC9yYXN0ZXIucHk=) | `92.94% <100.00%> (+0.08%)` | :arrow_up: |

------

[Continue to review full report at Codecov](https://codecov.io/gh/dlr-eoc/ukis-pysat/pull/75?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/dlr-eoc/ukis-pysat/pull/75?src=pr&el=footer). Last update [7c0df73...e8ba487](https://codecov.io/gh/dlr-eoc/ukis-pysat/pull/75?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).

MWieland: solved it with kwargs instead of hardcoding nbits. this way we can pass any driver specific arguments to the method (e.g., TILED or NBITS for GeoTiff or WRITE_BOTTOMUP for NetCDF)

Patch:
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index e34dfcf..981d100 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -20,6 +20,7 @@ Added
 - ``raster.Image()``: With Statement Context Manager for Image #45
 - ``raster.Image()``: Alter image array #67
 - ``raster.Image()``: Target align option for `warp()` #60
+- ``raster.Image()``: Pass driver specific kwargs to `write_to_file()` #74
 
 Fixed
 *****
diff --git a/ukis_pysat/raster.py b/ukis_pysat/raster.py
index c4b3176..d23ca93 100644
--- a/ukis_pysat/raster.py
+++ b/ukis_pysat/raster.py
@@ -414,7 +414,7 @@ class Image:
         self.da_arr = da.from_array(self.__arr, chunks=chunk_size)
         return self.da_arr
 
-    def write_to_file(self, path_to_file, dtype, driver="GTiff", nodata=None, compress=None):
+    def write_to_file(self, path_to_file, dtype, driver="GTiff", nodata=None, compress=None, kwargs=None):
         """
         Write a dataset to file.
         :param path_to_file: str, path to new file
@@ -423,6 +423,8 @@ class Image:
         :param driver: str, optional (default: 'GTiff')
         :param nodata: nodata value, e.g. 255 (default: None, means nodata value of dataset will be used)
         :param compress: compression, e.g. 'lzw' (default: None)
+        :param kwargs: driver specific keyword arguments, e.g. {'nbits': 1, 'tiled': True} for GTiff (default: None)
+            for more keyword arguments see gdal driver specifications, e.g. https://gdal.org/drivers/raster/gtiff.html
         """
         if type(dtype) == str and dtype == "min":
             dtype = get_minimum_dtype(self.__arr)
@@ -445,6 +447,9 @@ class Image:
         if compress:
             profile.update({"compress": compress})
 
+        if kwargs:
+            profile.update(**kwargs)
+
         with rasterio.open(path_to_file, "w", **profile) as dst:
             dst.write(self.__arr.astype(dtype))
 


Test patch:
diff --git a/tests/test_raster.py b/tests/test_raster.py
index 1f65f72..7ee6eeb 100644
--- a/tests/test_raster.py
+++ b/tests/test_raster.py
@@ -278,6 +278,14 @@ class DataTest(unittest.TestCase):
         img2.close()
         os.remove(r"result.tif")
 
+        self.img.write_to_file(r"result.tif", np.uint8, compress="packbits", kwargs={"tiled": True})
+        img2 = Image("result.tif")
+        self.assertEqual(img2.arr.dtype, "uint8")
+        self.assertEqual(img2.dataset.profile["tiled"], True)
+
+        img2.close()
+        os.remove(r"result.tif")
+
         img3 = Image(self.img.arr, crs=self.img.dataset.crs, transform=self.img.dataset.transform)
         img3.write_to_file(r"result.tif", np.uint16)
         img3.close()