LandscapeStratificationMetric.py 19.2 KB
Newer Older
Gaetano Raffaele's avatar
Gaetano Raffaele committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# -*- coding: utf-8 -*-

"""
***************************************************************************
*                                                                         *
*   This program is free software; you can redistribute it and/or modify  *
*   it under the terms of the GNU General Public License as published by  *
*   the Free Software Foundation; either version 2 of the License, or     *
*   (at your option) any later version.                                   *
*                                                                         *
***************************************************************************
"""

from qgis.PyQt.QtCore import QCoreApplication
15
from qgis.core import (QgsProcessingAlgorithm,
Gaetano Raffaele's avatar
Gaetano Raffaele committed
16
17
18
19
20
                       QgsProcessingParameterFolderDestination,
                       QgsProcessingParameterFile,
                       QgsProcessingParameterString,
                       QgsProcessingParameterNumber,
                       QgsProcessingParameterVectorLayer,
21
                       QgsProcessingContext)
Gaetano Raffaele's avatar
Gaetano Raffaele committed
22
from qgis import processing
23
from qgis.utils import iface
Gaetano Raffaele's avatar
Gaetano Raffaele committed
24
25
26
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
import ogr
import os
import sys
import gdal
import calendar
import platform
import datetime

def find_next_date(datelist, date):
    for i,l in enumerate(datelist):
        if l >= date:
            return i
    return None

def find_first_month_day(dates, month=1, day=1):
    start_year = dates[0].year
    test_date = datetime.datetime(start_year,month,day)
    if dates[0] > test_date:
        start_year += 1
        test_date = datetime.datetime(start_year, month, day)

    return find_next_date(dates, test_date)

def get_period_intervals(date_file, md=[1,1], duration=365):
    dates = []
    #orig_dates = []
    with open(date_file) as f:
        for l in f.read().splitlines():
            try:
                dates.append(datetime.datetime.strptime(l, '%Y%m%d'))
                #orig_dates.append(l)
            except:
                continue


    periods = []
    s,e = 0,0
    S = 0
    while s is not None and e is not None:
        s = find_first_month_day(dates, md[0], md[1])
        if s is not None:
            e = find_next_date(dates, dates[s] + datetime.timedelta(days=duration))
            if e is not None:
                periods.append((S+s,S+e))
                S += s+1
                dates = dates[s+1:]

    #for p in periods:
    #    print(orig_dates[p[0]],orig_dates[p[1]],p[1]-p[0]+1)

    return periods
    
def get_mean_expression(periods):
    l = periods[0][1]-periods[0][0]+1
    expr = []
    for i in range(1,l+1):
        s = [p[0]+i for p in periods]
        expr.append('(' + '+'.join(['im1b%d' % x for x in s]) + ')/' + str(len(s)))

    return '{' + ';'.join(expr) + '}'

def ModisToYYYYMMDD(raster_list, output):
    dates=[]
    for path in raster_list :
        modisDate = path.split('_')[-2][3:]
        year = int(modisDate[:-3])
        day = int(modisDate[-3:])
        month = 1
        while day - calendar.monthrange(year,month)[1] > 0 and month <= 12:
            day = day - calendar.monthrange(year,month)[1]
            month = month + 1
        month= '0'+str(month) if month < 10 else str(month)
        day= '0'+str(day) if day < 10 else str(day)
        dates.append(str(year)+str(month)+str(day))
    dates.sort()
    with open(output,'w') as f:
        for date in dates:
            f.write(date+'\n')

def NDVI_subdates_maker(TS_file,datefile,output_folder,begin_date,end_date,context,feedback):
    raster_band_list = []
    dates_list= []
    with open(datefile,'r') as f:
        for i,date in enumerate(f):
            if int(date)>=begin_date and int(date) <=end_date:
                raster_band_list.append(i+1)
                dates_list.append(int(date))
    exp=''
    for i in raster_band_list :
        exp+='im1b'+str(i)+';'
    exp=exp[:-1]
    out = os.path.join(output_folder,"sub_ndvi_ts.tif")
    BMX_parameters = {'il':[TS_file],'exp':exp, 'out':out, 'outcontext':os.path.join(output_folder,"outcontext.txt")}
    processing.run('otb:BandMathX',BMX_parameters, context=context, feedback=feedback)
    os.remove(os.path.join(output_folder,"outcontext.txt"))
    
    with open(os.path.join(output_folder,os.path.basename(datefile)),'w') as f:
        for date in dates_list:
            f.write(str(date)+'\n')
    return out, os.path.join(output_folder,os.path.basename(datefile))
            
