Unit 22 - Spatio-temporal scripting

GRASS offers a Python API for space-time processing. The usage is presented in the script described below.

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

UI

Let’s define input and output parameters of the script:

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

Python Temporal API

Functions from GRASS GIS Temporal Framework:

  • initialization must be done by init function, see line 144
  • space time datasets are open on lines 146-148 by open_old_stds
  • raster maps registered in reference dataset (b4) are listed on line 152 by get_registered_maps
  • related raster maps in two other datasets (b8, cl) are searched on lines 155-158 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
#!/usr/bin/env python3
#
##############################################################################
#
# 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,
           raster = 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'])

    Module("v.colors",
           map=output,
           layer="1",
           use="cat",
           raster="ndvi_class")
    
def stats(output, date, fd):
    fd.write('-' * 80)
    fd.write('\n')
    fd.write('NDVI class statistics ({0}: {1})'.format(output, date))
    fd.write('\n')
    fd.write('-' * 80)
    fd.write('\n')
    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('\n')

    # 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'].values():
        # 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('\n')
        
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())

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

Example of usage:

ndvi-tgrass.py b4=b4 b8=b8 mask=clouds basename=ndvi out=stats.txt

Possible output:

--------------------------------------------------------------------------------
NDVI class statistics (ndvi_1: 2019-04-07 10:20:21)
--------------------------------------------------------------------------------
NDVI class 1: 182.4 ha
NDVI class 2: 4923.4 ha
NDVI class 3: 6330.2 ha
NDVI class 1: -0.2073 (min) 0.4915 (max) 0.0554 (mean)
NDVI class 2: -0.2380 (min) 0.9989 (max) 0.3736 (mean)
NDVI class 3: -0.4533 (min) 0.9988 (max) 0.6468 (mean)
...
--------------------------------------------------------------------------------
NDVI class statistics (ndvi_7: 2019-10-14 10:20:31)
--------------------------------------------------------------------------------
NDVI class 1: 163.4 ha
NDVI class 2: 2669.2 ha
NDVI class 3: 8603.6 ha
NDVI class 1: -0.2253 (min) 0.7481 (max) 0.0457 (mean)
NDVI class 2: -1.0000 (min) 0.9994 (max) 0.2999 (mean)
NDVI class 3: -0.9978 (min) 0.9994 (max) 0.6992 (mean)