baseclasses.py 79.5 KB
Newer Older
1 2 3 4
# -*- coding: utf-8 -*-

import os
import warnings
5
from pkgutil import find_loader
6
from collections import OrderedDict
Daniel Scheffler's avatar
Daniel Scheffler committed
7
from copy import deepcopy
8
from typing import Union  # noqa F401
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

import numpy as np
from matplotlib import pyplot as plt
from osgeo import gdal_array
# custom
from shapely.geometry import Polygon
from shapely.wkt import loads as shply_loads
from six import PY3

# mpl_toolkits.basemap -> imported when GeoArray.show_map() is used
# dill -> imported when dumping GeoArray

try:
    from osgeo import gdal
    from osgeo import gdalnumeric
except ImportError:
    import gdal
    import gdalnumeric
27 28 29 30
from py_tools_ds.convenience.object_oriented import alias_property
from py_tools_ds.geo.coord_calc import get_corner_coordinates
from py_tools_ds.geo.coord_grid import snap_bounds_to_pixGrid
from py_tools_ds.geo.coord_trafo import mapXY2imXY, imXY2mapXY, transform_any_prj, reproject_shapelyGeometry
31
from py_tools_ds.geo.projection import prj_equal, WKT2EPSG, EPSG2WKT, isLocal
32 33
from py_tools_ds.geo.raster.conversion import raster2polygon
from py_tools_ds.geo.vector.topology \
34
    import get_footprint_polygon, polyVertices_outside_poly, fill_holes_within_poly
35 36
from py_tools_ds.geo.vector.geometry import boxObj
from py_tools_ds.io.raster.gdal import get_GDAL_ds_inmem
37
from py_tools_ds.compatibility.gdal import get_gdal_func
38
from py_tools_ds.numeric.numbers import is_number
39
from py_tools_ds.numeric.array import get_array_tilebounds
40 41 42

#  internal imports
from .subsetting import get_array_at_mapPos
43
from .metadata import GDAL_Metadata
44

45
if PY3:
46
    # noinspection PyCompatibility
47 48 49
    from builtins import TimeoutError, FileNotFoundError
else:
    from py_tools_ds.compatibility.python.exceptions import TimeoutError, FileNotFoundError
50

51
__author__ = 'Daniel Scheffler'
52 53 54 55 56


class GeoArray(object):
    def __init__(self, path_or_array, geotransform=None, projection=None, bandnames=None, nodata=None, progress=True,
                 q=False):
57
        # type: (Union[str, np.ndarray], tuple, str, list, float, bool, bool) -> None
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
        """This class creates a fast Python interface for geodata - either on disk or in memory. It can be instanced with
        a file path or with a numpy array and the corresponding geoinformation. Instances can always be indexed like
        normal numpy arrays, no matter if GeoArray has been instanced from file or from an in-memory array. GeoArray
        provides a wide range of geo-related attributes belonging to the dataset as well as some functions for quickly
        visualizing the data as a map, a simple image or an interactive image.

        :param path_or_array:   a numpy.ndarray or a valid file path
        :param geotransform:    GDAL geotransform of the given array or file on disk
        :param projection:      projection of the given array or file on disk as WKT string
                                (only needed if GeoArray is instanced with an array)
        :param bandnames:       names of the bands within the input array, e.g. ['mask_1bit', 'mask_clouds'],
                                (default: ['B1', 'B2', 'B3', ...])
        :param nodata:          nodata value
        :param progress:        show progress bars (default: True)
        :param q:               quiet mode (default: False)
        """

        # TODO implement compatibility to GDAL VRTs
        if not (isinstance(path_or_array, (str, np.ndarray, GeoArray)) or
77
           issubclass(getattr(path_or_array, '__class__'), GeoArray)):
78
            raise ValueError("%s parameter 'arg' takes only string, np.ndarray or GeoArray(and subclass) instances. "
79
                             "Got %s." % (self.__class__.__name__, type(path_or_array)))
80 81

        if path_or_array is None:
82
            raise ValueError("The %s parameter 'path_or_array' must not be None!" % self.__class__.__name__)
83 84 85 86 87

        if isinstance(path_or_array, str):
            assert ' ' not in path_or_array, "The given path contains whitespaces. This is not supported by GDAL."

            if not os.path.exists(path_or_array):
88
                raise FileNotFoundError(path_or_array)
89

90 91
        if isinstance(path_or_array, GeoArray) or issubclass(getattr(path_or_array, '__class__'), GeoArray):
            self.__dict__ = path_or_array.__dict__.copy()
92
            self._initParams = dict([x for x in locals().items() if x[0] != "self"])
93 94
            self.geotransform = geotransform or self.geotransform
            self.projection = projection or self.projection
95
            self.bandnames = bandnames or list(self.bandnames.keys())
96 97 98
            self._nodata = nodata if nodata is not None else self._nodata
            self.progress = False if progress is False else self.progress
            self.q = q if q is not None else self.q
99 100

        else:
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
            self._initParams = dict([x for x in locals().items() if x[0] != "self"])
            self.arg = path_or_array
            self._arr = path_or_array if isinstance(path_or_array, np.ndarray) else None
            self.filePath = path_or_array if isinstance(path_or_array, str) and path_or_array else None
            self.basename = os.path.splitext(os.path.basename(self.filePath))[0] if not self.is_inmem else 'IN_MEM'
            self.progress = progress
            self.q = q
            self._arr_cache = None  # dict containing key 'pos' and 'arr_cached'
            self._geotransform = None
            self._projection = None
            self._shape = None
            self._dtype = None
            self._nodata = nodata
            self._mask_nodata = None
            self._mask_baddata = None
116 117
            self._footprint_poly = None
            self._gdalDataset_meta_already_set = False
118 119
            self._metadata = None
            self._bandnames = None
120 121

            if bandnames:
122
                self.bandnames = bandnames  # use property in order to validate given value
123
            if geotransform:
124
                self.geotransform = geotransform  # use property in order to validate given value
125
            if projection:
126
                self.projection = projection  # use property in order to validate given value
