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

# gms_preprocessing, spatial and spectral homogenization of satellite remote sensing data
#
5
# Copyright (C) 2020  Daniel Scheffler (GFZ Potsdam, daniel.scheffler@gfz-potsdam.de)
6
7
8
9
10
11
#
# This software was developed within the context of the GeoMultiSens project funded
# by the German Federal Ministry of Education and Research
# (project grant code: 01 IS 14 010 A-C).
#
# This program is free software: you can redistribute it and/or modify it under
12
# the terms of the GNU General Public License as published by the Free Software
13
14
# Foundation, either version 3 of the License, or (at your option) any later version.
# Please note the following exception: `gms_preprocessing` depends on tqdm, which
15
16
17
# is distributed under the Mozilla Public Licence (MPL) v2.0 except for the files
# "tqdm/_tqdm.py", "setup.py", "README.rst", "MANIFEST.in" and ".gitignore".
# Details can be found here: https://github.com/tqdm/tqdm/blob/master/LICENCE.
18
19
20
21
22
23
24
25
26
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License along
# with this program.  If not, see <http://www.gnu.org/licenses/>.

27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
"""
GEOPROCESSING OBJECT
"GIS operations to manipulate spatial data.
Takes an input dataset, performs an operation on that dataset
and returns the result of the operation as an output dataset.
"""

import collections
import datetime
import math
import os
import re
import subprocess
import time
import warnings

import numpy as np
from matplotlib import dates as mdates

# custom
try:
    from osgeo import osr
    from osgeo import gdal
    from osgeo import gdalnumeric
except ImportError:
    import osr
    import gdal
    import gdalnumeric
from gdalconst import GA_ReadOnly

import pyproj
from pyorbital import astronomy
import ephem
from shapely.geometry import MultiPoint, Polygon
from shapely.ops import cascaded_union

from geoarray import GeoArray
from py_tools_ds.geo.coord_grid import snap_bounds_to_pixGrid
from py_tools_ds.geo.coord_trafo import transform_utm_to_wgs84, transform_wgs84_to_utm, mapXY2imXY, imXY2mapXY

67
from ..options.config import GMS_config as CFG
68
from ..misc.definition_dicts import get_outFillZeroSaturated
69
from ..misc.logging import close_logger
70
71
72
73
74
75
76
77
78

__author__ = 'Daniel Scheffler', 'Robert Behling'


class GEOPROCESSING(object):

    def __init__(self, geodata, logger, workspace=None, subset=None, v=None):
        self.logger = logger
        self.subset = subset
79
80
        self.target_radunit_optical = ''
        self.target_radunit_thermal = ''
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
        self.outpath_conv = None
        # check gdal environment
        if v is not None:
            self.logger.debug("\n--")
            self.logger.debug("GDAL Environment:")
            self.logger.debug("\tGDAL-version: ", gdal.VersionInfo())
            self.logger.debug("\tmaximum amount of memory (as bytes) for caching within GDAL: ", gdal.GetCacheMax())
            self.logger.debug("\tthe amount of memory currently used for caching within GDAL: ", gdal.GetCacheUsed())
            self.logger.debug("\tPopFinderLocation: ", gdal.PopFinderLocation())

            # load Raster file to an GDAL Object
        # ----register drivers
        # • A driver is an object that knows how to interact with a certain data type (such as a shapefile)
        # • Need an appropriate driver in order to read or write data (need it explicitly for write)
        # register all drivers for reading

        gdal.AllRegister()

        assert type(geodata) in [str, gdal.Dataset], \
            "GEOP: The argument 'geodata' has to be a path or a gdal.Dataset. Got %s." % type(geodata)
        if isinstance(geodata, str):
            # ----open files Open(<filename>, <GDALAccess>)
            # open raster to gdal object
            self.inDs = (gdal.Open(geodata, GA_ReadOnly))
            self.filepath, self.filename = os.path.split(geodata)
            self.shortname, self.extension = os.path.splitext(self.filename)
            if v:
                self.logger.debug("\n--")
                self.logger.debug("load data to GDAL:\n\tfilepath: %s\n\tfilename: %s" % (self.filepath, self.filename))
            if not geodata.startswith('/vsi'):
                path2check = geodata
            else:
                # gdal_prefix_dict = {'/vsizip': '.zip', '/vsitar': '.tar', '/vsitar': '.tar.gz',
                #                     '/vsitar' '.gz': '/vsigzip'}
                p1 = [geodata.split(i)[0] + i for i in ['.zip', '.tar', '.tar.gz', '.gz', '.tgz']
                      if len(geodata.split(i)) > 1 and geodata.split(i)[1].startswith('/')][0]
117
                path2check = os.path.abspath('.' + re.search(r'/vsi[\s\S]*(/[\s\S,.]*)', p1, re.I).group(1))
118
119
120
121
122
123
124
125
126
            assert os.path.exists(path2check), "ERROR: data %s does not exist!" % path2check
            assert self.inDs is not None, "ERROR: Could not open %s!" % self.filename
        elif isinstance(geodata, gdal.Dataset):
            self.inDs = geodata
            del geodata
            self.filepath, self.filename = None, self.inDs.GetDescription()
            self.shortname, self.extension = os.path.splitext(self.filename)

        # ****OBJECT ATTRIBUTES***************************************************
127
        self.workspace = os.path.join(CFG.path_tempdir, 'GEOPROCESSING_temp') if workspace is None else workspace
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
        if v:
            self.logger.debug("\n--")
            self.logger.debug("\ttemporary geoprocessing workspace", self.workspace)

        # --Getting columns, rows and number of bands of inputdataset
        self.desc = self.inDs.GetDescription()
        if self.subset is None or self.subset[0] == 'cube':
            self.cols = self.inDs.RasterXSize
            self.rows = self.inDs.RasterYSize
            self.bands = self.inDs.RasterCount
            self.colStart = 0
            self.rowStart = 0
            self.bandStart = 0
            self.colEnd = self.cols - 1
            self.rowEnd = self.rows - 1
            self.bandEnd = self.bands - 1
            self.bandsList = range(self.bandStart, self.bandEnd + 1)
        else:
            assert isinstance(self.subset, list) and len(self.subset) == 2, \
                "Unable to initialize GEOP object due to bad arguments at subset keyword. Got %s." % self.subset
            self.subset_kwargs_to_cols_rows_bands_colStart_rowStart_bandStart()

        self.DataProp = [self.cols, self.rows, self.bands, self.colStart, self.rowStart, self.bandStart]
        if v is not None:
            self.logger.info("""--\nproperties of the inputdataset\n\tcolumns[cols]: %s\n\trows[rows]:
            %s\n\tbands[bands]: %s\n\tDescription[desc]: %s""" % (self.cols, self.rows, self.bands, self.desc))

        # --Getting driver infos of inputdataset
        self.drname_s = self.inDs.GetDriver().ShortName
        self.drname_l = self.inDs.GetDriver().LongName
        self.drhelp = self.inDs.GetDriver().HelpTopic
        self.DriverProp = [self.drname_s, self.drname_l, self.drhelp]

        if v is not None:
            self.logger.info(
                "\tDriverShortName[drname_s]: %s\n\tDriverLongName[drnam_l]: %s\n\tDriverHelpWebsite[drhelp]: %s" % (
                    self.drname_s, self.drname_l, self.drhelp))

        # --Getting Georeference info of inputdataset
        self.geotransform = self.inDs.GetGeoTransform()
        self.projection = self.inDs.GetProjection()
        self.originX = self.geotransform[0]
        self.originY = self.geotransform[3]
        self.pixelWidth = self.geotransform[1]
        self.pixelHeight = self.geotransform[5]
        self.rot1 = self.geotransform[2]
        self.rot2 = self.geotransform[4]
        self.extent = [self.originX, self.originY, self.originX + (self.cols * self.pixelWidth),
                       self.originY + (self.rows * self.pixelHeight)]  # [ulx, uly, lrx, lry]
        self.GeoProp = [self.originX, self.originY, self.pixelWidth, self.pixelHeight, self.rot1, self.rot2]

        if v is not None:
            self.logger.info("\toriginX[originX]:", self.originX, "\n\toriginY[originY]:", self.originY,
                             "\n\tresolution: X[pixelWidth]:" + str(self.pixelWidth),
                             "Y[pixelHeight]:" + str(self.pixelHeight), "\n\trotation: a[rot1]:" + str(self.rot1),
                             "b[rot2]:" + str(self.rot2))

        self.Prop = {'DataProp': self.DataProp, 'DriverProp': self.DriverProp, 'GeoProp': self.GeoProp}

    """****OBJECT METHODS******************************************************"""

