raster.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. """!@package grass.script.raster
  2. @brief GRASS Python scripting module (raster functions)
  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-2011 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. import types
  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 <%(map)s>. "
  34. "Raster map <%(map)s> not found in current mapset." % { 'map' : map, 'map' : map}))
  35. return False
  36. # run "r.info -gre ..." 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. def float_or_null(s):
  52. if s == 'NULL':
  53. return None
  54. else:
  55. return float(s)
  56. s = read_command('r.info', flags = 'gre', map = map)
  57. kv = parse_key_val(s)
  58. for k in ['min', 'max']:
  59. kv[k] = float_or_null(kv[k])
  60. for k in ['north', 'south', 'east', 'west']:
  61. kv[k] = float(kv[k])
  62. for k in ['nsres', 'ewres']:
  63. kv[k] = float_or_dms(kv[k])
  64. return kv
  65. # interface to r.mapcalc
  66. def mapcalc(exp, quiet = False, verbose = False, overwrite = False, **kwargs):
  67. """!Interface to r.mapcalc.
  68. @param exp expression
  69. @param quiet True to run quietly (<tt>--q</tt>)
  70. @param verbose True to run verbosely (<tt>--v</tt>)
  71. @param overwrite True to enable overwriting the output (<tt>--o</tt>)
  72. @param kwargs
  73. """
  74. t = string.Template(exp)
  75. e = t.substitute(**kwargs)
  76. if run_command('r.mapcalc', expression = e,
  77. quiet = quiet,
  78. verbose = verbose,
  79. overwrite = overwrite) != 0:
  80. fatal(_("An error occurred while running r.mapcalc"))
  81. def mapcalc_start(exp, quiet = False, verbose = False, overwrite = False, **kwargs):
  82. """!Interface to r.mapcalc, doesn't wait for it to finish, returns Popen object.
  83. \code
  84. >>> expr1 = '"%s" = "%s" * 10' % (output, input)
  85. >>> expr2 = '...' # etc.
  86. >>> # launch the jobs:
  87. >>> p1 = grass.mapcalc_start(expr1)
  88. >>> p2 = grass.mapcalc_start(expr2) # etc.
  89. ...
  90. >>> # wait for them to finish:
  91. >>> p1.wait()
  92. >>> p2.wait() # etc.
  93. \endcode
  94. @param exp expression
  95. @param quiet True to run quietly (<tt>--q</tt>)
  96. @param verbose True to run verbosely (<tt>--v</tt>)
  97. @param overwrite True to enable overwriting the output (<tt>--o</tt>)
  98. @param kwargs
  99. @return Popen object
  100. """
  101. t = string.Template(exp)
  102. e = t.substitute(**kwargs)
  103. return start_command('r.mapcalc', expression = e,
  104. quiet = quiet,
  105. verbose = verbose,
  106. overwrite = overwrite)
  107. # interface to r.what
  108. def raster_what(map, coord):
  109. """!TODO"""
  110. if type(map) in (types.StringType, types.UnicodeType):
  111. map_list = [map]
  112. else:
  113. map_list = map
  114. coord_list = list()
  115. if type(coord) is types.TupleType:
  116. coord_list.append('%f,%f' % (coord[0], coord[1]))
  117. else:
  118. for e, n in coord:
  119. coord_list.append('%f,%f' % (e, n))
  120. sep = '|'
  121. # separator '|' not included in command
  122. # because | is causing problems on Windows
  123. # change separator?
  124. cmdParams = dict(quiet = True,
  125. flags = 'rf',
  126. map = ','.join(map_list),
  127. coordinates = ','.join(coord_list),
  128. null = _("No data"))
  129. ret = read_command('r.what',
  130. **cmdParams)
  131. data = list()
  132. if not ret:
  133. return data
  134. labels = (_("value"), _("label"), _("color"))
  135. for item in ret.splitlines():
  136. line = item.split(sep)[3:]
  137. for i, map_name in enumerate(map_list):
  138. tmp_dict = {}
  139. tmp_dict[map_name] = {}
  140. for j in range(len(labels)):
  141. tmp_dict[map_name][labels[j]] = line[i*len(labels)+j]
  142. data.append(tmp_dict)
  143. return data