127 128 129 130 131 132 133 134 135 136

            if self.filePath:
                self.set_gdalDataset_meta()

    @property
    def arr(self):
        return self._arr

    @arr.setter
    def arr(self, ndarray):
137 138
        assert isinstance(ndarray, np.ndarray), "'arr' can only be set to a numpy array! Got %s." % type(ndarray)
        # assert ndarray.shape == self.shape, "'arr' can only be set to a numpy array with shape %s. Received %s. " \
139 140 141 142 143
        #                                    "If you need to change the dimensions, create a new instance of %s." \
        #                                    %(self.shape, ndarray.shape, self.__class__.__name__)
        #  THIS would avoid warping like this: geoArr.arr, geoArr.gt, geoArr.prj = warp(...)

        if ndarray.shape != self.shape:
144
            self.flush_cache()  # the cached array is not useful anymore
145 146 147 148 149

        self._arr = ndarray

    @property
    def bandnames(self):
150
        if self._bandnames and len(self._bandnames) == self.bands:
151 152
            return self._bandnames
        else:
153
            del self.bandnames  # runs deleter which sets it to default values
154 155 156 157 158 159 160
            return self._bandnames

    @bandnames.setter
    def bandnames(self, list_bandnames):
        # type: (list) -> None

        if list_bandnames:
161 162 163 164 165 166 167 168
            if not isinstance(list_bandnames, list):
                raise TypeError("A list must be given when setting the 'bandnames' attribute. "
                                "Received %s." % type(list_bandnames))
            if len(list_bandnames) != self.bands:
                raise ValueError('Number of given bandnames does not match number of bands in array.')
            if len(list(set([type(b) for b in list_bandnames]))) != 1 or not isinstance(list_bandnames[0], str):
                raise ValueError("'bandnames must be a set of strings. Got other datatypes in there.'")

169
            bN_dict = OrderedDict((band, i) for i, band in enumerate(list_bandnames))
170 171 172

            if len(bN_dict) != self.bands:
                raise ValueError('Bands must different names. Received band list: %s' % list_bandnames)
173 174 175

            self._bandnames = bN_dict

176
            try:
177
                self.metadata.band_meta['band_names'] = list_bandnames
178 179 180
            except AttributeError:
                # in case self._metadata is None
                pass
181 182 183 184 185 186 187
        else:
            del self.bandnames

    @bandnames.deleter
    def bandnames(self):
        self._bandnames = OrderedDict(('B%s' % band, i) for i, band in enumerate(range(1, self.bands + 1)))
        if self._metadata is not None:
188
            self.metadata.band_meta['band_names'] = list(self._bandnames.keys())
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
    @property
    def is_inmem(self):
        """Check if associated image array is completely loaded into memory."""
        return isinstance(self.arr, np.ndarray)

    @property
    def shape(self):
        """Get the array shape of the associated image array."""
        if self.is_inmem:
            return self.arr.shape
        else:
            if self._shape:
                return self._shape
            else:
                self.set_gdalDataset_meta()
                return self._shape

    @property
    def ndim(self):
        """Get the number dimensions of the associated image array."""
        return len(self.shape)

    @property
    def rows(self):
        """Get the number of rows of the associated image array."""

        return self.shape[0]

    @property
    def columns(self):
        """Get the number of columns of the associated image array."""

        return self.shape[1]

    cols = alias_property('columns')

    @property
    def bands(self):
        """Get the number of bands of the associated image array."""

230
        return self.shape[2] if len(self.shape) > 2 else 1
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245

    @property
    def dtype(self):
        """Get the numpy data type of the associated image array."""

        if self._dtype:
            return self._dtype
        elif self.is_inmem:
            return self.arr.dtype
        else:
            self.set_gdalDataset_meta()
            return self._dtype

    @property
    def geotransform(self):
246
        """Get the GDAL GeoTransform of the associated image, e.g., (283500.0, 5.0, 0.0, 4464500.0, 0.0, -5.0)"""
247 248 249 250 251 252 253

        if self._geotransform:
            return self._geotransform
        elif not self.is_inmem:
            self.set_gdalDataset_meta()
            return self._geotransform
        else:
254
            return [0, 1, 0, 0, 0, -1]
255 256 257

    @geotransform.setter
    def geotransform(self, gt):
258
        # type: (Union[list, tuple]) -> None
259 260
        assert isinstance(gt, (list, tuple)) and len(gt) == 6,\
            'geotransform must be a list with 6 numbers. Got %s.' % str(gt)
261

262
        for i in gt:
263
            assert is_number(i), "geotransform must contain only numbers. Got '%s' (type: %s)." % (i, type(i))
264

265
        self._geotransform = gt
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287

    gt = alias_property('geotransform')

    @property
    def xgsd(self):
        """Get the X resolution in units of the given or detected projection."""

        return self.geotransform[1]

    @property
    def ygsd(self):
        """Get the Y resolution in units of the given or detected projection."""

        return abs(self.geotransform[5])

    @property
    def xygrid_specs(self):
        """
        Get the specifications for the X/Y coordinate grid, e.g. [[15,30], [0,30]] for a coordinate with its origin
        at X/Y[15,0] and a GSD of X/Y[15,30].
        """

288
        def get_grid(gt, xgsd, ygsd): return [[gt[0], gt[0] + xgsd], [gt[3], gt[3] - ygsd]]
289 290 291 292 293 294 295 296 297 298 299 300 301
        return get_grid(self.geotransform, self.xgsd, self.ygsd)

    @property
    def projection(self):
        """
        Get the projection of the associated image. Setting the projection is only allowed if GeoArray has been
        instanced from memory or the associated file on disk has no projection.
        """

        if self._projection:
            return self._projection
        elif not self.is_inmem:
            self.set_gdalDataset_meta()
302
            return self._projection  # or "LOCAL_CS[\"MAP\"]"
303
        else:
304
            return ''  # '"LOCAL_CS[\"MAP\"]"
305 306 307

    @projection.setter
    def projection(self, prj):
308
        # type: (str) -> None
