raster.py 6.0 KB

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