189
190
191
192
193
194
195
196
197
198
199
    def __getstate__(self):
        """Defines how the attributes of GEOPROCESSING instances are pickled."""
        close_logger(self.logger)
        self.logger = None

        return self.__dict__

    def __del__(self):
        close_logger(self.logger)
        self.logger = None

200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
    def subset_kwargs_to_cols_rows_bands_colStart_rowStart_bandStart(self):
        shape_fullArr = [self.inDs.RasterYSize, self.inDs.RasterXSize, self.inDs.RasterCount]
        self.rows, self.cols, self.bands, self.rowStart, self.rowEnd, self.colStart, self.colEnd, self.bandStart, \
            self.bandEnd, self.bandsList = get_subsetProps_from_subsetArg(shape_fullArr, self.subset).values()
        self.subset = self.subset if self.subset[0] != 'cube' else None

    def update_dataset_related_attributes(self):
        self.desc = self.inDs.GetDescription()
        self.filepath, self.filename = os.path.split(self.desc)
        self.shortname, self.extension = os.path.splitext(self.filename)

        if self.subset is None or self.subset == 'cube':
            self.cols = self.inDs.RasterXSize
            self.rows = self.inDs.RasterYSize
            self.bands = self.inDs.RasterCount
            self.colStart = 0
            self.rowStart = 0
            self.bandStart = 0
            self.colEnd = self.cols - 1
            self.rowEnd = self.rows - 1
            self.bandEnd = self.bands - 1
            self.bandsList = range(self.bandStart, self.bandEnd + 1)
        else:
            self.subset_kwargs_to_cols_rows_bands_colStart_rowStart_bandStart()

        self.DataProp = [self.cols, self.rows, self.bands, self.colStart, self.rowStart, self.bandStart]
        self.drname_s = self.inDs.GetDriver().ShortName
        self.drname_l = self.inDs.GetDriver().LongName
        self.drhelp = self.inDs.GetDriver().HelpTopic
        self.DriverProp = [self.drname_s, self.drname_l, self.drhelp]

        self.geotransform = self.inDs.GetGeoTransform()
        self.projection = self.inDs.GetProjection()
        self.originX = self.geotransform[0]
        self.originY = self.geotransform[3]
        self.pixelWidth = self.geotransform[1]
        self.pixelHeight = self.geotransform[5]
        self.rot1 = self.geotransform[2]  # FIXME check
        self.rot2 = self.geotransform[4]
        self.extent = [self.originX, self.originY, self.originX + (self.cols * self.pixelWidth),
                       self.originY + (self.rows * self.pixelHeight)]  # [ulx, uly, lrx, lry]
        self.GeoProp = [self.originX, self.originY, self.pixelWidth, self.pixelHeight, self.rot1, self.rot2]

        self.Prop = {'DataProp': self.DataProp, 'DriverProp': self.DriverProp, 'GeoProp': self.GeoProp}

    def gdalinfo(self):