309
        if self.filePath and self.projection:
310
            assert self.projection is None or prj_equal(self.projection, prj), \
311
                "Cannot set %s.projection to the given value because it does not match the projection from the file " \
312
                "on disk." % self.__class__.__name__
313 314 315 316 317 318 319 320 321 322 323 324 325
        else:
            self._projection = prj

    prj = alias_property('projection')

    @property
    def epsg(self):
        """Get the EPSG code of the projection of the GeoArray."""

        return WKT2EPSG(self.projection)

    @epsg.setter
    def epsg(self, epsg_code):
326
        # type: (int) -> None
327 328 329 330 331 332 333
        self.projection = EPSG2WKT(epsg_code)

    @property
    def box(self):
        mapPoly = get_footprint_polygon(get_corner_coordinates(gt=self.geotransform, cols=self.columns, rows=self.rows))
        return boxObj(gt=self.geotransform, prj=self.projection, mapPoly=mapPoly)

334 335 336 337 338 339 340 341
    @property
    def is_map_geo(self):
        # type: () -> bool
        """
        Returns 'True' if the GeoArray instance has a valid geoinformation with map instead of image coordinates.
        """
        return self.gt and list(self.gt) != [0, 1, 0, 0, 0, -1] and self.prj

342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
    @property
    def nodata(self):
        """
        Get the nodata value of the GeoArray. If GeoArray has been instanced with a file path the file is checked
        for an existing nodata value. Otherwise (if no value is exlicitly given during object instanciation) the nodata
        value is tried to be automatically detected.
        """

        if self._nodata is not None:
            return self._nodata
        else:
            # try to get nodata value from file
            if not self.is_inmem:
                self.set_gdalDataset_meta()
            if self._nodata is None:
Daniel Scheffler's avatar
Bugfix  
Daniel Scheffler committed
357
                self._nodata = self.find_noDataVal()
358 359 360 361 362 363
                if self._nodata == 'ambiguous':
                    warnings.warn('Nodata value could not be clearly identified. It has been set to None.')
                    self._nodata = None
                else:
                    if self._nodata is not None and not self.q:
                        print("Automatically detected nodata value for %s '%s': %s"
364
                              % (self.__class__.__name__, self.basename, self._nodata))
365 366 367 368
            return self._nodata

    @nodata.setter
    def nodata(self, value):
369
        # type: (Union[int, None]) -> None
370 371 372 373 374 375 376 377 378 379 380
        self._nodata = value

    @property
    def mask_nodata(self):
        """
        Get the nodata mask of the associated image array. It is calculated using all image bands.
        """

        if self._mask_nodata is not None:
            return self._mask_nodata
        else:
381
            self.calc_mask_nodata()  # sets self._mask_nodata
382 383 384 385 386 387 388 389 390 391 392
            return self._mask_nodata

    @mask_nodata.setter
    def mask_nodata(self, mask):
        """Set bad data mask.

        :param mask:    Can be a file path, a numpy array or an instance o GeoArray.
        """

        if mask is not None:
            from .masks import NoDataMask
393 394
            geoArr_mask = NoDataMask(mask, progress=self.progress, q=self.q)
            geoArr_mask.gt = geoArr_mask.gt if geoArr_mask.gt not in [None, [0, 1, 0, 0, 0, -1]] else self.gt
395
            geoArr_mask.prj = geoArr_mask.prj if geoArr_mask.prj else self.prj
396
            imName = "the %s '%s'" % (self.__class__.__name__, self.basename)
397 398 399 400

            assert geoArr_mask.bands == 1, \
                'Expected one single band as nodata mask for %s. Got %s bands.' % (self.basename, geoArr_mask.bands)
            assert geoArr_mask.shape[:2] == self.shape[:2], 'The provided nodata mask must have the same number of ' \
401
                                                            'rows and columns as the %s itself.' % imName
402 403
            assert geoArr_mask.gt == self.gt, \
                'The geotransform of the given nodata mask for %s must match the geotransform of the %s itself. ' \
404
                'Got %s.' % (imName, self.__class__.__name__, geoArr_mask.gt)
405 406
            assert not geoArr_mask.prj or prj_equal(geoArr_mask.prj, self.prj), \
                'The projection of the given nodata mask for the %s must match the projection of the %s itself.' \
407
                % (imName, self.__class__.__name__)
408 409

            self._mask_nodata = geoArr_mask
410 411 412 413 414 415
        else:
            del self.mask_nodata

    @mask_nodata.deleter
    def mask_nodata(self):
        self._mask_nodata = None
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434

    @property
    def mask_baddata(self):
        """
        Returns the bad data mask for the associated image array if it has been explicitly previously. It can be set
         by passing a file path, a numpy array or an instance of GeoArray to the setter of this property.
        """

        return self._mask_baddata

    @mask_baddata.setter
    def mask_baddata(self, mask):
        """Set bad data mask.

        :param mask:    Can be a file path, a numpy array or an instance o GeoArray.
        """

        if mask is not None:
            from .masks import BadDataMask
435 436
            geoArr_mask = BadDataMask(mask, progress=self.progress, q=self.q)
            geoArr_mask.gt = geoArr_mask.gt if geoArr_mask.gt not in [None, [0, 1, 0, 0, 0, -1]] else self.gt
437
            geoArr_mask.prj = geoArr_mask.prj if geoArr_mask.prj else self.prj
438
            imName = "the %s '%s'" % (self.__class__.__name__, self.basename)
439 440 441 442

            assert geoArr_mask.bands == 1, \
                'Expected one single band as bad data mask for %s. Got %s bands.' % (self.basename, geoArr_mask.bands)
            assert geoArr_mask.shape[:2] == self.shape[:2], 'The provided bad data mask must have the same number of ' \
443
                                                            'rows and columns as the %s itself.' % imName
444 445
            assert geoArr_mask.gt == self.gt, \
                'The geotransform of the given bad data mask for %s must match the geotransform of the %s itself. ' \
446
                'Got %s.' % (imName, self.__class__.__name__, geoArr_mask.gt)
