raster.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. """!@package grass.script.raster
  2. @brief GRASS Python scripting module
  3. Raster related functions to be used in Python scripts.
  4. Usage:
  5. @code
  6. from grass.script import core, raster as grass
  7. grass.parser()
  8. grass.raster_history(map)
  9. ...
  10. @endcode
  11. (C) 2008-2009 by the GRASS Development Team
  12. This program is free software under the GNU General Public
  13. License (>=v2). Read the file COPYING that comes with GRASS
  14. for details.
  15. @author Glynn Clements
  16. @author Martin Landa <landa.martin gmail.com>
  17. """
  18. import os
  19. import string
  20. from core import *
  21. # add raster history
  22. def raster_history(map):
  23. """!Set the command history for a raster map to the command used to
  24. invoke the script (interface to `r.support').
  25. @param map map name
  26. @return True on success
  27. @return False on failure
  28. """
  29. current_mapset = gisenv()['MAPSET']
  30. if find_file(name = map)['mapset'] == current_mapset:
  31. run_command('r.support', map = map, history = os.environ['CMDLINE'])
  32. return True
  33. warning("Unable to write history for <%s>. Raster map <%s> not found in current mapset." % (map, map))
  34. return False
  35. # run "r.info -rgstmpud ..." and parse output
  36. def raster_info(map):
  37. """!Return information about a raster map (interface to
  38. `r.info'). Example:
  39. \code
  40. >>> grass.raster_info('elevation')
  41. {'north': 228500.0, 'timestamp': '"none"', 'min': 55.578792572021499,
  42. 'datatype': 'FCELL', 'max': 156.32986450195301, 'ewres': 10.0,
  43. 'vertical_datum': '', 'west': 630000.0, 'units': '',
  44. 'title': 'South-West Wake county: Elevation NED 10m (elev_ned10m)',
  45. 'east': 645000.0, 'nsres': 10.0, 'south': 215000.0}
  46. \endcode
  47. @param map map name
  48. @return parsed raster info
  49. """
  50. s = read_command('r.info', flags = 'rgstmpud', map = map)
  51. kv = parse_key_val(s)
  52. for k in ['min', 'max', 'north', 'south', 'east', 'west']:
  53. kv[k] = float(kv[k])
  54. for k in ['nsres', 'ewres']:
  55. kv[k] = float_or_dms(kv[k])
  56. return kv
  57. # interface to r.mapcalc
  58. def mapcalc(exp, **kwargs):
  59. """!Interface to r.mapcalc.
  60. @param exp expression
  61. @param kwargs
  62. """
  63. t = string.Template(exp)
  64. e = t.substitute(**kwargs)
  65. if run_command('r.mapcalc', expression = e) != 0:
  66. fatal("An error occurred while running r.mapcalc")