Daniel Scheffler's avatar
Daniel Scheffler committed
246
247
        """get properties of the Inputdatasets via gdalinfo

248
249
250
251
252
253
254
255
256
257
258
        (die Infos die er hier ausschreibt in subrocess.Popen können einer variable als Text übergeben werden. Aus
        diesem Text kann ich dann die Infos als Attribute ausschreiben.
        als ersatz für die jetzige Attributerzeugung
        Muss die Attributerzeugung wirklich sein? kann ich nicht alle irgendwie über das GDAL-objekt abfragen!
        bis jetzt hab ich aber nur die Infos die oben stehen als Abfrage ermöglichen können
        """
        subprocess.Popen(["gdalinfo", os.path.join(self.filepath, self.filename)]).wait()

    def add_GeoTransform_Projection_using_MetaData(self, CornerTieP_LonLat, CS_EPSG=None, CS_TYPE=None, CS_DATUM=None,
                                                   CS_UTM_ZONE=None, gResolution=None, shape_fullArr=None):
        """ Method assumes that north is up. Map rotations are not respected.
Daniel Scheffler's avatar
Daniel Scheffler committed
259

260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
        :param CornerTieP_LonLat:
        :param CS_EPSG:
        :param CS_TYPE:
        :param CS_DATUM:
        :param CS_UTM_ZONE:
        :param gResolution:
        :param shape_fullArr:
        """
        if CornerTieP_LonLat == [] or CornerTieP_LonLat is None:
            self.logger.error('Failed to add projection. L1A object must have corner coordinates.')
        else:
            # Projection
            srs = osr.SpatialReference()
            if CS_EPSG is not None:
                srs.ImportFromEPSG(CS_EPSG)
                self.inDs.SetProjection(srs.ExportToWkt())
            elif CS_TYPE is not None and CS_DATUM is not None:
                if CS_TYPE == 'UTM' and CS_DATUM == 'WGS84':
                    UTM_zone = int(1 + (CornerTieP_LonLat[0][0] + 180.0) / 6.0) if CS_UTM_ZONE is None else CS_UTM_ZONE
                    EPSG_code = int('326' + str(UTM_zone)) if CornerTieP_LonLat[0][1] > 0.0 else int(
                        '327' + str(UTM_zone))
                elif CS_TYPE == 'LonLat' and CS_DATUM == 'WGS84':
                    EPSG_code = 4326
                else:
                    self.logger.error('Coordinate system type %s is not yet implemented. Since corner coordinates in '
                                      'Lon/Lat are available, it has been set to Lon/Lat.' % CS_TYPE)
                    EPSG_code, CS_TYPE, CS_DATUM = (4326, 'LonLat', 'WGS84')
                srs.ImportFromEPSG(EPSG_code)
                self.inDs.SetProjection(srs.ExportToWkt())
            else:
                CS_TYPE, CS_DATUM, CS_EPSG = ('LonLat', 'WGS84', 4326)
                srs.ImportFromEPSG(CS_EPSG)
                self.inDs.SetProjection(srs.ExportToWkt())
            self.projection = self.inDs.GetProjection()
            # GeoTransform
            self.originX, self.originY = CornerTieP_LonLat[0] if CS_TYPE == 'LonLat' else transform_wgs84_to_utm(
                CornerTieP_LonLat[0][0], CornerTieP_LonLat[0][1])
            if gResolution is None or gResolution == -99.:
                if shape_fullArr is None:
                    self.logger.error("Failed to add projection. Please provide at least one of the arguments "
                                      "'gResolution' or 'shape_fullArr'!")
                else:
                    gResolution = float(pyproj.Geod(ellps=CS_DATUM).inv(CornerTieP_LonLat[0][0],
                                                                        CornerTieP_LonLat[0][1],
                                                                        CornerTieP_LonLat[1][0],
                                                                        CornerTieP_LonLat[1][1])[2]) / shape_fullArr[1]
                    # distance in [m]/cols
                    self.logger.info(
                        "While adding projection the ground sampling distance had to be calculated. It has "
                        "been set to %s meters." % gResolution)
            self.pixelWidth, self.pixelHeight, self.rot1, self.rot2 = (gResolution, gResolution * -1., 0, 0)
            GT = [self.originX, self.pixelWidth, self.rot1, self.originY, self.rot2, self.pixelHeight]
            self.inDs.SetGeoTransform(GT)
            self.geotransform = self.inDs.GetGeoTransform()

    def georeference_by_TieP_or_inherent_GCPs(self, use_inherent_GCPs=False, TieP=None, dst_EPSG_code=None,
                                              dst_CS='UTM', dst_CS_datum='WGS84', mode='GDAL', use_workspace=True,
                                              inFill=None):
        """Warp image to new Projection.
Daniel Scheffler's avatar
Daniel Scheffler committed
319

320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
        :param use_inherent_GCPs:
        :param TieP:                Corner Tie Points - always LonLat.
        :param dst_EPSG_code:       EPSG-Code defines LonLat or UTM coordinates.
        :param dst_CS:
        :param dst_CS_datum:
        :param mode:
        :param use_workspace:
        :param inFill:
        """
        if use_inherent_GCPs and TieP is None:
            self.logger.info('Georeferencing dataset using inherent GCP list...')
        if use_inherent_GCPs and TieP:
            self.logger.info("\n\nWARNING: User defined tie points are provided though 'use_inherent_GCPs' is true. "
                             "Georeferencing dataset using inherent GCP list...")
        if not use_inherent_GCPs and TieP:
            self.logger.info('Georeferencing dataset by given tiepoints...')
            gcp_ul = [1, 1, TieP[0][0], TieP[0][1]]  # col/row/map_x/map_y
            gcp_ur = [self.cols, 1, TieP[1][0], TieP[1][1]]
            gcp_ll = [1, self.rows, TieP[2][0], TieP[2][1]]
            gcp_lr = [self.cols, self.rows, TieP[3][0], TieP[3][1]]

        if dst_EPSG_code is None or dst_EPSG_code == -99.:
            if dst_CS == 'UTM' and dst_CS_datum == 'WGS84':
                UTM_zone = int(1 + (TieP[0][0] + 180.0) / 6.0)
                dst_EPSG_code = int('326' + str(UTM_zone)) if TieP[0][1] > 0.0 else int('327' + str(UTM_zone))
            if dst_CS == 'LonLat' and dst_CS_datum == 'WGS84':
                dst_EPSG_code = 4326

        assert mode in ['rasterio', 'GDAL'], "The 'mode' argument must be set to 'rasterio' or 'GDAL'."

        if mode == 'rasterio':
            """needs no temporary files but does not support multiprocessing"""
            raise NotImplementedError()
            # out_prj = EPSG2WKT(dst_EPSG_code)
            # proj_geo = isProjectedOrGeographic(self.projection)
            #
            # assert proj_geo in ['projected', 'geographic']
            # TieP = TieP if proj_geo == 'geographic' else \
            #     [transform_wgs84_to_utm(LonLat[0], LonLat[1], get_UTMzone(prj=self.projection)) for LonLat in TieP]
            # xmin, xmax, ymin, ymax = HLP_F.corner_coord_to_minmax(TieP)
            # t0 = time.time()
            # in_arr = np.swapaxes(np.swapaxes(gdalnumeric.LoadFile(self.desc), 0, 2), 0, 1)
            # print('reading time', time.time() - t0)
            # if inFill is None:
            #     inFill = get_outFillZeroSaturated(in_arr.dtype)[0]
            # out_nodataVal = get_outFillZeroSaturated(in_arr.dtype)[0]
            # t0 = time.time()

            # warped, gt, prj = warp_ndarray(in_arr, self.geotransform, self.projection, out_prj,
            #                                out_bounds=([xmin, ymin, xmax, ymax]), rspAlg='cubic',
            #                                in_nodata=inFill, out_nodata=out_nodataVal)[0]

            # multiprocessing: not implemented further because multiproceesing within Python Mappers is not possible
            # args = [(in_arr[:,:,i],self.geotransform,self.projection,out_prj,([xmin, ymin, xmax, ymax]),
            #        2,in_nodataVal) for i in range(in_arr.shape[2])]
            # import multiprocessing
            # with multiprocessing.Pool() as pool:
            #    results = pool.map(warp_mp,args)

            # print('warping time', time.time() - t0)
            # from spectral.io import envi
            # envi.save_image('/dev/shm/test_warped.hdr',warped,dtype=str(np.dtype(warped.dtype)),
            #                force=True,ext='.bsq',interleave='bsq')

        else:  # mode == 'GDAL'
            """needs temporary files but does support multiprocessing and configuring cache size"""
            t0 = time.time()
            in_dtype = gdalnumeric.LoadFile(self.desc, 0, 0, 1, 1).dtype
            if inFill is None:
                inFill = get_outFillZeroSaturated(in_dtype)[0]
            out_nodataVal = get_outFillZeroSaturated(in_dtype)[0]
            gcps = ' '.join(['-gcp %s %s %s %s' % tuple(gcp) for gcp in [gcp_ul, gcp_ur, gcp_ll, gcp_lr]])

            if use_workspace:
                inFile = self.desc
                translatedFile = os.path.splitext(inFile)[0] + '_translate' if not use_inherent_GCPs else inFile
                warpedFile = os.path.splitext(inFile)[0] + '_warp'
                if not use_inherent_GCPs:
                    os.system('gdal_translate -of ENVI %s \
                        -a_srs EPSG:%s -q %s %s' % (gcps, dst_EPSG_code, inFile, translatedFile))

                    # os.system('gdalwarp -of ENVI --config GDAL_CACHEMAX 2048 -wm 2048 -ot Int16 -t_srs EPSG:%s -tps
                    #   -r cubic -srcnodata -%s -dstnodata %s -overwrite -q %s %s' \
                    #   %(dst_EPSG_code, in_nodataVal,out_nodataVal, translatedFile, warpedFile))
                    os.system('gdalwarp -of ENVI --config GDAL_CACHEMAX 2048 -wm 2048 -t_srs EPSG:%s -tps -r \
                        cubic -srcnodata %s -dstnodata %s -multi -overwrite -wo NUM_THREADS=%s -q %s %s'
406
                              % (dst_EPSG_code, inFill, out_nodataVal, CFG.CPUs, translatedFile, warpedFile))
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
                    # import shutil
                    # only for bugfixing:
                    # shutil.copy(translatedFile, \
                    #     '//misc/hy5/scheffler/Skripte_Models/python/gms_preprocessing/sandbox/out/')
                    # shutil.copy(translatedFile+'.hdr',\
                    #     '//misc/hy5/scheffler/Skripte_Models/python/gms_preprocessing/sandbox/out/')
                    # shutil.copy(warpedFile, \
                    #     '//misc/hy5/scheffler/Skripte_Models/python/gms_preprocessing/sandbox/out/')
                    # shutil.copy(warpedFile+'.hdr', \
                    #     '//misc/hy5/scheffler/Skripte_Models/python/gms_preprocessing/sandbox/out/')
            else:
                VRT_name = os.path.splitext(os.path.basename(self.desc))[0] + '.vrt'
                # dst_ds = gdal.GetDriverByName('VRT').CreateCopy(VRT_name, self.inDs, 0)
                # del dst_ds
                inFile = VRT_name
                translatedFile = os.path.splitext(inFile)[0] + '_translate.vrt' if not use_inherent_GCPs else self.desc
                warpedFile = os.path.splitext(inFile)[0] + '_warp.vrt'
                if not use_inherent_GCPs:
                    os.system('gdal_translate -of VRT %s \
                        -a_srs EPSG:%s -q %s %s' % (gcps, dst_EPSG_code, inFile, translatedFile))
                    # os.system('gdalwarp -of VRT --config GDAL_CACHEMAX 500 -wm 500 -ot Int16 -t_srs EPSG:%s -tps -r \
                    #     cubic -srcnodata %s -dstnodata %s -multi -overwrite -wo NUM_THREADS=10 -q %s %s' \
                    #     %(dst_EPSG_code,in_nodataVal,out_nodataVal,translatedFile,warpedFile))
                    os.system('gdalwarp -of VRT --config GDAL_CACHEMAX 2048 -wm 2048 -ot Int16 -t_srs EPSG:%s -tps -r \
                        cubic -srcnodata %s -dstnodata %s -overwrite -multi -wo NUM_THREADS=%s -q %s %s'
432
                              % (dst_EPSG_code, inFill, out_nodataVal, CFG.CPUs, translatedFile, warpedFile))
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
                    # print('warped')
            print('GDAL warping time', time.time() - t0)

            self.inDs = gdal.OpenShared(warpedFile, GA_ReadOnly) \
                if inFile.endswith('.vrt') else gdal.Open(warpedFile, GA_ReadOnly)
            # print('read successful')
            self.update_dataset_related_attributes()

    # def get_row_column_bounds(self,arr_shape = None, arr_pos = None):
    #    if arr_shape == None and arr_pos == None:
    #        arr_shape = 'cube'
    #    try:
    #        if arr_shape == 'row': # arr_pos = int
    #            row_start,row_end,col_start,col_end, rows,cols = arr_pos,arr_pos+1,0,self.cols, 1,self.cols
    #        elif arr_shape == 'col': # arr_pos = int
    #            row_start,row_end,col_start,col_end, rows,cols = 0,self.rows,arr_pos,arr_pos+1, self.rows,1
    #        elif arr_shape == 'band' or arr_shape == 'cube': # arr_pos = None
    #            row_start,row_end,col_start,col_end, rows,cols = 0,self.rows-1,0,self.cols-1, self.rows,self.cols
    #        elif arr_shape == 'block' or arr_shape == 'custom':
    #            # arr_pos = [ (row_start,row_end),(col_start,col_end),(band_start,band_end) ]
    #            row_start,row_end,col_start,col_end, rows,cols = \
    #                arr_pos[0][0],arr_pos[0][1],arr_pos[1][0],arr_pos[1][1], \
    #                arr_pos[0][1]+1-arr_pos[0][0],arr_pos[1][1]+1-arr_pos[1][0]
    #        elif arr_shape == 'pixel': # arr_pos = (x,y)
    #            row_start,row_end,col_start,col_end, rows,cols = arr_pos[0],arr_pos[0]+1,arr_pos[1],arr_pos[1]+1, 1,1
    #        return row_start,row_end,col_start,col_end,rows,cols
    #    except:
    #        self.logger.error(
    #            'Error while setting row and column bounds. Got arr_shape = %s and arr_pos = %s' %(arr_shape,arr_pos))

    def get_projection_type(self):
        return 'LonLat' if osr.SpatialReference(self.projection).IsGeographic() else 'UTM' if osr.SpatialReference(
            self.projection).IsProjected() else None

    def get_corner_coordinates(self, targetProj):
        """Returns corner coordinates of the entire GEOP object in lon/lat or UTM.
Daniel Scheffler's avatar
Daniel Scheffler committed
469
470
471
472
473
474
475
476

        ATTENTION: coordinates represent PIXEL CORNERS:
            UL=UL-coordinate of (0,0)
            UR=UR-coordinate of (0,self.cols-1)
            => lonlat_arr always contains UL-coordinate of each pixel

        :param targetProj: 'LonLat' or 'UTM'
        """
