Unit 24 - Spatio-temporal scripting

There is another GRASS Python library to be introduced - GRASS GIS Temporal Framework.

In a script below similar computation like in Unit 11 - PyGRASS scripting and Unit 12 - Script User Interface will be performed. But instead of processing single Sentinel scene, a spatio-temporal dataset of multiple Sentinel scenes will be processed.

Let’s define input and output parameters:

  • b4 - Name of input 4th band space time raster dataset (line 19)
  • b8 - Name of input 8th band space time raster dataset (line 23)
  • clouds - Name of the input mask (region+clouds) space time raster dataset (line 27)
  • clouds - Name for output stats file (line 30)
  • basename - Basename for output raster maps (line 33)
  • threshold - Threshold for removing small areas (line 38)

Focus on functions used from GRASS GIS Temporal Framework:

  • initialization must be done by init function, see line 138
  • space time datasets are open on lines 140-142 by open_old_stds
  • raster maps registered in reference dataset (b4) are listed on line 146 by get_registered_maps
  • related raster maps in two other datasets (b8, cl) are searched on lines 149-152 by get_registered_maps with where parameter
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
#!/usr/bin/env python
#
##############################################################################
#
# MODULE:       ndvi-tgrass-v1
#
# AUTHOR(S):    martin
#
# PURPOSE:      NDVI TGRASS version 1
#
# DATE:         Sat Feb  3 15:45:35 2018
#
##############################################################################

#%module
#% description: NDVI TGRASS script version 1
#%end                
#%option G_OPT_STRDS_INPUT
#% key: b4
#% description: Name of input 4th band space time raster dataset
#%end
#%option G_OPT_STRDS_INPUT
#% key: b8
#% description: Name of input 8th band space time raster dataset
#%end
#%option G_OPT_STRDS_INPUT
#% key: mask
#% description: Name of input mask space time raster dataset
#%end
#%option G_OPT_F_OUTPUT
#%end
#%option
#% key: basename
#% description: Basename for output raster maps
#% required: yes
#%end
#%option
#% key: threshold
#% description: Threshold for removing small areas
#% answer: 1600
#%end

import sys
import os
import atexit

from grass.pygrass.modules import Module
from grass.script import parser
from grass.script.vector import vector_db_select
    
def cleanup():
    Module('g.remove', flags='f', name='ndvi', type='raster')
    Module('g.remove', flags='f', name='ndvi_class', type='raster')
    Module('g.remove', flags='f', name='ndvi_class', type='vector')

def compute(b4, b8, msk, output):

    Module("g.region",
           overwrite = True,
           vector = msk,
           align = b4)

    Module("r.mask",
           overwrite = True,
           raster = msk)

    Module("i.vi",
           overwrite = True,
           red = b4,
           output = "ndvi",
           nir = b8)
                
    recode_str="""-1:0.1:1
0.1:0.5:2
0.5:1:3"""

    Module("r.recode",
           overwrite = True,
           input = "ndvi",
           output = "ndvi_class",
           rules = "-",
           stdin_ = recode_str)

    colors_str="""1 grey
2 255 255 0
3 green"""
    Module("r.colors",
           map = "ndvi_class",
           rules = "-",
           stdin_ = colors_str)
    
    Module("r.to.vect",
           flags = 'sv',
           overwrite = True,
           input = "ndvi_class",
           output = "ndvi_class",
           type = "area")

    Module("v.clean",
           overwrite = True,
           input = "ndvi_class",
           output = output,
           tool = "rmarea",
           threshold = options['threshold'])

def stats(output, date, fd):
    fd.write('-' * 80)
    fd.write(os.linesep)
    fd.write('NDVI class statistics ({0}: {1})'.format(output, date))
    fd.write(os.linesep)
    fd.write('-' * 80)
    fd.write(os.linesep)
    from subprocess import PIPE
    ret = Module('v.report', map=output, option='area',
                 stdout_=PIPE)
    for line in ret.outputs.stdout.splitlines()[1:]: # skip first line (cat|label|area)
        # parse line (eg. 1||2712850)
        data = line.split('|')
        cat = data[0]
        area = float(data[-1])
        fd.write('NDVI class {0}: {1:.1f} ha'.format(cat, area/1e4))
        fd.write(os.linesep)

    # v.to.rast: use -c flag for updating statistics if exists
    Module('v.rast.stats', flags='c', map=output, raster='ndvi',
           column_prefix='ndvi', method=['minimum','maximum','average'])
    
    data = vector_db_select(output)
    for vals in data['values'].itervalues():
        # unfortunately we need to cast values by float
        fd.write('NDVI class {0}: {1:.4f} (min) {2:.4f} (max) {3:.4f} (mean)'.format(
            vals[0], float(vals[2]), float(vals[3]), float(vals[4])))
        fd.write(os.linesep)
        
def main():
    import grass.temporal as tgis

    tgis.init()

    sp4 = tgis.open_old_stds(options['b4'], 'raster')
    sp8 = tgis.open_old_stds(options['b8'], 'raster')
    msk = tgis.open_old_stds(options['mask'], 'raster')

    idx = 1
    fd = open(options['output'], 'w')
    for item in sp4.get_registered_maps(columns='name,start_time'):
        b4 = item[0]
        date=item[1]
        b8 = sp8.get_registered_maps(columns='name',
                                     where="start_time = '{}'".format(date))[0][0]
        ms = msk.get_registered_maps(columns='name',
                                     where="start_time = '{}'".format(date))[0][0]
        output = '{}_{}'.format(options['basename'], idx)
        compute(b4, b8, ms, output)
        stats(output, date, fd)
        cleanup()
        idx += 1

    fd.close()
    
    return 0

if __name__ == "__main__":
    options, flags = parser()
    sys.exit(main())

Example of usage:

ndvi-tgrass.py b4=b4 b8=b8 clouds=clouds basename=ndvi_t output=stats.txt
--------------------------------------------------------------------------------
NDVI class statistics (ndvi_t_1: 2017-05-06 10:50:31)
--------------------------------------------------------------------------------
NDVI class 1: 6714.4 ha
NDVI class 2: 11480.8 ha
NDVI class 3: 29852.3 ha
NDVI class 1: -0.9929 (min) 0.9928 (max) -0.3230 (mean)
NDVI class 2: -0.9512 (min) 0.9993 (max) 0.3327 (mean)
NDVI class 3: -0.9512 (min) 0.9988 (max) 0.7312 (mean)
...
--------------------------------------------------------------------------------
NDVI class statistics (ndvi_t_4: 2017-07-05 10:50:31)
--------------------------------------------------------------------------------
NDVI class 1: 24122.4 ha
NDVI class 2: 7243.5 ha
NDVI class 3: 16682.1 ha
NDVI class 1: -0.9914 (min) 0.9710 (max) -0.0292 (mean)
NDVI class 2: -0.9286 (min) 0.9487 (max) 0.2506 (mean)
NDVI class 3: -0.9545 (min) 0.9982 (max) 0.8190 (mean)

Note

Script will run for a while in the case of Oslo region.

Sample script to download: ndvi-tgrass-v1.py