import grass.script as gscript

"""
Explanation: Introduction to the GRASS GIS 7 Python Scripting Library
The GRASS GIS 7 Python Scripting Library provides functions to call GRASS modules within scripts as subprocesses.
The most often used functions include:
* run_command: most often used with modules which output raster/vector data where text output is not expected
* read_command: used when we are interested in text output
* parse_command: used with modules producing text output as key=value pair
* write_command: for modules expecting text input from either standard input or file
Besides, this library provides several wrapper functions for often called modules.
Calling GRASS GIS modules
We start by importing GRASS GIS Python Scripting Library:
End of explanation
"""


gscript.run_command('g.region', raster='elevation')

"""
Explanation: Before running any GRASS raster modules, you need to set the computational region using g.region. In this example, we set the computational extent and resolution to the raster layer elevation.
End of explanation
"""


gscript.run_command('r.neighbors', input='elevation', output='elev_smoothed', method='average', flags='c')

"""
Explanation: The run_command() function is the most commonly used one. Here, we apply the focal operation average (r.neighbors) to smooth the elevation raster layer. Note that the syntax is similar to bash syntax, just the flags are specified in a parameter.
End of explanation
"""


from render import view
view(rasters=['elev_smoothed'])

"""
Explanation: Specifics of interactive interpreters
When using the GUI, we can look at the map right away. In scripts, we rarely render a map. In IPython Notebook we are able to show a map as a result. For this we use function view() from a custom Python module render supplied with these notebooks. (This function might be part of GRASS GIS Python API for IPython in the future.)
End of explanation
"""


import os
os.environ['GRASS_OVERWRITE'] = '1'

"""
Explanation: To simplify the re-running of examples, we set the environmental variable GRASS_OVERWRITE,
which allows direct overwriting of results from previous runs, bypassing the overwrite checks.
End of explanation
"""


gscript.set_raise_on_error(True)

"""
Explanation: When an unrecoverable error occurs (due to incorrect parameter use or other issues), the GRASS GIS functions usually print the error message and end the program execution (by calling the exit() function). However, when working in an interactive environment such as IPython, the behavior can be changed using set_raise_on_error() function. The following call will cause GRASS GIS Python functions to raise an exception instead of calling exit().
End of explanation
"""


print(gscript.read_command('g.region', flags='p'))

print(gscript.read_command('r.univar', map='elev_smoothed', flags='g'))

"""
Explanation: Calling GRASS GIS modules with textual input or output
Textual output from modules can be captured using the read_command() function.
End of explanation
"""


gscript.parse_command('g.proj', flags='g')

"""
Explanation: Certain modules can produce output in key-value format which is enabled by the g flag. The parse_command() function automatically parses this output and returns a dictionary. In this example, we call g.proj to display the projection parameters of the actual location.
End of explanation
"""


print(gscript.read_command('g.proj', flags='g'))

"""
Explanation: For comparison, below is the same example, but using the read_command() function.
End of explanation
"""


gscript.write_command('v.in.ascii', input='-', stdin='%s|%s' % (635818.8, 221342.4), output='view_point')

"""
Explanation: Certain modules require the text input be in a file or provided as standard input. Using the write_command() function we can conveniently pass the string to the module. Here, we are creating a new vector with one point with v.in.ascii.
Note that stdin parameter is not used as a module parameter, but its content is passed as standard input to the subprocess.
End of explanation
"""


gscript.vector_info('view_point')

"""
Explanation: Convenient wrapper functions
Some modules have wrapper functions to simplify frequent tasks.
We can obtain the information about the vector layer which we just created with the v.info wrapper.
End of explanation
"""


gscript.raster_what('elevation', [[635818.8, 221342.4], [635710, 221330]])

"""
Explanation: It is also possible to retrieve the raster layer history (r.support) and layer information (r.info) or to query (r.what) raster layer pixel values.
End of explanation
"""


gscript.mapcalc("elev_strip = if(elevation > 100 && elevation < 125, elevation, null())")
print(gscript.read_command('r.univar', map='elev_strip', flags='g'))

"""
Explanation: As another example, the r.mapcalc wrapper for raster algebra allows using a long expressions.
End of explanation
"""


region = gscript.region()
print region
# cell area in map units (in projected Locations)
region['nsres'] * region['ewres']

"""
Explanation: The g.region wrapper is a convenient way to retrieve the current region settings (i.e., computational region). It returns a dictionary with values converted to appropriate types (floats and ints).
End of explanation
"""


gscript.list_grouped(['raster'])

"""
Explanation: We can list data stored in a GRASS GIS location with g.list wrappers. With this function, the map layers are grouped by mapsets (in this example, raster layers):
End of explanation
"""


current_mapset = gscript.gisenv()['MAPSET']
gscript.list_pairs('raster', mapset=current_mapset)

"""
Explanation: Here is an example of a different g.list wrapper which structures the output as list of pairs (name, mapset).
We obtain current mapset with g.gisenv wrapper.
End of explanation
"""