477
478
479
480
481
482
483
484
485
486
487
488
489
        UL_LonLat = self.pixelToWorldCoord_using_geotransform_and_projection((0, 0), targetProj)
        # self.cols statt self.cols-1, um Koordinate am rechten Pixelrand zu berechnen:
        UR_LonLat = self.pixelToWorldCoord_using_geotransform_and_projection((0, self.cols), targetProj)
        LL_LonLat = self.pixelToWorldCoord_using_geotransform_and_projection((self.rows, 0), targetProj)
        LR_LonLat = self.pixelToWorldCoord_using_geotransform_and_projection((self.rows, self.cols), targetProj)
        UL_LonLat = tuple([round(i, 10) for i in UL_LonLat])
        UR_LonLat = tuple([round(i, 10) for i in UR_LonLat])
        LL_LonLat = tuple([round(i, 10) for i in LL_LonLat])
        LR_LonLat = tuple([round(i, 10) for i in LR_LonLat])
        return [UL_LonLat, UR_LonLat, LL_LonLat, LR_LonLat]

    def calc_mask_data_nodata(self, array=None, custom_nodataVal=-9999):
        """Berechnet den Bildbereich, der von allen Kanälen abgedeckt wird.
Daniel Scheffler's avatar
Daniel Scheffler committed
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
        :param array:               input numpy array to be used for mask calculation (otherwise read from disk)
        :param custom_nodataVal:
        """
        nodataVal = get_outFillZeroSaturated(np.int16)[0] if custom_nodataVal is None else custom_nodataVal
        in_arr = array if array is not None else np.swapaxes(np.swapaxes(gdalnumeric.LoadFile(self.desc), 0, 2), 0, 1)
        return np.all(np.where(in_arr == nodataVal, 0, 1), axis=2)

    def pixelToWorldCoord_using_geotransform_and_projection(self, Pixel_row_col, targetProj):
        if targetProj not in ['UTM', 'LonLat']:
            self.logger.error("Failed to calculate world coordinates of true data corners. Target projection must be "
                              "'UTM' or 'LonLat'. Got %s" % targetProj)
        row, col = Pixel_row_col
        XWorld = self.geotransform[0] + col * self.geotransform[1]
        YWorld = self.geotransform[3] + row * self.geotransform[5]
        src_srs = osr.SpatialReference()
        src_srs.ImportFromWkt(self.projection)
        if src_srs.IsGeographic() and targetProj == 'LonLat' or src_srs.IsProjected() and targetProj == 'UTM':
            return XWorld, YWorld
        elif src_srs.IsProjected() and targetProj == 'LonLat':
            return transform_utm_to_wgs84(XWorld, YWorld, src_srs.GetUTMZone())  # [Lon,Lat]
        else:  # geographic to UTM
            return transform_wgs84_to_utm(XWorld, YWorld)  # [HW,RW]

    def tondarray(self, direction=1, startpix=None, extent=None, UL=None, LR=None, v=0):
