Repository: dlr-eoc/ukis-pysat

Issue:
Add array setter
Instancing an Image object with `self.img = ukis_pysat.raster.Image(self.path_to_img)` gives access to attributes of the Image class, e.g. `self.img.arr`.

At some point it is desired to alter `self.img.arr`. However, `self.img.arr = self.img.arr * 10` fails with an `AttrbiuteError`.

Suggest to extend the property decorator. Current implementation is:
```
@property
def arr(self):
    """array property"""
    if self.dimorder == "first":
        return self.__arr
    else:
        return reshape_as_image(self.__arr)
```

This could be extended with:
```
@arr.setter
def arr(self, value):
    self.__arr = value
```


Discussion:
fwfichtner: How do we handle multiple bands, is this logical?

Patch:
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index 31780cb..a3660a0 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -17,20 +17,21 @@ something was changed
 ----------------------
 Added
 *****
-- `raster.Image()``: With Statement Context Manager for Image #45
+- ``raster.Image()``: With Statement Context Manager for Image #45
+- ``raster.Image()``: Alter image array #67
 
 Changed
 *******
-- `data.Metadata()``: Corrected field types #58
-- `data.MetadataCollection()``: Improved plotting of MetadataCollection to_pandas method #56
-- `data.MetadataCollection()``: Made filter method more flexible with list and fuzzy filter options #55
+- ``data.Metadata()``: Corrected field types #58
+- ``data.MetadataCollection()``: Improved plotting of MetadataCollection to_pandas method #56
+- ``data.MetadataCollection()``: Made filter method more flexible with list and fuzzy filter options #55
 
 [0.5.0]  (2020-07-03)
 ----------------------
 
 Added
 *****
-- `raster.Image()``: optional nodata value for writing #32
+- ``raster.Image()``: optional nodata value for writing #32
 
 Fixed
 *****
@@ -51,7 +52,7 @@ Added
 *****
 - ``raster.Image()``: expanded test_arr to test AttributeError #31
 - ``raster.Image()``: optional dimorder for arr and according test #31
-- `dn2toa` tests and testfiles #17
+- ``dn2toa()`` tests and testfiles #17
 - ``data.source()``: accept WKT string as AOI #26
 - ``data.source()``: check if an AOI string is a file or a WKT string #26
 
diff --git a/docs/index.rst b/docs/index.rst
index c21821f..f0e152a 100644
--- a/docs/index.rst
+++ b/docs/index.rst
@@ -44,9 +44,23 @@ The UKIS-pysat package provides generic classes and functions to query, access a
 
   # get sentinel scene from directory
   with get_sentinel_scene_from_dir(target_dir) as (full_path, ident):
+      # initialize an image object
+      # keep the dimension order in mind (order of channels or bands)
       img = Image(os.path_testfiles.join(full_path, 'pre_nrcs.tif'))
 
+      # scale the image array, having one band
+      img.arr = img.arr * 0.3
 
+Dimension order
+---------------
+The dimension order can be set upon initialization and you have to choose between *first* (bands, rows, columns), being raster shape needed for rasterio, or *last* (rows, columns, bands), being image shape used by most image processing libraries. Default is *first*.
+Compare with the `documentation of rasterio <https://rasterio.readthedocs.io/en/latest/api/rasterio.plot.html#rasterio.plot.reshape_as_image>`__. UKIS-pysat uses rasterio internally and the dimension order is always reshaped to *first* (bands, rows, columns) if the dimension order has been set as *last*.
+If the image was initialized with dimension order *last*, the result will be reshaped to *last* (rows, columns, bands) when calling ``img.arr``.
+
+Altering the array replaces all bands. If it is intended to alter a particular band, the remaining bands should be copied.
+
+Environment variables
+---------------------
 To use ``ukis_pysat.data`` and to download from the respective Datahub you need to set the credentials as environment variables.
 
 For EarthExplorer that's:
