Unit 26 - MODIS ST scripting¶
Let’s create a simple Python script for computing LST statistics in Germany area for given period. Input parameters:
- input - Name of the input space time raster dataset (line 6)
- start - Start date (line 9)
- end - End date (line 15)
The script prints minimum, maximum and mean LST value. The raster map for computing statistics is created by t.rast.series (line 50), statistics is computed by r.univar (line 60). Statistics will be printed by lines 66-68.
In Unit 25 - MODIS ST we processed LST space time dataset only for year 2019. We will also check if input dates are valid, see line 31.
Tip
Verbosity level can be set globally by GRASS_VERBOSE
environment variable, see line 47.
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 | #!/usr/bin/env python3
#%module
#% description: Computes LST stats for given period (limited to Germany and 2019).
#%end
#%option G_OPT_STRDS_INPUT
#%end
#%option
#% key: start
#% description: Start date (eg. 2019-03-01)
#% type: string
#% required: yes
#%end
#%option
#% key: end
#% description: End date (eg. 2019-04-01)
#% type: string
#% required: yes
#%end
import os
import sys
import atexit
from datetime import datetime
from subprocess import PIPE
import grass.script as gs
from grass.pygrass.modules import Module
from grass.exceptions import CalledModuleError
def check_date(date_str):
d = datetime.strptime(date_str, '%Y-%m-%d')
if d.year != 2019:
gs.fatal("Only year 2019 allowed")
def cleanup():
try:
Module('g.remove', flags='f', type='raster', name=output)
except CalledModuleError:
pass
def main():
check_date(options['start'])
check_date(options['end'])
# be silent
os.environ['GRASS_VERBOSE'] = '0'
try:
Module('t.rast.series',
input=options['input'],
output=output,
method='average',
where="start_time > '{start}' and start_time < '{end}'".format(
start=options['start'], end=options['end']
))
except CalledModuleError:
gs.fatal('Unable to compute statistics')
ret = Module('r.univar',
flags='g',
map=output,
stdout_=PIPE
)
stats = gs.parse_key_val(ret.outputs.stdout)
print('Min: {0:.1f}'.format(float(stats['min'])))
print('Max: {0:.1f}'.format(float(stats['max'])))
print('Mean: {0:.1f}'.format(float(stats['mean'])))
if __name__ == "__main__":
options, flags = gs.parser()
output = '{}_{}'.format(
options['input'].split('@')[0], os.getpid()
)
atexit.register(cleanup)
sys.exit(main())
|
Sample script to download: modis-date-stats.py
Example of usage:
modis-date-stats.py input=modis_c start=2019-03-01 end=2019-04-01
Min: -8.3
Max: 12.6
Mean: 7.3