Daniel Scheffler's avatar
Daniel Scheffler committed
515
516
        """Convert gdalobject to 3dimensional ndarray stack ([x,y,z]).

517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
        :param direction:   1: shape: [bands, rows, cols]
                                -> same as theres read envi structure ([band1],[band2],..[bandn])
                            2: shape: [rows, bands, cols]
                            3: shape: [rows, cols, bands]
                                -> Structure used in PIL and IDL for example
                                ([pixband1,pixband2,..,pixbandn],[pixband1,pixband2,..,pixbandn],...)
        :param startpix:    [x,y] pixels->UL:pixelcoordinates for subset generation
        :param extent:      [cols, rows] -> number of pixels in x and y-direction
        :param UL:          [x,y] map coordinates -> UL map coordinates for subset generation
        :param LR:          [x,y] map coordinates -> LR map coordinates for subset generation
        :param v:
        """
        # -- test of given inputparameter
        test = [startpix is not None, extent is not None, UL is not None, LR is not None]

        if test == [False, False, False, False]:
            startpix = [0, 0]
            extent = [self.cols, self.rows]

        # only startpixel coordinates given. extent set to startcoordinates to LR of the image
        elif test == [True, False, False, False]:
            assert len(startpix) == 2 and startpix[0] < self.cols and startpix[1] < self.rows, \
                "XXX-ERROR-XXX: Start coordinates x: %i, y: %i out of range" % (startpix[0], startpix[1])
            extent = [self.cols - startpix[0], self.rows - startpix[1]]

        # startpix and extent given
        elif test == [True, True, False, False]:
            assert len(startpix) == 2 and startpix[0] < self.cols and startpix[1] < self.rows and len(extent) == 2, \
                "XXX-ERROR-XXX: Start coordinates x: %i, y: %i out of range" % (startpix[0], startpix[1])
            if extent[0] > self.cols - startpix[0]:
                extent[0] = self.cols - startpix[0]
            elif extent[1] > self.rows - startpix[1]:
                extent[1] = self.rows - startpix[1]

        # extent and UL given
        elif test == [False, True, True, False]:
            pass
        # only UL coordinates given. extent set to startcoordinates to LR of the image (use UL coordnates if they are
        # within the image otherwise UL=origin of the image)
        elif test == [False, False, True, False]:
            assert len(UL) == 2, "XXX-ERROR-XXX: A list of 2 arguments (numbers) for UL required"
            # convert coordinates to float
            UL = [float(UL[0]), float(UL[1])]
            # Test if x of UL is within the image
            if not self.originX <= UL[0] <= (self.originX + self.cols * self.pixelWidth):
                UL[0] = self.originX
            # Test if y of UL is within the image
            if not self.originY >= UL[1] >= (self.originY + self.rows * self.pixelHeight):
                UL[1] = self.originY
            # convert UL in pixelcoordinates
            startpix = [int(float((UL[0] - self.originX)) / float(self.pixelWidth)),
                        int(float((UL[1] - self.originY)) / float(self.pixelHeight))]
            extent = [self.cols - startpix[0], self.rows - startpix[1]]

        # UL and LR coordinates given (use UL and LR coordinates if they are within the image otherwise use the whole
        # image)
        elif test == [False, False, True, True]:
            assert len(UL) == 2 and len(LR) == 2, \
                "XXX-ERROR-XXX: A list of 2 arguments (numbers) for UL and for LR is required"
            # convert coordinates to float
            UL = [float(UL[0]), float(UL[1])]
            LR = [float(LR[0]), float(LR[1])]
            # Test if x of UL is within the image
            if not self.originX <= UL[0] <= (self.originX + self.cols * self.pixelWidth):
                UL[0] = self.originX
            # Test if y of UL is within the image
            if not self.originY >= UL[1] >= (self.originY + self.rows * self.pixelHeight):
                UL[1] = self.originY
            # Test if x of LR is within the image
            if not self.originX <= LR[0] <= (self.originX + self.cols * self.pixelWidth):
                LR[0] = self.originX + self.cols * self.pixelWidth
            # Test if y of UL is within the image
            if not self.originY >= LR[1] >= (self.originY + self.rows * self.pixelHeight):
                LR[1] = self.originY + self.rows * self.pixelHeight
            # convert UL in pixelcoordinates
            startpix = [int(float((UL[0] - self.originX)) / float(self.pixelWidth)),
                        int(float((UL[1] - self.originY)) / float(self.pixelHeight))]
            # get extent
            extent = [int(float((LR[0] - UL[0])) / self.pixelWidth + 0.5),
                      int(float((LR[1] - UL[1])) / self.pixelHeight + 0.5)]

            # if UL or LR are the same. only one pixel selected
            if extent[0] == 0:
                extent[0] = 1
            if extent[1] == 0:
                extent[1] = 1
        if v:
            print("\t startpix:", startpix)
            print("\t extent:", extent)

        if self.subset is not None and self.subset != 'cube':  # rasObj instanced as subset
            if [self.inDs.RasterYSize, self.inDs.RasterXSize] != [self.rows,
                                                                  self.cols]:  # inDs does not represent subset
                startpix = [startpix[0] + self.colStart, startpix[1] + self.rowStart]
                extent = [self.cols, self.rows]

        if self.subset is not None and self.subset[0] == 'custom' and \