def setNoDataValue(fn, val=None):
    """ setNoDataValue(fn,val = 0)
    Sets a value for nodata pixels in a raster GDAL dataset.

    INPUT   :   fn      -   GDAL dataset file
                val     -   nodata value (def. 0)

    OUTPUT  :   None
    """
    ds = gdal.Open(fn, gdal.GA_Update)
    for i in range(0, ds.RasterCount):
        band = ds.GetRasterBand(i + 1)
        if val is None:
            band.DeleteNoDataValue()
        else:
            band.SetNoDataValue(val)
        band = None
    ds.FlushCache()
    ds = None

145
146
147
148
149
150
151
152
153
154
155
156
157
158
def getNoDataValue(fn):
    """ getNoDataValue(fn,val = 0)
    Gets the value for nodata pixels in a raster GDAL dataset.

    INPUT   :   fn      -   GDAL dataset file

    OUTPUT  :   no-data value
    """
    ds = gdal.Open(fn)
    band = ds.GetRasterBand(1)
    ndv = band.GetNoDataValue()
    ds = None
    return ndv

Gaetano Raffaele's avatar
Gaetano Raffaele committed
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
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
def moy_NDVI_TS(TS,dates, month, day, duration):
    periods = get_period_intervals(dates, [month,day], duration)
    return get_mean_expression(periods)

class LandscapeStratification(QgsProcessingAlgorithm):
    """
    This is an example algorithm that takes a vector layer and
    creates a new identical one.

    It is meant to be used as an example of how to create your own
    algorithms and explain methods and variables used to do it. An
    algorithm like this will be available in all elements, and there
    is not need for additional work.

    All Processing algorithms should extend the QgsProcessingAlgorithm
    class.
    """

    # Constants used to refer to parameters and outputs. They will be
    # used when calling the algorithm from another algorithm, or when
    # calling from the QGIS console.

    INPUT = 'INPUT'
    INPUTDATE = 'INPUTDATE'
    BEGDATE = 'BEGDATE'
    ENDDATE = 'ENDDATE'
    STARTMONTH = 'STARTMONTH'
    STARTDAY = 'STARTDAY'
    DURATION = 'DURATION'
    CLIP = 'CLIP'
    OUTPUT = 'OUTPUT'
    PREFIX = 'PREFIX'
    CBEGIN = 'CBEGIN'
    CEND = 'CEND'
    SW = 'SW'
    CW = 'CW'
    THRESHOLD = 'THRESHOLD'

    def tr(self, string):
        """
        Returns a translatable string with the self.tr() function.
        """
        return QCoreApplication.translate('Processing', string)

    def createInstance(self):
        return LandscapeStratification()

    def name(self):
        """
        Returns the algorithm name, used for identifying the algorithm. This
        string should be fixed for the algorithm, and must not be localised.
        The name should be unique within each provider. Names should contain
        lowercase alphanumeric characters only and no spaces or other
        formatting characters.
        """
        return 'LandscapeStratification'

    def displayName(self):
        """
        Returns the translated algorithm name, which should be used for any
        user-visible display of the algorithm name.
        """
        return self.tr('LandscapeStratification')

    def group(self):
        """
        Returns the name of the group this algorithm belongs to. This string
        should be localised.
        """
        return self.tr('TSNDVI')

    def groupId(self):
        """
        Returns the unique ID of the group this algorithm belongs to. This
        string should be fixed for the algorithm, and must not be localised.
        The group id should be unique within each provider. Group id should
        contain lowercase alphanumeric characters only and no spaces or other
        formatting characters.
        """
        return 'TSNDVI'

    def shortHelpString(self):
        """
        Returns a localised short helper string for the algorithm. This string
        should provide a basic description about what the algorithm does and the
        parameters and outputs associated with it..
        """
        return self.tr("Compute a landscape stratification metric")

    def initAlgorithm(self, config=None):
        """
        Here we define the inputs and output of the algorithm, along
        with some other properties.
        """

        # We add the input vector features source. It can have any kind of
        # geometry.
        self.addParameter(
            QgsProcessingParameterFile(
                self.INPUT,
                self.tr('Input NDVI stack')
            )
        )

        self.addParameter(
            QgsProcessingParameterFile(
                self.INPUTDATE,
266
267
                self.tr('Input NDVI dates file'),
                optional=True
Gaetano Raffaele's avatar
Gaetano Raffaele committed
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
            )
        )
        self.addParameter(
            QgsProcessingParameterString(
                self.BEGDATE,
                self.tr('Beginning date for selection (YYYYMMDD)'),
                defaultValue='20000101'
            )
        )
        self.addParameter(
            QgsProcessingParameterString(
                self.ENDDATE,
                self.tr('End date for selection (YYYYMMDD)'),
                defaultValue=datetime.date.today().strftime("%Y%m%d")
            )
        )
        self.addParameter(
            QgsProcessingParameterNumber(
                self.STARTMONTH,
                self.tr('Starting month for multi-annual mean'),
                type=0,
                defaultValue=1,
                minValue=1,
                maxValue=12
            )
        )
        self.addParameter(
            QgsProcessingParameterNumber(
                self.STARTDAY,
                self.tr('Starting day for multi-annual mean'),
                type=0,
                defaultValue=1,
                minValue=1,
                maxValue=31
            )
        )
        self.addParameter(
            QgsProcessingParameterNumber(
                self.DURATION,
                self.tr('Period length for multi-annual mean'),
                type=0,
                defaultValue=365,
                minValue=1
            )
        )

        self.addParameter(
            QgsProcessingParameterVectorLayer(
                self.CLIP,
317
318
319
                self.tr('Clip vector layer'),
                optional=True,
                defaultValue=None
Gaetano Raffaele's avatar
Gaetano Raffaele committed
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
            )
        )

        self.addParameter(
            QgsProcessingParameterString(
                self.PREFIX,
                self.tr('Output files prefix'),
                ''
            )
        )
 
        self.addParameter(
            QgsProcessingParameterNumber(
                self.CBEGIN,
                self.tr('Starting PCA component'),
                type=0,
                defaultValue=2))
        self.addParameter(
            QgsProcessingParameterNumber(
                self.CEND,
                self.tr('Final PCA component (0 for last)'),
                type=0,
342
                defaultValue=5))