diff --git a/ukis_pysat/raster.py b/ukis_pysat/raster.py
index 89d4476..23320de 100644
--- a/ukis_pysat/raster.py
+++ b/ukis_pysat/raster.py
@@ -73,6 +73,26 @@ class Image:
         else:
             return reshape_as_image(self.__arr)
 
+    @arr.setter
+    def arr(self, arr_altered):
+        """Alters the array.
+        :param arr_altered: altered array of same dimension order (first or last) and same shape (xy) as original array
+        """
+        if not isinstance(arr_altered, np.ndarray):
+            raise TypeError("altered array must be of type np.ndarray")
+
+        if self.dimorder == "last":
+            arr_altered = reshape_as_raster(arr_altered)
+
+        if not arr_altered.shape[-2:] == self.__arr.shape[-2:]:
+            raise ValueError(
+                "Shape mismatch. Shape of source array: {}, shape of altered array {}".format(
+                    self.__arr.shape, arr_altered.shape
+                )
+            )
+
+        self.__arr = arr_altered
+
     def get_valid_data_bbox(self, nodata=0):
         """bounding box covering the input array's valid data pixels.
 


Test patch:
diff --git a/tests/test_raster.py b/tests/test_raster.py
index aa80145..d41b9d2 100644
--- a/tests/test_raster.py
+++ b/tests/test_raster.py
@@ -61,7 +61,7 @@ class DataTest(unittest.TestCase):
 
     def test_arr(self):
         img_first = Image(TEST_FILE, dimorder="first")
-        img_first.mask(box(11.9027457562112939, 51.4664152338322580, 11.9477435281016131, 51.5009522690838750, ))
+        img_first.mask(box(11.9027457562112939, 51.4664152338322580, 11.9477435281016131, 51.5009522690838750,))
         self.assertEqual(img_first.arr.shape, (1, 385, 502))
         self.assertEqual(
             str(img_first.dataset.transform),
@@ -79,7 +79,7 @@ class DataTest(unittest.TestCase):
         img_first.close()
 
         img_last = Image(TEST_FILE, dimorder="last")
-        img_last.mask(box(11.9027457562112939, 51.4664152338322580, 11.9477435281016131, 51.5009522690838750, ))
+        img_last.mask(box(11.9027457562112939, 51.4664152338322580, 11.9477435281016131, 51.5009522690838750,))
         self.assertEqual(img_last.arr.shape, (385, 502, 1))
         self.assertEqual(
             str(img_last.dataset.transform),
@@ -108,6 +108,25 @@ class DataTest(unittest.TestCase):
         self.assertEqual(img_last.arr.shape, (385, 502, 1))
         img_last.close()
 
+    def test_set_array(self):
+        img = Image(TEST_FILE, dimorder="last")
+        img.arr = img.arr + 1
+
+        self.assertTrue(np.array_equal(img.arr, np.ones(shape=img.arr.shape)))
+
+    def test_set_array_error(self):
+        img_first = Image(TEST_FILE, dimorder="first")
+
+        with self.assertRaises(TypeError):
+            img_first.arr = "error"
+
+        with self.assertRaises(ValueError):
+            img_first.arr = np.ones(shape=(764, 679, 1))
+
+        with self.assertRaises(ValueError):
+            img_last = Image(TEST_FILE, dimorder="last")
+            img_last.arr = np.ones(shape=(1, 764, 679))
+
     def test_get_valid_data_bbox(self):
         self.assertEqual(
             self.img.get_valid_data_bbox(), (11.896863892, 51.515176657, 11.896863892, 51.515176657),
@@ -120,7 +139,7 @@ class DataTest(unittest.TestCase):
         with self.assertRaises(TypeError, msg="bbox must be of type tuple or Shapely Polygon"):
             self.img.mask([1, 2, 3])
 
-        self.img.mask(box(11.9027457562112939, 51.4664152338322580, 11.9477435281016131, 51.5009522690838750, ))
+        self.img.mask(box(11.9027457562112939, 51.4664152338322580, 11.9477435281016131, 51.5009522690838750,))
         self.assertEqual(
             self.img.dataset.bounds,
             BoundingBox(