raster.py 6.4 KB

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