Gaetano Raffaele's avatar
Gaetano Raffaele committed
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
        self.addParameter(
            QgsProcessingParameterNumber(
                self.SW,
                self.tr('Weight for the spatial homogeneity'),
                type=1,
                defaultValue=0.5,
                minValue=0,
                maxValue=1))
        self.addParameter(
            QgsProcessingParameterNumber(
                self.CW,
                self.tr('Weight for the spectral homogeneity'),
                type=1,
                defaultValue=0.5,
                minValue=0,
                maxValue=1))
        self.addParameter(
            QgsProcessingParameterNumber(
                self.THRESHOLD,
                self.tr('Threshold for Generic region merging operation'),
                defaultValue=850
                ))

        self.addParameter(
            QgsProcessingParameterFolderDestination(
                self.OUTPUT,
                self.tr('Output folder')
            )
        )

    def processAlgorithm(self, parameters, context, feedback):
        """
        Here is where the processing itself takes place.
        """
        if platform.system() == 'Linux':
            sh = False
        elif platform.system() == 'Windows':
            sh = True
        else:
            sys.exit("Platform not supported!")
        # Retrieve the feature source and sink. The 'dest_id' variable is used
        # to uniquely identify the feature sink, and must be included in the
        # dictionary returned by the processAlgorithm function.
        Smooth_TS = self.parameterAsString(
            parameters,
            self.INPUT,
            context
        )
        
        datefile = self.parameterAsString(
            parameters,
            self.INPUTDATE,
            context
        )

        clip = self.parameterAsVectorLayer(
            parameters,
            self.CLIP,
            context
        )

        output_folder = self.parameterAsString(
            parameters,
            self.OUTPUT,
            context
        )

        prefix = parameters['PREFIX'] if parameters['PREFIX'] != None else ''
        if len(prefix)>0 and prefix[-1] != '_':
            prefix+='_'
        begin_date = parameters['BEGDATE'] if parameters['BEGDATE'] != None else 20000101
        end_date = parameters['ENDDATE'] if parameters['ENDDATE'] != None else int(datetime.date.today().strftime("%Y%m%d"))
        #write_temp_files = parameters['KEEPFILES']
        
        threshold=parameters['THRESHOLD']
        cw=parameters['CW']
        sw=parameters['SW']
        cbegin=parameters['CBEGIN']
        cend=parameters['CEND']