447 448
            assert prj_equal(geoArr_mask.prj, self.prj), \
                'The projection of the given bad data mask for the %s must match the projection of the %s itself.' \
449
                % (imName, self.__class__.__name__)
450 451

            self._mask_baddata = geoArr_mask
452 453 454 455 456 457
        else:
            del self.mask_baddata

    @mask_baddata.deleter
    def mask_baddata(self):
        self._mask_baddata = None
458 459 460 461 462 463 464 465 466 467

    @property
    def footprint_poly(self):
        # FIXME should return polygon in image coordinates if no projection is available
        """
        Get the footprint polygon of the associated image array (returns an instance of shapely.geometry.Polygon.
        """

        if self._footprint_poly is None:
            assert self.mask_nodata is not None, 'A nodata mask is needed for calculating the footprint polygon. '
468
            if False not in self.mask_nodata[:]:
469 470 471 472
                # do not run raster2polygon if whole image is filled with data
                self._footprint_poly = self.box.mapPoly
            else:
                try:
473 474
                    multipolygon = raster2polygon(self.mask_nodata.astype(np.uint8), self.gt, self.prj, exact=False,
                                                  progress=self.progress, q=self.q, maxfeatCount=10, timeout=3)
475
                    self._footprint_poly = fill_holes_within_poly(multipolygon)
476
                except (RuntimeError, TimeoutError):
477 478 479 480
                    if not self.q:
                        warnings.warn("\nCalculation of footprint polygon failed for %s '%s'. Using outer bounds. One "
                                      "reason could be that the nodata value appears within the actual image (not only "
                                      "as fill value). To avoid this use another nodata value. Current nodata value is "
481
                                      "%s." % (self.__class__.__name__, self.basename, self.nodata))
482 483 484
                    self._footprint_poly = self.box.mapPoly

            # validation
485 486 487 488
            assert not polyVertices_outside_poly(self._footprint_poly, self.box.mapPoly), \
                "Computing footprint polygon for %s '%s' failed. The resulting polygon is partly or completely " \
                "outside of the image bounds." % (self.__class__.__name__, self.basename)
            # assert self._footprint_poly
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
            # for XY in self.corner_coord:
            #    assert self.GeoArray.box.mapPoly.contains(Point(XY)) or self.GeoArray.box.mapPoly.touches(Point(XY)), \
            #        "The corner position '%s' is outside of the %s." % (XY, self.imName)

        return self._footprint_poly

    @footprint_poly.setter
    def footprint_poly(self, poly):
        if isinstance(poly, Polygon):
            self._footprint_poly = poly
        elif isinstance(poly, str):
            self._footprint_poly = shply_loads(poly)
        else:
            raise ValueError("'footprint_poly' can only be set from a shapely polygon or a WKT string.")

    @property
    def metadata(self):
        """
        Returns a GeoDataFrame containing all available metadata (read from file if available).
        Use 'metadata[band_index].to_dict()' to get a metadata dictionary for a specific band.
        Use 'metadata.loc[row_name].to_dict()' to get all metadata values of the same key for all bands as dictionary.
        Use 'metadata.loc[row_name, band_index] = value' to set a new value.

        :return:  geopandas.GeoDataFrame
        """

        if self._metadata is not None:
            return self._metadata
        else:
518 519
            default = GDAL_Metadata(nbands=self.bands)

520 521 522 523 524 525 526 527
            self._metadata = default
            if not self.is_inmem:
                self.set_gdalDataset_meta()
                return self._metadata
            else:
                return self._metadata

    @metadata.setter
528 529 530 531 532 533
    def metadata(self, meta):
        if not isinstance(meta, GDAL_Metadata) or meta.bands != self.bands:
            raise ValueError("%s.metadata can only be set with an instance of geoarray.metadata.GDAL_Metadata of "
                             "which the band number corresponds to the band number of %s."
                             % (self.__class__.__name__, self.__class__.__name__))
        self._metadata = meta
534 535 536 537

    meta = alias_property('metadata')

    def __getitem__(self, given):
538
        if isinstance(given, (int, float, slice, np.integer, np.floating)) and self.ndim == 3:
539 540 541 542 543 544 545 546 547 548 549 550 551
            # handle 'given' as index for 3rd (bands) dimension
            if self.is_inmem:
                return self.arr[:, :, given]
            else:
                return self.from_path(self.arg, [given])

        elif isinstance(given, str):
            # behave like a dictionary and return the corresponding band
            if self.bandnames:
                if given not in self.bandnames:
                    raise ValueError("'%s' is not a known band. Known bands are: %s"
                                     % (given, ', '.join(list(self.bandnames.keys()))))
                if self.is_inmem:
552
                    return self.arr if self.ndim == 2 else self.arr[:, :, self.bandnames[given]]
553 554 555 556
                else:
                    return self.from_path(self.arg, [self.bandnames[given]])
            else:
                raise ValueError('String indices are only supported if %s has been instanced with bandnames given.'
557
                                 % self.__class__.__name__)
558 559 560 561 562 563 564

        elif isinstance(given, (tuple, list)):
            # handle requests like geoArr[[1,2],[3,4]  -> not implemented in from_path if array is not in mem
            types = [type(i) for i in given]
            if list in types or tuple in types:
                self.to_mem()

565
            if len(given) == 3:
566 567

                # handle strings in the 3rd dim of 'given' -> convert them to a band index
568
                if isinstance(given[2], str):
569 570 571 572 573 574 575 576
                    if self.bandnames:
                        if given[2] not in self.bandnames:
                            raise ValueError("'%s' is not a known band. Known bands are: %s"
                                             % (given[2], ', '.join(list(self.bandnames.keys()))))

                        band_idx = self.bandnames[given[2]]
                        # NOTE: the string in the 3rd is ignored if ndim==2 and band_idx==0
                        if self.is_inmem:
577
                            return self.arr if (self.ndim == 2 and band_idx == 0) else self.arr[:, :, band_idx]
578
                        else:
579 580
                            getitem_params = \
                                given[:2] if (self.ndim == 2 and band_idx == 0) else given[:2] + (band_idx,)
