raster.py 2.2 KB

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