raster.py 6.0 KB

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