raster.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  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. def mapcalc_start(exp, quiet=False, verbose=False, overwrite=False,
  85. seed=None, env=None, **kwargs):
  86. """Interface to r.mapcalc, doesn't wait for it to finish, returns Popen object.
  87. >>> output = 'newele'
  88. >>> input = 'elevation'
  89. >>> expr1 = '"%s" = "%s" * 10' % (output, input)
  90. >>> expr2 = '...' # etc.
  91. >>> # launch the jobs:
  92. >>> p1 = mapcalc_start(expr1)
  93. >>> p2 = mapcalc_start(expr2)
  94. ...
  95. >>> # wait for them to finish:
  96. >>> p1.wait()
  97. 0
  98. >>> p2.wait()
  99. 1
  100. >>> run_command('g.remove', flags='f', type='raster', name=output)
  101. :param str exp: expression
  102. :param bool quiet: True to run quietly (<tt>--q</tt>)
  103. :param bool verbose: True to run verbosely (<tt>--v</tt>)
  104. :param bool overwrite: True to enable overwriting the output (<tt>--o</tt>)
  105. :param seed: an integer used to seed the random-number generator for the
  106. rand() function, or 'auto' to generate a random seed
  107. :param dict env: dictionary of environment variables for child process
  108. :param kwargs:
  109. :return: Popen object
  110. """
  111. if seed == 'auto':
  112. seed = hash((os.getpid(), time.time())) % (2**32)
  113. t = string.Template(exp)
  114. e = t.substitute(**kwargs)
  115. p = feed_command('r.mapcalc', file='-', env=env, seed=seed,
  116. quiet=quiet, verbose=verbose, overwrite=overwrite)
  117. p.stdin.write(e)
  118. p.stdin.close()
  119. return p
  120. def raster_what(map, coord, env=None, localized=False):
  121. """Interface to r.what
  122. >>> raster_what('elevation', [[640000, 228000]])
  123. [{'elevation': {'color': '255:214:000', 'label': '', 'value': '102.479'}}]
  124. :param str map: the map name
  125. :param list coord: a list of list containing all the point that you want
  126. query
  127. :param env:
  128. """
  129. if isinstance(map, (bytes, unicode)):
  130. map_list = [map]
  131. else:
  132. map_list = map
  133. coord_list = list()
  134. if isinstance(coord, tuple):
  135. coord_list.append('%f,%f' % (coord[0], coord[1]))
  136. else:
  137. for e, n in coord:
  138. coord_list.append('%f,%f' % (e, n))
  139. sep = '|'
  140. # separator '|' not included in command
  141. # because | is causing problems on Windows
  142. # change separator?
  143. ret = read_command('r.what',
  144. flags='rf',
  145. map=','.join(map_list),
  146. coordinates=','.join(coord_list),
  147. null=_("No data"),
  148. quiet=True,
  149. env=env)
  150. data = list()
  151. if not ret:
  152. return data
  153. if localized:
  154. labels = (_("value"), _("label"), _("color"))
  155. else:
  156. labels = ('value', 'label', 'color')
  157. for item in ret.splitlines():
  158. line = item.split(sep)[3:]
  159. for i, map_name in enumerate(map_list):
  160. tmp_dict = {}
  161. tmp_dict[map_name] = {}
  162. for j in range(len(labels)):
  163. tmp_dict[map_name][labels[j]] = line[i*len(labels)+j]
  164. data.append(tmp_dict)
  165. return data