614
                self.target_radunit_optical == '' and self.target_radunit_thermal == '':
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
            # conversion to Rad or Ref overwrites self.inDs
            # => custom bandsList contains bands that are NOT in range(self.bands)
            bands2process = self.bandsList
        else:  # normal case
            bands2process = range(self.bands)

        np_dtype = convertGdalNumpyDataType(gdal.GetDataTypeName(self.inDs.GetRasterBand(1).DataType))
        im = np.empty((self.rows, self.cols, len(bands2process)), np_dtype)
        for out_idx, x in enumerate(bands2process):
            im[:, :, out_idx] = self.inDs.GetRasterBand(x + 1).ReadAsArray(startpix[0], startpix[1], extent[0],
                                                                           extent[1])
        if direction == 1:  # bands, rows, cols;  so wie Theres es gebastelt hat
            im = np.rollaxis(im, 2)
        elif direction == 2:  # rows, bands, cols
            im = np.swapaxes(im, 1, 2)
        elif direction == 3:  # rows, cols, bands;  so wie in PIL bzw. IDL benötigt
            pass  # bands, rows,cols
        return im

    def Layerstacking(self, layers_pathlist, path_output=None):
        rows, cols, bands = self.rows, self.cols, len(layers_pathlist)

        if path_output is None:
            dtype = gdalnumeric.LoadFile(layers_pathlist[0], 0, 0, 1, 1).dtype
            stacked = np.empty((self.rows, self.cols, len(layers_pathlist)), dtype)

            for i, p in enumerate(layers_pathlist):
                self.logger.info('Adding band %s to Layerstack..' % os.path.basename(p))
                if self.subset is None or self.subset[0] == 'cube':
                    stacked[:, :, i] = gdalnumeric.LoadFile(p)
                else:
                    stacked[:, :, i] = gdalnumeric.LoadFile(p, self.colStart, self.rowStart, cols, rows)

            return stacked

650
        elif path_output == 'MEMORY':  # CFG.inmem_serialization is True
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
            stack_in_mem = gdal.GetDriverByName("MEM").Create("stack.mem", cols, rows, bands)

            for idx, layer in enumerate(layers_pathlist):
                current_band = gdal.Open(layer, GA_ReadOnly)
                stack_in_mem.AddBand()  # data type is dynamically assigned
                band_in_stack = stack_in_mem.GetRasterBand(idx + 1)

                if [self.rows, self.cols] == [current_band.RasterYSize, current_band.RasterXSize]:
                    self.logger.info('Adding band %s to Layerstack..' % os.path.basename(layer))

                    if self.subset is None or self.subset[0] == 'cube':
                        band_in_stack.WriteArray(current_band.GetRasterBand(1).ReadAsArray(), 0, 0)
                    else:
                        band_in_stack.WriteArray(current_band.GetRasterBand(1)
                                                 .ReadAsArray(self.colStart, self.rowStart, self.cols, self.rows), 0, 0)
                else:
                    self.logger.info(
                        'Band %s skipped due to incompatible geometrical resolution.' % os.path.basename(layer))
                del current_band, band_in_stack

            self.bands = bands
            self.inDs = stack_in_mem

674
        else:  # CFG.inmem_serialization is False
675
676
            from ..misc.helper_functions import subcall_with_output

677
678
679
680
681
682
683
684
685
686
687
688
689
            self.logger.info('Adding the following bands to Layerstack:')
            [self.logger.info(os.path.basename(i)) for i in layers_pathlist]

            if not os.path.isdir(os.path.dirname(path_output)):
                os.makedirs(os.path.dirname(path_output))
            if os.path.exists(path_output):
                os.remove(path_output)
            if os.path.exists(os.path.splitext(path_output)[0] + '.hdr'):
                os.remove(os.path.splitext(path_output)[0] + '.hdr')

            str_layers_pathlist = ' '.join(layers_pathlist)

            if self.subset is None:
690
691
692
693
694
695
                cmd = "gdal_merge.py -q -o %s -of ENVI -seperate %s" % (path_output, str_layers_pathlist)
                output, exitcode, err = subcall_with_output(cmd)
                if exitcode:
                    raise RuntimeError(err)
                if output:
                    return output.decode('UTF-8')
696
697
698
699
700
701
702
703
704
705
706
707
                # FIXME this changes the format of the projection (maybe a GDAL bug?)
                # FIXME normalize by EPSG2WKT(WKT2EPSG(WKT))
            else:
                # convert Pixel Coords to Geo Coords
                orig_ds = gdal.Open(layers_pathlist[0], GA_ReadOnly)
                GT, PR = orig_ds.GetGeoTransform(), orig_ds.GetProjection()
                UL_Xgeo = GT[0] + self.colStart * GT[1] + self.rowStart * GT[2]
                UL_Ygeo = GT[3] + self.colStart * GT[4] + self.rowStart * GT[5]
                LR_Xgeo = GT[0] + self.colEnd * GT[1] + self.rowEnd * GT[2]
                LR_Ygeo = GT[3] + self.colEnd * GT[4] + self.rowEnd * GT[5]
                ullr = '%s %s %s %s' % (UL_Xgeo, UL_Ygeo, LR_Xgeo, LR_Ygeo)

708
709
710
711
712
713
714
                cmd = "gdal_merge.py -q -o %s -ul_lr %s -of ENVI -seperate %s" \
                      % (path_output, ullr, str_layers_pathlist)
                output, exitcode, err = subcall_with_output(cmd)
                if exitcode:
                    raise RuntimeError(err)
                if output:
                    return output.decode('UTF-8')
715
716
717
718
719
720

                if [GT, PR] == [(0.0, 1.0, 0.0, 0.0, 0.0, 1.0), '']:
                    # delete output map info in case of arbitrary coordinate system
                    with open(os.path.splitext(path_output)[0] + '.hdr', 'r') as inF:
                        lines = inF.readlines()

721
                    outContent = ''.join([i for i in lines if not re.search(r'map info', i, re.I)])
722
723
724
725
726
727
728
729
730
731
732
733
734
                    with open(os.path.splitext(path_output)[0] + '.hdr', 'w') as outF:
                        outF.write(outContent)

            assert os.path.exists(path_output) and os.path.exists(os.path.splitext(path_output)[0] + '.hdr'), \
                "Layerstacking failed because output cannot be found."

            # validate the written format of the projection and change it if needed
            # NOT NEEDED ANYMORE (GeoArray always validates projection when reading from disk)
            # prj_written = GeoArray(path_output).prj
            # if self.projection != prj_written and WKT2EPSG(prj_written) == WKT2EPSG(self.projection):
            #
            #     with open(os.path.splitext(path_output)[0] + '.hdr', 'r') as inF:
            #         lines      = inF.readlines()
