Unit 21 - Spatio-temporal scripting

Warning

Materials under construction!

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

In script below we will do similar computation like in Unit 12 - Script User Interface. But with a small difference. We will not process only one Sentinel scene, but spatio-temporal dataset of multiple Sentinel scenes.

Let’s define input and output parameters:

  • region - Name of input vector region map (line 19)
  • b4 - Name of input 4th band space time raster dataset (line 24)
  • b8 - Name of input 8th band space time raster dataset (line 29)
  • clouds - Name of the input clouds space time raster dataset (line 32)
  • basename - Basename for output raster maps (line 38)
  • threshold - Threshold for removing small areas (line 43)

Let’s focus on functions used from GRASS GIS Temporal Framework:

  • initialization must be done by init, see line 155
  • space time datasets are open on lines 157-159 by open_old_stds
  • raster maps registered in reference dataset (b4) are listed on line 163 by get_registered_maps
  • related raster maps in two other datasets (b8, cl) are searched on lines 166-169 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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
#!/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_V_INPUT
#% key: region
#% description: Name of input vector region map 
#% answer: jena_boundary@PERMANENT
#%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: clouds
#% description: Name of input clouds 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='region_mask', type='vector')
    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, cl, output):

    if cl:
        region_mask = "region_mask"
        Module("v.overlay",
               overwrite = True,
               ainput = options["region"],
               binput = cl,
               operator = "not",
               output = region_mask)
    else:
        region_mask = options["region"]

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

    Module("r.mask",
           overwrite = True,
           vector = region_mask)

    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')
    spc = tgis.open_old_stds(options['clouds'], '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]
        cl = spc.get_registered_maps(columns='name',
                                     where="start_time = '{}'".format(date))[0][0]
        output = '{}_{}'.format(options['basename'], idx)
        compute(b4, b8, cl, 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 out=stats.txt

Possible output:

--------------------------------------------------------------------------------
NDVI class statistics (ndvi_1: 2017-05-17 10:20:31)
--------------------------------------------------------------------------------
NDVI class 1: 227.6 ha
NDVI class 2: 1565.3 ha
NDVI class 3: 9643.5 ha
NDVI class 1: -0.5690 (min) 0.7275 (max) 0.0496 (mean)
NDVI class 2: -0.4697 (min) 0.9789 (max) 0.3135 (mean)
NDVI class 3: -0.2160 (min) 0.9993 (max) 0.7998 (mean)
...
--------------------------------------------------------------------------------
NDVI class statistics (ndvi_7: 2017-11-03 10:22:01)
--------------------------------------------------------------------------------
NDVI class 1: 156.2 ha
NDVI class 2: 2549.5 ha
NDVI class 3: 8730.5 ha
NDVI class 1: -0.6170 (min) 0.6725 (max) 0.0495 (mean)
NDVI class 2: -0.9977 (min) 0.9989 (max) 0.3215 (mean)
NDVI class 3: -0.1564 (min) 0.9994 (max) 0.6794 (mean)

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