581 582 583 584 585 586 587
                            return self.from_path(self.arg, getitem_params)
                    else:
                        raise ValueError(
                            'String indices are only supported if %s has been instanced with bandnames given.'
                            % self.__class__.__name__)

                # in case a third dim is requested from 2D-array -> ignore 3rd dim if 3rd dim is 0
588
                elif self.ndim == 2 and given[2] == 0:
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
                    if self.is_inmem:
                        return self.arr[given[:2]]
                    else:
                        return self.from_path(self.arg, given[:2])

        # if nothing has been returned until here -> behave like a numpy array
        if self.is_inmem:
            return self.arr[given]
        else:
            getitem_params = [given] if isinstance(given, slice) else given
            return self.from_path(self.arg, getitem_params)

    def __setitem__(self, idx, array2set):
        """Overwrites the pixel values of GeoArray.arr with the given array.

        :param idx:         <int, list, slice> the index position to overwrite
        :param array2set:   <np.ndarray> array to be set. Must be compatible to the given index position.
        :return:
        """

        if self.is_inmem:
            self.arr[idx] = array2set
        else:
            raise NotImplementedError('Item assignment for %s instances that are not in memory is not yet supported.'
613
                                      % self.__class__.__name__)
614 615 616

    def __getattr__(self, attr):
        # check if the requested attribute can not be present because GeoArray has been instanced with an array
617 618
        attrsNot2Link2np = ['__deepcopy__']   # attributes we don't want to inherit from numpy.ndarray

619 620
        if attr not in self.__dir__() and not self.is_inmem and attr in ['shape', 'dtype', 'geotransform',
                                                                         'projection']:
621 622
            self.set_gdalDataset_meta()

623 624
        if attr in self.__dir__():  # __dir__() includes also methods and properties
            return self.__getattribute__(attr)  # __getattribute__ avoids infinite loop
625
        elif attr not in attrsNot2Link2np and hasattr(np.array([]), attr):
626 627
            return self[:].__getattribute__(attr)
        else:
628
            raise AttributeError("%s object has no attribute '%s'." % (self.__class__.__name__, attr))
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648

    def __getstate__(self):
        """Defines how the attributes of GMS object are pickled."""

        # clean array cache in order to avoid cache pickling
        self.flush_cache()

        return self.__dict__

    def __setstate__(self, state):
        """Defines how the attributes of GMS object are unpickled.
        NOTE: This method has been implemented because otherwise pickled and unpickled instances show recursion errors
        within __getattr__ when requesting any attribute.
        """

        self.__dict__ = state

    def calc_mask_nodata(self, fromBand=None, overwrite=False):
        """Calculates a no data mask with (values: 0=nodata; 1=data)

649 650 651
        NOTE:   Only pixel containing the nodata values in ALL bands are recognized as nodata pixel. If they contain a
                pixel value different from the nodata value in any band they are good data pixels.

652 653 654 655 656 657 658
        :param fromBand:  <int> index of the band to be used (if None, all bands are used)
        :param overwrite: <bool> whether to overwrite existing nodata mask that has already been calculated
        :return:
        """

        if self._mask_nodata is None or overwrite:
            assert self.ndim in [2, 3], "Only 2D or 3D arrays are supported. Got a %sD array." % self.ndim
659
            arr = self[:, :, fromBand] if self.ndim == 3 and fromBand is not None else self[:]
660

661 662 663
            min_v, max_v = np.min(arr), np.max(arr)
            if (min_v == max_v == self.nodata) or (np.isnan(min_v) and np.isnan(max_v) and np.isnan(self.nodata)):
                self.mask_nodata = np.full(arr.shape[:2], False)
664
            else:
665 666 667 668 669
                if self.nodata is None:
                    self.mask_nodata = np.ones((self.rows, self.cols), np.bool)
                elif np.isnan(self.nodata):
                    self.mask_nodata = \
                        np.invert(np.isnan(arr)) if arr.ndim == 2 else \
670
                        np.any(np.invert(np.isnan(arr)), axis=2)
671 672 673
                else:
                    self.mask_nodata = \
                        np.ma.masked_not_equal(arr, self.nodata).mask if arr.ndim == 2 else \
674
                        np.any(np.ma.masked_not_equal(arr, self.nodata).mask, axis=2)
675

676 677 678 679 680 681 682 683
    def find_noDataVal(self, bandIdx=0, sz=3):
        """Tries to derive no data value from homogenious corner pixels within 3x3 windows (by default).
        :param bandIdx:
        :param sz: window size in which corner pixels are analysed
        """
        wins = [self[0:sz, 0:sz, bandIdx], self[0:sz, -sz:, bandIdx],
                self[-sz:, -sz:, bandIdx], self[-sz:, 0:sz, bandIdx]]  # UL, UR, LR, LL

684 685
        means, stds = [np.mean(win) for win in wins], [np.std(win) for win in wins]
        possVals = [mean for mean, std in zip(means, stds) if std == 0 or np.isnan(std)]
686 687 688 689
        # possVals==[]: all corners are filled with data; np.std(possVals)==0: noDataVal clearly identified

        if possVals:
            if np.std(possVals) != 0:
690 691 692 693 694 695
                if np.isnan(np.std(possVals)):
                    # at least one of the possible values is np.nan
                    nodata = np.nan
                else:
                    # different possible nodata values have been found in the image corner
                    nodata = 'ambiguous'
696 697 698 699 700
            else:
                if len(possVals) <= 2:
                    # each window in each corner
                    warnings.warn("\nAutomatic nodata value detection returned the value %s for GeoArray '%s' but this "
                                  "seems to be unreliable (occurs in only %s). To avoid automatic detection, just pass "
701 702 703
                                  "the correct nodata value."
                                  % (possVals[0], self.basename, ('2 image corners' if len(possVals) == 2 else
                                                                  '1 image corner')))
704
                nodata = possVals[0]
705
        else:
706 707 708
            nodata = None

        return nodata
709