735
            #         outContent = ''.join([line if not re.search(r'coordinate system string', line, re.I) else
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
            #                               'coordinate system string = %s' % self.projection for line in lines])
            #
            #     with open(os.path.splitext(path_output)[0] + '.hdr', 'w') as outF:
            #         outF.write(outContent)
            #
            #     self.inDs = gdal.Open(path_output)

            count_outBands = GeoArray(path_output).bands
            assert count_outBands == len(layers_pathlist), "Layerstacking failed because its output has only %s " \
                                                           "instead of %s bands." % (
                                                               count_outBands, len(layers_pathlist))

        self.update_dataset_related_attributes()

        # writing via envi memmap (tiling-fähig)
        # FileObj = envi.create_image(os.path.splitext(path_output)[0]+'.hdr',shape=(self.rows,self.cols,
        # len(layers_pathlist)),dtype='int16',interleave='bsq',ext='.bsq', force=True) # 8bit for muliple masks
        # in one file
        # File_memmap = FileObj.open_memmap(writable=True)
        # File_memmap[:,:,idx] = current_band.GetRasterBand(1).ReadAsArray()


"""********Help_functions**************************************************"""


def ndarray2gdal(ndarray, outPath=None, importFile=None, direction=1, GDAL_Type="ENVI", geotransform=None,
                 projection=None, v=0):
Daniel Scheffler's avatar
Daniel Scheffler committed
763
764
    """Converts a numpy array to a Georasterdataset (default envi bsq).

765
    bis jetzt nur georeferenzierung und projectionszuweisung durch import aus anderem file möglich
Daniel Scheffler's avatar
Daniel Scheffler committed
766

767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
    :param ndarray:         [bands, rows, cols]
    :param outPath:         Path were to store the outputFile
    :param importFile:      path of a file, where to import the projection and mapinfos
    :param direction:
    :param GDAL_Type:
    :param geotransform:    gdal list for geotransformation [originX, pixelWidth, rot1, originY, pixelHeight, rot2]
    :param projection:      a gdal compatible projection string
                            -> if importFile is not availabele geotransform and projection need to be set,
                            otherwise a gdaldata set without coordinate system will be created
    :param v:
    :return:                GDAL data File
    """

    if v:
        print("\n--------GEOPROCESSING--------\n##Function##"
              "\n**ndarray2gdal**")
    assert outPath is not None, "\n   >>> ERROR: Name of outputfile required"
    if importFile is not None:
        assert os.path.isfile(importFile), \
            "\n   >>> ERROR: File for importing mapprojections does not exists: -> GEOPROCESSING.ndarray2gdal"
    if GDAL_Type != 'MEM':
        if not os.path.isdir(os.path.dirname(outPath)):
            os.makedirs(os.path.dirname(outPath))
        if os.path.exists(outPath):
            os.remove(outPath)

    # main
    if len(ndarray.shape) == 2:  # convert 2 dimensional array to 3 dimensional array
        ndarray = np.reshape(ndarray, (1, ndarray.shape[0], ndarray.shape[1]))

    if direction == 1:  # [bands, rows, cols]
        pass
    if direction == 2:  # [rows, bands, cols]
        ndarray = np.swapaxes(ndarray, 0, 1)
    if direction == 3:  # [rows, cols, bands]
        ndarray = np.rollaxis(ndarray, 2)

    bands, rows, cols = ndarray.shape

    # get gdal dataType depending on numpy datatype
    gdal_dtype_name = convertGdalNumpyDataType(ndarray.dtype.type)
    gdal_dtype = gdal.GetDataTypeByName(gdal_dtype_name)

    if v:
        print("\n\tnew dataset:\n\t  name: %s\n\t  bands: %s\n\t  rows %s\n\t  cols: %s\n\t  GDALtype: %s" % (
            os.path.split(outPath)[1], str(bands), str(rows), str(cols), gdal_dtype_name))
    # register outputdriver
    driver = gdal.GetDriverByName(GDAL_Type)
    driver.Register()
    # Create new gdalfile:  Create(<filename>, <xsize>, <ysize>, [<bands>], [<GDALDataType>]) bands is optional and
    # defaults to 1 GDALDataType is optional and defaults to GDT_Byte
    outDs = driver.Create(outPath, cols, rows, bands, gdal_dtype)
    assert outDs is not None, 'Could not create OutputData'

    for i in range(bands):
        # write outputband
        outBand = outDs.GetRasterBand(i + 1)
        outBand.WriteArray(ndarray[i, :, :], 0, 0)

        # flush data to disk, set the NoData value and calculate stats
        outBand.FlushCache()
        del outBand

    # import georeference and projection from other dataset
    if importFile is not None:
        gdal.AllRegister()
        inDs = gdal.Open(importFile, GA_ReadOnly)
        outDs.SetGeoTransform(inDs.GetGeoTransform())
        outDs.SetProjection(inDs.GetProjection())
    elif geotransform is not None and projection is not None:
        outDs.SetGeoTransform(geotransform)
        outDs.SetProjection(projection)
    if GDAL_Type == 'MEM':  # FIXME geändert von GDAL_Type != 'MEM' (sinnlos!) -> checken, ob L1AP noch läuft
        del outDs
    else:
        return outDs


def convertGdalNumpyDataType(dType):
Daniel Scheffler's avatar
Daniel Scheffler committed
846
    """convertGdalNumpyDataType
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
    input:
        dType: GDALdataType string or numpy dataType
    output:
        corresponding dataType
    """
    # dictionary to translate GDAL data types (strings) in corresponding numpy data types
    dTypeDic = {"Byte": np.uint8, "UInt16": np.uint16, "Int16": np.int16, "UInt32": np.uint32, "Int32": np.int32,
                "Float32": np.float32, "Float64": np.float64, "GDT_UInt32": np.uint32}
    outdType = None

    if dType in dTypeDic:
        outdType = dTypeDic[dType]
    elif dType in dTypeDic.values():
        for i in dTypeDic.items():
            if dType == i[1]:
                outdType = i[0]
    elif dType in [np.int8, np.int64, np.int]:
        outdType = "Int32"
        print(">>>  Warning: %s is converted to GDAL_Type 'Int_32'\n" % dType)
    elif dType in [np.bool, np.bool_]:
        outdType = "Byte"
        print(">>>  Warning: %s is converted to GDAL_Type 'Byte'\n" % dType)
    elif dType in [np.float]:
        outdType = "Float32"
        print(">>>  Warning: %s is converted to GDAL_Type 'Float32'\n" % dType)
    elif dType in [np.float16]:
        outdType = "Float32"
        print(">>>  Warning: %s is converted to GDAL_Type 'Float32'\n" % dType)
    else:
        raise Exception('GEOP.convertGdalNumpyDataType: Unexpected input data type %s.' % dType)
    return outdType


def get_point_bounds(points):
    mp_points = MultiPoint(points)
    (min_lon, min_lat, max_lon, max_lat) = mp_points.bounds
    return min_lon, min_lat, max_lon, max_lat