422

423
        tmp_name = prefix + 'metrics'
Gaetano Raffaele's avatar
Gaetano Raffaele committed
424
425
426
427
        tmp_folder = os.path.join(output_folder,tmp_name)
        if not os.path.exists(tmp_folder):
            os.mkdir(tmp_folder)

428
429
430
431
432
433
        print('Check Datefile')
        print(datefile)
        if datefile == '':
            datefile = os.path.splitext(Smooth_TS)[0] + '_dates.txt'
        print(datefile)

Gaetano Raffaele's avatar
Gaetano Raffaele committed
434
435
436
437
438
        if int(begin_date)!=20000101 or int(end_date)!=int(datetime.date.today().strftime("%Y%m%d")):
            TS_file, datefile = NDVI_subdates_maker(Smooth_TS,datefile,tmp_folder,int(begin_date),int(end_date),context,feedback)
        else :
            TS_file = Smooth_TS

439
440
441
        ndv = getNoDataValue(TS_file)

        # Compute mean time series over the period
Gaetano Raffaele's avatar
Gaetano Raffaele committed
442
443
444
445
446
        exp = moy_NDVI_TS(TS_file,datefile,parameters['STARTMONTH'], parameters['STARTDAY'], parameters['DURATION'])
        Moy_TS = os.path.join(tmp_folder, prefix+"LandStrat_mean.tif")
        BMX_parameters = {'il':[TS_file],'exp':exp, 'out':Moy_TS, "outputpixeltype":2, 'outcontext':os.path.join(output_folder,"outcontext.txt")}
        processing.run("otb:BandMathX", BMX_parameters, context=context, feedback=feedback)
        os.remove(os.path.join(output_folder,"outcontext.txt"))
447
448
449
450
451
452
453
454
455
456
457
458
459
460
        if ndv is not None:
            setNoDataValue(Moy_TS, ndv)

        # manage mask (nodata from input U clip mask)
        if clip is not None:
            maskc = os.path.join(tmp_folder, prefix+"mask_clip.tif")
            processing.run("otb:Rasterization", {"in":clip,"im":Smooth_TS,"mode.binary.foreground":1,"out":maskc, "outputpixeltype":0}, context=context, feedback=feedback)
            vald = os.path.join(tmp_folder, prefix+"valid.tif")
            ND_app_parameters = {"in": TS_file, "out":vald, "mode":"buildmask", 'mode.apply.mask':maskc, "outputpixeltype":0}
            processing.run('otb:ManageNoData', ND_app_parameters, context=context, feedback=feedback)
            mask = os.path.join(tmp_folder, prefix+"mask.tif")
            BMX_parameters = {'il': [maskc, vald], 'exp':'im1b1*im2b1', 'out':mask, 'outputpixeltype':0, 'outcontext':os.path.join(output_folder,"outcontext.txt")}
            processing.run("otb:BandMathX", BMX_parameters, context=context, feedback=feedback)
            os.remove(os.path.join(output_folder,"outcontext.txt"))
461
462
            #os.remove(maskc)
            #os.remove(vald)
463
464
465
466
467
468
469
470
471
472
473
        else:
            mask = os.path.join(tmp_folder, prefix + "mask.tif")
            ND_app_parameters = {"in": TS_file, "out": mask, "mode": "buildmask", 'mode.apply.mask': TS_file,
                                 "outputpixeltype": 0}
            processing.run('otb:ManageNoData', ND_app_parameters, context=context, feedback=feedback)

        # Compute metric using no-data value
        LS_Strat_pre = os.path.join(tmp_folder, prefix+"LandStrat_metric_pre.tif")
        LS_app_parameters = {"ndvits": Moy_TS, "out": LS_Strat_pre, "outputpixeltype": 5}
        if ndv is not None:
            LS_app_parameters["bv"] = ndv
