raster.py 5.7 KB

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