def get_common_extent(list_extentcoords, alg='outer', return_box=True):
    """Returns the common extent coordinates of all given coordinate extents.
    NOTE: this function asserts that all input coordinates belong to the same projection!

    :param list_extentcoords:   a list of coordinate sets, e.g. [ [ULxy1,URxy1,LRxy1,LLxy1], ULxy2,URxy2,LRxy2,LLxy2],]
    :param alg:                 'outer': return the outer Polygon extent
                                'inner': return the inner Polygon extent
    :param return_box:          whether to return a coordinate box/envelope of the output Polygon
    :return:    [ULxy,URxy,LRxy,LLxy]
    """
    if alg != 'outer':
        raise NotImplementedError  # TODO apply shapely intersection

    allPolys = [Polygon(extentcoords).envelope for extentcoords in list_extentcoords]
    common_extent = cascaded_union(allPolys)

    def get_coordsXY(shpPoly): return np.swapaxes(np.array(shpPoly.exterior.coords.xy), 0, 1).tolist()

    return get_coordsXY(common_extent) if not return_box else get_coordsXY(common_extent.envelope)


def zoom_2Darray_to_shapeFullArr(arr2D, shapeFullArr, meshwidth=1, subset=None, method='linear'):
908
909
    from scipy.interpolate import RegularGridInterpolator

910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
    assert method in ['linear', 'nearest']
    rS, rE, cS, cE = list(get_subsetProps_from_subsetArg(shapeFullArr, subset).values())[3:7]
    rowpos = np.linspace(0, shapeFullArr[0] - 1, arr2D.shape[0])
    colpos = np.linspace(0, shapeFullArr[1] - 1, arr2D.shape[1])

    rgi = RegularGridInterpolator([rowpos, colpos], arr2D, method=method)
    out_rows_grid, out_cols_grid = np.meshgrid(range(rS, rE, meshwidth), range(cS, cE, meshwidth), indexing='ij')
    return rgi(np.dstack([out_rows_grid, out_cols_grid]))


def adjust_acquisArrProv_to_shapeFullArr(arrProv, shapeFullArr, meshwidth=1, subset=None, bandwise=False):
    assert isinstance(arrProv, dict) and isinstance(arrProv[list(arrProv.keys())[0]], list), \
        'Expected a dictionary with band names (from LayerbandsAssignment) as keys and lists as ' \
        'values. Got %s.' % type(arrProv)

    arrProv = {k: np.array(v) for k, v in arrProv.items()}
    shapes = [v.shape for v in arrProv.values()]

    assert len(
        list(set(shapes))) == 1, 'The arrays contained in the values of arrProv have different shapes. Got %s.' % shapes

    if bandwise:
        outDict = {k: zoom_2Darray_to_shapeFullArr(arr, shapeFullArr, meshwidth, subset) for k, arr in arrProv.items()}
        return outDict
    else:
935
        arr2interp = np.mean(np.dstack(list(arrProv.values())), axis=2)
936
937
938
939
940
941
        interpolated = zoom_2Darray_to_shapeFullArr(arr2interp, shapeFullArr, meshwidth, subset).astype(np.float32)
        return interpolated


def DN2Rad(ndarray, offsets, gains, inFill=None, inZero=None, inSaturated=None, cutNeg=True):
    # type: (np.ndarray,list,list,int,int,int,bool) -> np.ndarray
Daniel Scheffler's avatar
Daniel Scheffler committed
942
943
944
945
    """Convert DN to Radiance [W * m-2 * sr-1 * micrometer-1].

    NOTE: InputGains and Offsets should be in [W * m-2 * sr-1 * micrometer-1]!!!

946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
    :param ndarray:     <np.ndarray> array of DNs to be converted into radiance
    :param offsets:     [W * m-2 * sr-1 * micrometer-1]:
                        list that includes the offsets of the individual rasterbands [offset_band1, offset_band2,
                        ... ,offset_bandn] or optional input as number if Dataset has only 1 Band
    :param gains:       [W * m-2 * sr-1 * micrometer-1]:
                        list that includes the gains of the individual rasterbands [gain_band1, gain_band2, ... ,
                        gain_bandn] or optional input as number if Dataset has only 1 Band
    :param inFill:      pixelvalues allocated to background/dummy/fill pixels
    :param inZero:      pixelvalues allocated to zero radiance
    :param inSaturated: pixelvalues allocated to saturated pixels
    :param cutNeg:      cutNegvalues -> all negative values set to 0
    """
    assert isinstance(offsets, list) and isinstance(gains, list), \
        "Offset and Gain parameters have to be provided as two lists containing gains and offsets for \
        each band in ascending order. Got offsets as type '%s' and gains as type '%s'." % (type(offsets), type(gains))

    bands = 1 if ndarray.ndim == 2 else ndarray.shape[2]
    for arg, argname in zip([offsets, gains], ['offsets', 'gains']):
        assert len(arg) == bands, """Argument '%s' does not match the number of bands.
            Expected a list of %s %s values for each band in ascending order. Got %s.""" \
                                  % (argname, bands, argname, len(arg))
        for i in arg:
            assert isinstance(i, float) or isinstance(i, int), \
                "DN2Rad: Expected float or integer values from argument '%s'. Got %s" % (argname, type(i))

    if [inFill, inZero, inSaturated] == [None, None, None]:
        inFill, inZero, inSaturated = get_outFillZeroSaturated(ndarray.dtype)
    # --Define default for Special Values of reflectanceband
    outFill, outZero, outSaturated = get_outFillZeroSaturated('int16')

    off, gai = [np.array(param).reshape(1, 1, bands) for param in [offsets, gains]]
    rad = (10 * (off + ndarray * gai)).astype(np.int16)
    rad = np.where(rad < 0, 0, rad) if cutNeg else rad
    rad = np.where(ndarray == inFill, outFill, rad) if inFill is not None else rad
    rad = np.where(ndarray == inSaturated, outSaturated, rad) if inSaturated is not None else rad
    rad = np.where(ndarray == inZero, outZero, rad) if inZero is not None else rad
    # rad = np.piecewise(rad,[ndarray==inFill,ndarray==inSaturated,ndarray==inZero],[outFill,outSaturated,outZero])

    return rad


def DN2TOARef(ndarray, offsets, gains, irradiances, zenith, earthSunDist,
              inFill=None, inZero=None, inSaturated=None, cutNeg=True):
    # type: (np.ndarray,list,list,list,float,float,int,int,int,bool) -> np.ndarray
    """Converts DN data to TOA Reflectance.
Daniel Scheffler's avatar
Daniel Scheffler committed
991

992
993
994
995
996
997
998
999
1000
    :param ndarray:         <np.ndarray> array of DNs to be converted into TOA reflectance
    :param offsets:         list: of offsets of each rasterband [W * m-2 * sr-1 * micrometer-1]
                            [offset_band1, offset_band2, ... ,offset_bandn] or optional as number if Dataset has
                            only 1 Band
    :param gains:           list: of gains of each rasterband [W * m-2 * sr-1 * micrometer-1]
                            [gain_band1, gain_band2, ... ,gain_bandn] or optional as number if Dataset has
                            only 1 Band
    :param irradiances:     list: of irradiance of each band [W * m-2 * micrometer-1]
                            [irradiance_band1, irradiance_band2, ... ,irradiance_bandn]
For faster browsing, not all history is shown. View entire blame