Gaetano Raffaele's avatar
Gaetano Raffaele committed
474
475
476
477
478
        if cbegin != None :
            LS_app_parameters["cbegin"]=cbegin
        if cend != None :
            LS_app_parameters["cend"]=cend
        processing.run("otb:LandscapeStratificationMetric", LS_app_parameters, context=context, feedback=feedback)
479
480
481
482
483
484

        LS_Strat = os.path.join(tmp_folder, prefix + "LandStrat_metric.tif")
        ND_app_parameters = {'in': LS_Strat_pre, 'out': LS_Strat, 'mode': 'apply', 'mode.apply.mask': mask,
                             'outputpixeltype': 5}
        processing.run('otb:ManageNoData', ND_app_parameters, context=context, feedback=feedback)
        setNoDataValue(LS_Strat, ndv)
Gaetano Raffaele's avatar
Gaetano Raffaele committed
485
486
        
        LS_Strat_norm = os.path.join(tmp_folder, prefix+"LandStrat_metric_norm.tif")
487
        DC_app_parameters={"in":LS_Strat, "out":LS_Strat_norm, "mask":mask, "outmin":0, "outmax":2048, "outputpixeltype":2}
Gaetano Raffaele's avatar
Gaetano Raffaele committed
488
489
        processing.run("otb:DynamicConvert", DC_app_parameters, context=context, feedback=feedback)

490
491
        LS_Strat = os.path.join(tmp_folder,prefix+"LandStrat_metric_norm_masked.tif")
        ND_app_parameters = {'in': LS_Strat_norm, 'out':LS_Strat, 'mode':'apply', 'mode.apply.mask':mask, 'outputpixeltype':2}
Gaetano Raffaele's avatar
Gaetano Raffaele committed
492
        processing.run('otb:ManageNoData', ND_app_parameters, context=context, feedback=feedback)
493
494
        setNoDataValue(LS_Strat, ndv)

495
496
        #os.remove(LS_Strat_pre)
        #os.remove(LS_Strat_norm)
Gaetano Raffaele's avatar
Gaetano Raffaele committed
497

498
499
        GRM_output_pre = os.path.join(tmp_folder,prefix+"LandStrat_map_pre.tif")
        GRM_app_parameters = {'in':LS_Strat, 'threshold':float(threshold), 'criterion':'bs', 'out':GRM_output_pre}
Gaetano Raffaele's avatar
Gaetano Raffaele committed
500
501
502
503
504
        if cw != 0.5:
            GRM_app_parameters['criterion.bs.cw']= cw
        if sw != 0.5:
            GRM_app_parameters['criterion.bs.sw']= sw
        processing.run("otb:LSGRM", GRM_app_parameters, context=context, feedback=feedback)
505
506
507
508
509
510

        GRM_output = os.path.join(tmp_folder, prefix + "LandStrat_map.tif")
        BMX_parameters = {'il': [GRM_output_pre, mask], 'exp': 'im1b1*im2b1', 'out': GRM_output, 'outputpixeltype': 3,
                          'outcontext': os.path.join(output_folder, "outcontext.txt")}
        processing.run("otb:BandMathX", BMX_parameters, context=context, feedback=feedback)
        os.remove(os.path.join(output_folder, "outcontext.txt"))
511
        #os.remove(GRM_output_pre)
Gaetano Raffaele's avatar
Gaetano Raffaele committed
512
        setNoDataValue(GRM_output, 0)
513

Gaetano Raffaele's avatar
Gaetano Raffaele committed
514
515
516
517
518
        GRM_vec_output = os.path.join(output_folder,prefix+"LandscapeStratification.shp")
        if os.path.exists(GRM_vec_output):
            drv = ogr.GetDriverByName('ESRI Shapefile')
            drv.DeleteDataSource(GRM_vec_output)
        processing.run("gdal:polygonize", {'INPUT':GRM_output, 'BAND':1, 'OUTPUT':GRM_vec_output}, context=context, feedback=feedback)
519
520
521
522

        nm = os.path.basename(os.path.splitext(GRM_vec_output)[0])
        context.addLayerToLoadOnCompletion(GRM_vec_output,
                                           QgsProcessingContext.LayerDetails(name=nm, project=context.project()))
Gaetano Raffaele's avatar
Gaetano Raffaele committed
523
524
        
        return {'OUT':GRM_vec_output}