710 711 712 713 714 715 716 717 718 719
    def set_gdalDataset_meta(self):
        """Retrieves GDAL metadata from file. This function is only executed once to avoid overwriting of user defined
         attributes, that are defined after object instanciation.

        :return:
        """

        if not self._gdalDataset_meta_already_set:
            assert self.filePath
            ds = gdal.Open(self.filePath)
720 721 722
            if not ds:
                raise Exception('Error reading file:  ' + gdal.GetLastErrorMsg())

723
            # set private class variables (in order to avoid recursion error)
724 725
            self._shape = tuple([ds.RasterYSize, ds.RasterXSize] + ([ds.RasterCount] if ds.RasterCount > 1 else []))
            self._dtype = gdal_array.GDALTypeCodeToNumericTypeCode(ds.GetRasterBand(1).DataType)
726
            self._geotransform = list(ds.GetGeoTransform())
727 728

            # for some reason GDAL reads arbitrary geotransforms as (0, 1, 0, 0, 0, 1) instead of (0, 1, 0, 0, 0, -1)
729
            self._geotransform[5] = -abs(self._geotransform[5])  # => force ygsd to be negative
730

731 732
            # temp conversion to EPSG needed because GDAL seems to modify WKT string when writing file to disk
            # (e.g. using gdal_merge) -> conversion to EPSG and back undos that
733 734
            wkt = ds.GetProjection()
            self._projection = EPSG2WKT(WKT2EPSG(wkt)) if not isLocal(wkt) else ''
735

736 737 738 739
            if 'nodata' not in self._initParams or self._initParams['nodata'] is None:
                band = ds.GetRasterBand(1)
                # FIXME this does not support different nodata values within the same file
                self._nodata = band.GetNoDataValue()
740

741 742 743 744
            # set metadata attribute
            if self.is_inmem or not self.filePath:
                # metadata cannot be read from disk -> set it to the default
                self._metadata = GDAL_Metadata(nbands=self.bands)
745

746 747
            else:
                self._metadata = GDAL_Metadata(filePath=self.filePath)
748

749
            del ds
750 751 752 753 754 755 756 757 758 759 760 761 762 763

        self._gdalDataset_meta_already_set = True

    def from_path(self, path, getitem_params=None):
        # type: (str, list) -> np.ndarray
        """Read a GDAL compatible raster image from disk, with respect to the given image position.
        NOTE: If the requested array position is already in cache, it is returned from there.

        :param path:            <str> the file path of the image to read
        :param getitem_params:  <list> a list of slices in the form [row_slice, col_slice, band_slice]
        :return out_arr:        <np.ndarray> the output array
        """

        ds = gdal.Open(path)
764 765 766
        if not ds:
            raise Exception('Error reading file:  ' + gdal.GetLastErrorMsg())

767
        R, C, B = ds.RasterYSize, ds.RasterXSize, ds.RasterCount
768
        del ds
769

770
        # convert getitem_params to subset area to be read #
771 772 773 774
        rS, rE, cS, cE, bS, bE, bL = [None] * 7

        # populate rS, rE, cS, cE, bS, bE, bL
        if getitem_params:
775
            # populate rS, rE, cS, cE
776 777 778 779 780 781 782 783 784 785 786 787 788 789
            if len(getitem_params) >= 2:
                givenR, givenC = getitem_params[:2]
                if isinstance(givenR, slice):
                    rS = givenR.start
                    rE = givenR.stop - 1 if givenR.stop is not None else None
                elif isinstance(givenR, int):
                    rS = givenR
                    rE = givenR
                if isinstance(givenC, slice):
                    cS = givenC.start
                    cE = givenC.stop - 1 if givenC.stop is not None else None
                elif isinstance(givenC, int):
                    cS = givenC
                    cE = givenC
790 791

            # populate bS, bE, bL
792 793 794 795 796 797 798 799
            if len(getitem_params) in [1, 3]:
                givenB = getitem_params[2] if len(getitem_params) == 3 else getitem_params[0]
                if isinstance(givenB, slice):
                    bS = givenB.start
                    bE = givenB.stop - 1 if givenB.stop is not None else None
                elif isinstance(givenB, int):
                    bS = givenB
                    bE = givenB
800
                elif isinstance(givenB, (tuple, list)):
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
                    typesInGivenB = [type(i) for i in givenB]
                    assert len(list(set(typesInGivenB))) == 1, \
                        'Mixed data types within the list of bands are not supported.'
                    if isinstance(givenB[0], int):
                        bL = list(givenB)
                    elif isinstance(givenB[0], str):
                        bL = [self.bandnames[i] for i in givenB]
                elif type(givenB) in [str]:
                    bL = [self.bandnames[givenB]]

        # set defaults for not given values
        rS = rS if rS is not None else 0
        rE = rE if rE is not None else R - 1
        cS = cS if cS is not None else 0
        cE = cE if cE is not None else C - 1
        bS = bS if bS is not None else 0
        bE = bE if bE is not None else B - 1
        bL = list(range(bS, bE + 1)) if not bL else bL

        # convert negative to positive ones
        rS = rS if rS >= 0 else self.rows + rS
        rE = rE if rE >= 0 else self.rows + rE
        cS = cS if cS >= 0 else self.columns + cS
        cE = cE if cE >= 0 else self.columns + cE
        bS = bS if bS >= 0 else self.bands + bS
        bE = bE if bE >= 0 else self.bands + bE
827
        bL = [b if b >= 0 else (self.bands + b) for b in bL]
828 829

        # validate subset area bounds to be read
830 831 832 833 834 835 836
        def msg(v, idx, sz):
            # FIXME numpy raises that error ONLY for the 2nd axis
            return '%s is out of bounds for axis %s with size %s' % (v, idx, sz)

        for val, axIdx, axSize in zip([rS, rE, cS, cE, bS, bE], [0, 0, 1, 1, 2, 2], [R, R, C, C, B, B]):
            if not 0 <= val <= axSize - 1:
                raise ValueError(msg(val, axIdx, axSize))
837 838

        # summarize requested array position in arr_pos
