raster.py 2.5 KB

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