raster.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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. import time
  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 <%(map)s>. "
  35. "Raster map <%(map)s> not found in current mapset." % { 'map' : map, 'map' : map}))
  36. return False
  37. # run "r.info -gre ..." and parse output
  38. def raster_info(map):
  39. """!Return information about a raster map (interface to
  40. `r.info'). Example:
  41. \code
  42. >>> grass.raster_info('elevation')
  43. {'north': 228500.0, 'timestamp': '"none"', 'min': 55.578792572021499,
  44. 'datatype': 'FCELL', 'max': 156.32986450195301, 'ewres': 10.0,
  45. 'vertical_datum': '', 'west': 630000.0, 'units': '',
  46. 'title': 'South-West Wake county: Elevation NED 10m (elev_ned10m)',
  47. 'east': 645000.0, 'nsres': 10.0, 'south': 215000.0}
  48. \endcode
  49. @param map map name
  50. @return parsed raster info
  51. """
  52. def float_or_null(s):
  53. if s == 'NULL':
  54. return None
  55. else:
  56. return float(s)
  57. s = read_command('r.info', flags = 'gre', map = map)
  58. kv = parse_key_val(s)
  59. for k in ['min', 'max']:
  60. kv[k] = float_or_null(kv[k])
  61. for k in ['north', 'south', 'east', 'west']:
  62. kv[k] = float(kv[k])
  63. for k in ['nsres', 'ewres']:
  64. kv[k] = float_or_dms(kv[k])
  65. return kv
  66. # interface to r.mapcalc
  67. def mapcalc(exp, quiet = False, verbose = False, overwrite = False, seed = None, **kwargs):
  68. """!Interface to r.mapcalc.
  69. @param exp expression
  70. @param quiet True to run quietly (<tt>--q</tt>)
  71. @param verbose True to run verbosely (<tt>--v</tt>)
  72. @param overwrite True to enable overwriting the output (<tt>--o</tt>)
  73. @param seed an integer used to seed the random-number generator for the rand() function,
  74. or 'auto' to generate a random seed
  75. @param kwargs
  76. """
  77. if seed == 'auto':
  78. seed = hash((os.getpid(), time.time())) % (2**32)
  79. t = string.Template(exp)
  80. e = t.substitute(**kwargs)
  81. if write_command('r.mapcalc', file = '-', stdin = e,
  82. seed = seed,
  83. quiet = quiet,
  84. verbose = verbose,
  85. overwrite = overwrite) != 0:
  86. fatal(_("An error occurred while running r.mapcalc"))
  87. def mapcalc_start(exp, quiet = False, verbose = False, overwrite = False, seed = None, **kwargs):
  88. """!Interface to r.mapcalc, doesn't wait for it to finish, returns Popen object.
  89. \code
  90. >>> expr1 = '"%s" = "%s" * 10' % (output, input)
  91. >>> expr2 = '...' # etc.
  92. >>> # launch the jobs:
  93. >>> p1 = grass.mapcalc_start(expr1)
  94. >>> p2 = grass.mapcalc_start(expr2) # etc.
  95. ...
  96. >>> # wait for them to finish:
  97. >>> p1.wait()
  98. >>> p2.wait() # etc.
  99. \endcode
  100. @param exp expression
  101. @param quiet True to run quietly (<tt>--q</tt>)
  102. @param verbose True to run verbosely (<tt>--v</tt>)
  103. @param overwrite True to enable overwriting the output (<tt>--o</tt>)
  104. @param seed an integer used to seed the random-number generator for the rand() function,
  105. or 'auto' to generate a random seed
  106. @param kwargs
  107. @return Popen object
  108. """
  109. if seed == 'auto':
  110. seed = hash((os.getpid(), time.time())) % (2**32)
  111. t = string.Template(exp)
  112. e = t.substitute(**kwargs)
  113. p = feed_command('r.mapcalc', file = '-',
  114. seed = seed,
  115. quiet = quiet,
  116. verbose = verbose,
  117. overwrite = overwrite)
  118. p.stdin.write(e)
  119. p.stdin.close()
  120. return p
  121. # interface to r.what
  122. def raster_what(map, coord):
  123. """!TODO"""
  124. if type(map) in (types.StringType, types.UnicodeType):
  125. map_list = [map]
  126. else:
  127. map_list = map
  128. coord_list = list()
  129. if type(coord) is types.TupleType:
  130. coord_list.append('%f,%f' % (coord[0], coord[1]))
  131. else:
  132. for e, n in coord:
  133. coord_list.append('%f,%f' % (e, n))
  134. sep = '|'
  135. # separator '|' not included in command
  136. # because | is causing problems on Windows
  137. # change separator?
  138. cmdParams = dict(quiet = True,
  139. flags = 'rf',
  140. map = ','.join(map_list),
  141. coordinates = ','.join(coord_list),
  142. null = _("No data"))
  143. ret = read_command('r.what',
  144. **cmdParams)
  145. data = list()
  146. if not ret:
  147. return data
  148. labels = (_("value"), _("label"), _("color"))
  149. for item in ret.splitlines():
  150. line = item.split(sep)[3:]
  151. for i, map_name in enumerate(map_list):
  152. tmp_dict = {}
  153. tmp_dict[map_name] = {}
  154. for j in range(len(labels)):
  155. tmp_dict[map_name][labels[j]] = line[i*len(labels)+j]
  156. data.append(tmp_dict)
  157. return data