raster.py 5.8 KB

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