839
        # NOTE: # bandlist must be string because truth value of an array with more than one element is ambiguous
840 841
        arr_pos = dict(rS=rS, rE=rE, cS=cS, cE=cE, bS=bS, bE=bE, bL=bL)

842 843
        def _ensure_np_shape_consistency_3D_2D(arr):
            """Ensure numpy output shape consistency according to the given indexing parameters.
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

            This may require 3D to 2D conversion in case out_arr can be represented by a 2D array AND index has been
            provided as integer (avoids shapes like (1,2,2). It also may require 2D to 3D conversion in case only one
            band has been requested and the 3rd dimension has been provided as a slice.

            NOTE: -> numpy also returns a 2D array in that case
            NOTE: if array is indexed with a slice -> keep it a 3D array
            """
            # 2D -> 3D
            if arr.ndim == 2 and isinstance(getitem_params, (tuple, list)) and len(getitem_params) == 3 and \
                    isinstance(getitem_params[2], slice):
                arr = arr[:, :, np.newaxis]

            # 3D -> 2D
            if 1 in arr.shape:
                outshape = []
                for i, sh in enumerate(arr.shape):
                    if sh == 1 and isinstance(getitem_params[i], (int, float)):
                        pass
                    else:
                        outshape.append(sh)

                arr = arr.reshape(*outshape)

            return arr

870
        # check if the requested array position is already in cache -> if yes, return it from there
871
        if self._arr_cache is not None and self._arr_cache['pos'] == arr_pos:
872
            out_arr = self._arr_cache['arr_cached']
873
            out_arr = _ensure_np_shape_consistency_3D_2D(out_arr)
874 875 876 877 878 879 880

        else:
            # TODO insert a multiprocessing.Lock here in order to prevent IO bottlenecks?
            # read subset area from disk
            if bL == list(range(0, B)):
                tempArr = gdalnumeric.LoadFile(path, cS, rS, cE - cS + 1, rE - rS + 1)
                out_arr = np.swapaxes(np.swapaxes(tempArr, 0, 2), 0, 1) if B > 1 else tempArr
881 882
                if out_arr is None:
                    raise Exception('Error reading file:  ' + gdal.GetLastErrorMsg())
883 884 885 886
            else:
                ds = gdal.Open(path)
                if len(bL) == 1:
                    band = ds.GetRasterBand(bL[0] + 1)
887
                    out_arr = band.ReadAsArray(cS, rS, cE - cS + 1, rE - rS + 1)
888 889
                    if out_arr is None:
                        raise Exception('Error reading file:  ' + gdal.GetLastErrorMsg())
890
                    del band
891 892 893 894 895
                else:
                    out_arr = np.empty((rE - rS + 1, cE - cS + 1, len(bL)))
                    for i, bIdx in enumerate(bL):
                        band = ds.GetRasterBand(bIdx + 1)
                        out_arr[:, :, i] = band.ReadAsArray(cS, rS, cE - cS + 1, rE - rS + 1)
896 897
                        if out_arr is None:
                            raise Exception('Error reading file:  ' + gdal.GetLastErrorMsg())
898
                        del band
899

900
                del ds
901

902
            out_arr = _ensure_np_shape_consistency_3D_2D(out_arr)
903

904
            # only set self.arr if the whole cube has been read (in order to avoid sudden shape changes)
905
            if out_arr.shape == self.shape:
906 907 908 909 910
                self.arr = out_arr

            # write _arr_cache
            self._arr_cache = dict(pos=arr_pos, arr_cached=out_arr)

911 912
        return out_arr  # TODO implement check of returned datatype (e.g. NoDataMask should always return np.bool
        # TODO -> would be np.int8 if an int8 file is read from disk
913 914 915 916 917 918 919 920

    def save(self, out_path, fmt='ENVI', creationOptions=None):
        # type: (str, str, list) -> None
        """Write the raster data to disk.

        :param out_path:        <str> output path
        :param fmt:             <str> the output format / GDAL driver code to be used for output creation, e.g. 'ENVI'
                                Refer to http://www.gdal.org/formats_list.html to get a full list of supported formats.
921 922
        :param creationOptions: <list> GDAL creation options,
                                e.g., ["QUALITY=80", "REVERSIBLE=YES", "WRITE_METADATA=YES"]
923 924 925
        """

        if not self.q:
926 927
            print('Writing GeoArray of size %s to %s.' % (self.shape, out_path))
        assert self.ndim in [2, 3], 'Only 2D- or 3D arrays are supported.'
928 929 930 931 932 933 934 935 936

        driver = gdal.GetDriverByName(fmt)
        if driver is None:
            raise Exception("'%s' is not a supported GDAL driver. Refer to www.gdal.org/formats_list.html for full "
                            "list of GDAL driver codes." % fmt)

        if not os.path.isdir(os.path.dirname(out_path)):
            os.makedirs(os.path.dirname(out_path))

937 938
        envi_metadict = self.metadata.to_ENVI_metadict()

939
        if self.is_inmem:
Daniel Scheffler's avatar
Daniel Scheffler committed
940 941 942 943 944
            ds_inmem = get_GDAL_ds_inmem(self.arr, self.geotransform, self.projection,
                                         self.nodata)  # expects rows,columns,bands

            # write dataset
            ds_out = driver.CreateCopy(out_path, ds_inmem, options=creationOptions if creationOptions else [])
945 946 947 948 949 950

            # # rows, columns, bands => bands, rows, columns
            # out_arr = self.arr if self.ndim == 2 else np.swapaxes(np.swapaxes(self.arr, 0, 2), 1, 2)
            # gdalnumeric.SaveArray(out_arr, out_path, format=fmt, prototype=ds_inmem)  # expects bands,rows,columns
            # ds_out = gdal.Open(out_path)

Daniel Scheffler's avatar
Daniel Scheffler committed
951
            del ds_inmem
952

953 954 955 956
            ################
            # set metadata #
            ################

Daniel Scheffler's avatar
Daniel Scheffler committed
957
            # NOTE:  The dataset has to be written BEFORE metadata are added. Otherwise, metadata are not written.
