raster.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. """
  2. Raster related functions to be used in Python scripts.
  3. Usage:
  4. ::
  5. from grass.script import raster as grass
  6. grass.raster_history(map)
  7. (C) 2008-2011 by the GRASS Development Team
  8. This program is free software under the GNU General Public
  9. License (>=v2). Read the file COPYING that comes with GRASS
  10. for details.
  11. .. sectionauthor:: Glynn Clements
  12. .. sectionauthor:: Martin Landa <landa.martin gmail.com>
  13. """
  14. import os
  15. import string
  16. import types
  17. import time
  18. from core import *
  19. from grass.exceptions import CalledModuleError
  20. from utils import float_or_dms, parse_key_val
  21. def raster_history(map):
  22. """Set the command history for a raster map to the command used to
  23. invoke the script (interface to `r.support`).
  24. :param str map: map name
  25. :return: True on success
  26. :return: False on failure
  27. """
  28. current_mapset = gisenv()['MAPSET']
  29. if find_file(name=map)['mapset'] == current_mapset:
  30. run_command('r.support', map=map, history=os.environ['CMDLINE'])
  31. return True
  32. warning(_("Unable to write history for <%(map)s>. "
  33. "Raster map <%(map)s> not found in current mapset." % { 'map': map, 'map': map}))
  34. return False
  35. def raster_info(map):
  36. """Return information about a raster map (interface to
  37. `r.info -gre`). Example:
  38. >>> raster_info('elevation') # doctest: +ELLIPSIS
  39. {'creator': '"helena"', 'cols': '1500' ... 'south': 215000.0}
  40. :param str map: map name
  41. :return: parsed raster info
  42. """
  43. def float_or_null(s):
  44. if s == 'NULL':
  45. return None
  46. else:
  47. return float(s)
  48. s = read_command('r.info', flags='gre', map=map)
  49. kv = parse_key_val(s)
  50. for k in ['min', 'max']:
  51. kv[k] = float_or_null(kv[k])
  52. for k in ['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. def mapcalc(exp, quiet=False, verbose=False, overwrite=False,
  58. seed=None, env=None, **kwargs):
  59. """Interface to r.mapcalc.
  60. :param str exp: expression
  61. :param bool quiet: True to run quietly (<tt>--q</tt>)
  62. :param bool verbose: True to run verbosely (<tt>--v</tt>)
  63. :param bool overwrite: True to enable overwriting the output (<tt>--o</tt>)
  64. :param seed: an integer used to seed the random-number generator for the
  65. rand() function, or 'auto' to generate a random seed
  66. :param dict env: dictionary of environment variables for child process
  67. :param kwargs:
  68. """
  69. if seed == 'auto':
  70. seed = hash((os.getpid(), time.time())) % (2**32)
  71. t = string.Template(exp)
  72. e = t.substitute(**kwargs)
  73. try:
  74. write_command('r.mapcalc', file='-', stdin=e, env=env, seed=seed,
  75. quiet=quiet, verbose=verbose, overwrite=overwrite)
  76. except CalledModuleError:
  77. fatal(_("An error occurred while running r.mapcalc"))
  78. def mapcalc_start(exp, quiet=False, verbose=False, overwrite=False,
  79. seed=None, env=None, **kwargs):
  80. """Interface to r.mapcalc, doesn't wait for it to finish, returns Popen object.
  81. >>> output = 'newele'
  82. >>> input = 'elevation'
  83. >>> expr1 = '"%s" = "%s" * 10' % (output, input)
  84. >>> expr2 = '...' # etc.
  85. >>> # launch the jobs:
  86. >>> p1 = mapcalc_start(expr1)
  87. >>> p2 = mapcalc_start(expr2)
  88. ...
  89. >>> # wait for them to finish:
  90. >>> p1.wait()
  91. 0
  92. >>> p2.wait()
  93. 1
  94. >>> run_command('g.remove', flags='f', type='rast', name=output)
  95. :param str exp: expression
  96. :param bool quiet: True to run quietly (<tt>--q</tt>)
  97. :param bool verbose: True to run verbosely (<tt>--v</tt>)
  98. :param bool overwrite: True to enable overwriting the output (<tt>--o</tt>)
  99. :param seed: an integer used to seed the random-number generator for the
  100. rand() function, or 'auto' to generate a random seed
  101. :param dict env: dictionary of environment variables for child process
  102. :param kwargs:
  103. :return: Popen object
  104. """
  105. if seed == 'auto':
  106. seed = hash((os.getpid(), time.time())) % (2**32)
  107. t = string.Template(exp)
  108. e = t.substitute(**kwargs)
  109. p = feed_command('r.mapcalc', file='-', env=env, seed=seed,
  110. quiet=quiet, verbose=verbose, overwrite=overwrite)
  111. p.stdin.write(e)
  112. p.stdin.close()
  113. return p
  114. def raster_what(map, coord, env=None):
  115. """Interface to r.what
  116. >>> raster_what('elevation', [[640000, 228000]])
  117. [{'elevation': {'color': '255:214:000', 'label': '', 'value': '102.479'}}]
  118. :param str map: the map name
  119. :param list coord: a list of list containing all the point that you want
  120. query
  121. :param env:
  122. """
  123. if type(map) in (types.StringType, types.UnicodeType):
  124. map_list = [map]
  125. else:
  126. map_list = map
  127. coord_list = list()
  128. if type(coord) is types.TupleType:
  129. coord_list.append('%f,%f' % (coord[0], coord[1]))
  130. else:
  131. for e, n in coord:
  132. coord_list.append('%f,%f' % (e, n))
  133. sep = '|'
  134. # separator '|' not included in command
  135. # because | is causing problems on Windows
  136. # change separator?
  137. ret = read_command('r.what',
  138. flags='rf',
  139. map=','.join(map_list),
  140. coordinates=','.join(coord_list),
  141. null=_("No data"),
  142. quiet=True,
  143. env=env)
  144. data = list()
  145. if not ret:
  146. return data
  147. labels = (_("value"), _("label"), _("color"))
  148. for item in ret.splitlines():
  149. line = item.split(sep)[3:]
  150. for i, map_name in enumerate(map_list):
  151. tmp_dict = {}
  152. tmp_dict[map_name] = {}
  153. for j in range(len(labels)):
  154. tmp_dict[map_name][labels[j]] = line[i*len(labels)+j]
  155. data.append(tmp_dict)
  156. return data