958 959 960

            # ENVI #
            ########
961 962
            if fmt == 'ENVI':
                ds_out.SetMetadata(envi_metadict, 'ENVI')
963

964
                if 'band_names' in envi_metadict:
965 966
                    for bidx in range(self.bands):
                        band = ds_out.GetRasterBand(bidx + 1)
967 968 969 970
                        bandname = self.metadata.band_meta['band_names'][bidx].strip()
                        band.SetDescription(bandname)

                        assert band.GetDescription() == bandname
971 972 973 974
                        del band

                if 'description' in envi_metadict:
                    ds_out.SetDescription(envi_metadict['description'])
975

976 977
                ds_out.FlushCache()
                gdal.Unlink(out_path + '.aux.xml')
978

979 980 981
            elif self.metadata.all_meta:
                    # set global domain metadata
                    if self.metadata.global_meta:
982
                        ds_out.SetMetadata(dict((k, repr(v)) for k, v in self.metadata.global_meta.items()))
983

984 985 986
                    if 'description' in envi_metadict:
                        ds_out.SetDescription(envi_metadict['description'])

987
                    # set band domain metadata
988 989
                    bandmeta_dict = self.metadata.to_DataFrame().astype(str).to_dict()

990 991
                    for bidx in range(self.bands):
                        band = ds_out.GetRasterBand(bidx + 1)
992 993 994
                        bandmeta = bandmeta_dict[bidx]
                        # meta2write = dict((k, repr(v)) for k, v in self.metadata.band_meta.items() if v is not np.nan)
                        band.SetMetadata(bandmeta)
995 996

                        if 'band_names' in envi_metadict:
997
                            band.SetDescription(self.metadata.band_meta['band_names'][bidx].strip())
998

999 1000
                        band.FlushCache()
                        del band
1001

Daniel Scheffler's avatar
Daniel Scheffler committed
1002 1003
            ds_out.FlushCache()
            del ds_out
1004 1005 1006

        else:
            src_ds = gdal.Open(self.filePath)
1007 1008 1009
            if not src_ds:
                raise Exception('Error reading file:  ' + gdal.GetLastErrorMsg())

1010 1011
            gdal_Translate = get_gdal_func('Translate')
            gdal_Translate(out_path, src_ds, format=fmt, creationOptions=creationOptions)
1012
            del src_ds
1013

1014 1015 1016 1017 1018 1019 1020 1021 1022
            # add band names
            if 'band_names' in envi_metadict:
                ds_out = gdal.Open(out_path)

                for bidx in range(self.bands):
                    band = ds_out.GetRasterBand(bidx + 1)
                    band.SetDescription(self.metadata.band_meta['band_names'][bidx])
                    del band

1023 1024 1025 1026 1027 1028 1029 1030
        if not os.path.exists(out_path):
            raise Exception(gdal.GetLastErrorMsg())

    def dump(self, out_path):
        # type: (str) -> None
        """Serialize the whole object instance to disk using dill."""

        import dill
1031 1032
        with open(out_path, 'wb') as outF:
            dill.dump(self, outF)
1033 1034 1035 1036 1037 1038 1039 1040 1041

    def _get_plottable_image(self, xlim=None, ylim=None, band=None, boundsMap=None, boundsMapPrj=None, res_factor=None,
                             nodataVal=None, out_prj=None):
        # handle limits
        if boundsMap:
            boundsMapPrj = boundsMapPrj if boundsMapPrj else self.prj
            image2plot, gt, prj = self.get_mapPos(boundsMap, boundsMapPrj, band2get=band,
                                                  fillVal=nodataVal if nodataVal is not None else self.nodata)
        else:
1042 1043
            cS, cE = xlim if isinstance(xlim, (tuple, list)) else (0, self.columns)
            rS, rE = ylim if isinstance(ylim, (tuple, list)) else (0, self.rows)
1044 1045

            image2plot = self[rS:rE, cS:cE, band] if band is not None else self[rS:rE, cS:cE]
1046
            gt, prj = self.geotransform, self.projection
1047

1048
        transOpt = ['SRC_METHOD=NO_GEOTRANSFORM'] if tuple(gt) == (0, 1, 0, 0, 0, -1) else None
1049
        xdim, ydim = None, None
1050
        nodataVal = nodataVal if nodataVal is not None else self.nodata
1051 1052

        if res_factor != 1. and image2plot.shape[0] * image2plot.shape[1] > 1e6:  # shape > 1000*1000
1053 1054 1055 1056
            # sample image down / normalize
            xdim, ydim = \
                (self.columns * res_factor, self.rows * res_factor) if res_factor else \
                tuple((np.array([self.columns, self.rows]) / (np.array([self.columns, self.rows]).max() / 1000)))
1057 1058 1059
            xdim, ydim = int(xdim), int(ydim)

        if xdim or ydim or out_prj:
1060
            from py_tools_ds.geo.raster.reproject import warp_ndarray
1061 1062 1063 1064 1065
            image2plot, gt, prj = warp_ndarray(image2plot, self.geotransform, self.projection,
                                               out_XYdims=(xdim, ydim), in_nodata=nodataVal, out_nodata=nodataVal,
                                               transformerOptions=transOpt, out_prj=out_prj, q=True)
            if transOpt and 'NO_GEOTRANSFORM' in ','.join(transOpt):
                image2plot = np.flipud(image2plot)
1066 1067
                gt = list(gt)
                gt[3] = 0
1068 1069 1070 1071 1072 1073 1074

            if xdim or ydim:
                print('Note: array has been downsampled to %s x %s for faster visualization.' % (xdim, ydim))

        return image2plot, gt, prj

    def show(self, xlim=None, ylim=None, band=None, boundsMap=None, boundsMapPrj=None, figsize=None,
1075
             interpolation='none', vmin=None, vmax=None, pmin=2, pmax=98, cmap=None, nodataVal=None,
1076
             res_factor=None, interactive=False, ax=None):
1077 1078 1079 1080 1081 1082 1083 1084