core.py 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342
  1. """!@package grass.script.core
  2. @brief GRASS Python scripting module (core functions)
  3. Core functions to be used in Python scripts.
  4. Usage:
  5. @code
  6. from grass.script import core as grass
  7. grass.parser()
  8. ...
  9. @endcode
  10. (C) 2008-2011 by the GRASS Development Team
  11. This program is free software under the GNU General Public
  12. License (>=v2). Read the file COPYING that comes with GRASS
  13. for details.
  14. @author Glynn Clements
  15. @author Martin Landa <landa.martin gmail.com>
  16. @author Michael Barton <michael.barton asu.edu>
  17. """
  18. import os
  19. import sys
  20. import types
  21. import re
  22. import atexit
  23. import subprocess
  24. import shutil
  25. import locale
  26. import codecs
  27. # i18N
  28. import gettext
  29. gettext.install('grasslibs', os.path.join(os.getenv("GISBASE"), 'locale'))
  30. # subprocess wrapper that uses shell on Windows
  31. class Popen(subprocess.Popen):
  32. def __init__(self, args, bufsize = 0, executable = None,
  33. stdin = None, stdout = None, stderr = None,
  34. preexec_fn = None, close_fds = False, shell = None,
  35. cwd = None, env = None, universal_newlines = False,
  36. startupinfo = None, creationflags = 0):
  37. if shell == None:
  38. shell = (sys.platform == "win32")
  39. subprocess.Popen.__init__(self, args, bufsize, executable,
  40. stdin, stdout, stderr,
  41. preexec_fn, close_fds, shell,
  42. cwd, env, universal_newlines,
  43. startupinfo, creationflags)
  44. PIPE = subprocess.PIPE
  45. STDOUT = subprocess.STDOUT
  46. class ScriptError(Exception):
  47. def __init__(self, msg):
  48. self.value = msg
  49. def __str__(self):
  50. return self.value
  51. raise_on_error = False # raise exception instead of calling fatal()
  52. debug_level = 0 # DEBUG level
  53. def call(*args, **kwargs):
  54. return Popen(*args, **kwargs).wait()
  55. # GRASS-oriented interface to subprocess module
  56. _popen_args = ["bufsize", "executable", "stdin", "stdout", "stderr",
  57. "preexec_fn", "close_fds", "cwd", "env",
  58. "universal_newlines", "startupinfo", "creationflags"]
  59. def decode(string):
  60. enc = locale.getdefaultlocale()[1]
  61. if enc:
  62. return string.decode(enc)
  63. return string
  64. def _make_val(val):
  65. if isinstance(val, types.StringType) or \
  66. isinstance(val, types.UnicodeType):
  67. return val
  68. if isinstance(val, types.ListType):
  69. return ",".join(map(_make_val, val))
  70. if isinstance(val, types.TupleType):
  71. return _make_val(list(val))
  72. return str(val)
  73. def make_command(prog, flags = "", overwrite = False, quiet = False, verbose = False, **options):
  74. """!Return a list of strings suitable for use as the args parameter to
  75. Popen() or call(). Example:
  76. @code
  77. >>> grass.make_command("g.message", flags = 'w', message = 'this is a warning')
  78. ['g.message', '-w', 'message=this is a warning']
  79. @endcode
  80. @param prog GRASS module
  81. @param flags flags to be used (given as a string)
  82. @param overwrite True to enable overwriting the output (<tt>--o</tt>)
  83. @param quiet True to run quietly (<tt>--q</tt>)
  84. @param verbose True to run verbosely (<tt>--v</tt>)
  85. @param options module's parameters
  86. @return list of arguments
  87. """
  88. args = [prog]
  89. if overwrite:
  90. args.append("--o")
  91. if quiet:
  92. args.append("--q")
  93. if verbose:
  94. args.append("--v")
  95. if flags:
  96. if '-' in flags:
  97. raise ScriptError("'-' is not a valid flag")
  98. args.append("-%s" % flags)
  99. for opt, val in options.iteritems():
  100. if val != None:
  101. if opt[0] == '_':
  102. opt = opt[1:]
  103. args.append("%s=%s" % (opt, _make_val(val)))
  104. return args
  105. def start_command(prog, flags = "", overwrite = False, quiet = False, verbose = False, **kwargs):
  106. """!Returns a Popen object with the command created by make_command.
  107. Accepts any of the arguments which Popen() accepts apart from "args"
  108. and "shell".
  109. \code
  110. >>> p = grass.start_command("g.gisenv", stdout = subprocess.PIPE)
  111. >>> print p
  112. <subprocess.Popen object at 0xb7c12f6c>
  113. >>> print p.communicate()[0]
  114. GISDBASE='/opt/grass-data';
  115. LOCATION_NAME='spearfish60';
  116. MAPSET='glynn';
  117. GRASS_DB_ENCODING='ascii';
  118. GUI='text';
  119. MONITOR='x0';
  120. \endcode
  121. @param prog GRASS module
  122. @param flags flags to be used (given as a string)
  123. @param overwrite True to enable overwriting the output (<tt>--o</tt>)
  124. @param quiet True to run quietly (<tt>--q</tt>)
  125. @param verbose True to run verbosely (<tt>--v</tt>)
  126. @param kwargs module's parameters
  127. @return Popen object
  128. """
  129. options = {}
  130. popts = {}
  131. for opt, val in kwargs.iteritems():
  132. if opt in _popen_args:
  133. popts[opt] = val
  134. else:
  135. options[opt] = val
  136. args = make_command(prog, flags, overwrite, quiet, verbose, **options)
  137. global debug_level
  138. if debug_level > 0:
  139. sys.stderr.write("D1/%d: %s.start_command(): %s\n" % (debug_level, __name__, ' '.join(args)))
  140. sys.stderr.flush()
  141. return Popen(args, **popts)
  142. def run_command(*args, **kwargs):
  143. """!Passes all arguments to start_command(), then waits for the process to
  144. complete, returning its exit code. Similar to subprocess.call(), but
  145. with the make_command() interface.
  146. @param args list of unnamed arguments (see start_command() for details)
  147. @param kwargs list of named arguments (see start_command() for details)
  148. @return exit code (0 for success)
  149. """
  150. ps = start_command(*args, **kwargs)
  151. return ps.wait()
  152. def pipe_command(*args, **kwargs):
  153. """!Passes all arguments to start_command(), but also adds
  154. "stdout = PIPE". Returns the Popen object.
  155. \code
  156. >>> p = grass.pipe_command("g.gisenv")
  157. >>> print p
  158. <subprocess.Popen object at 0xb7c12f6c>
  159. >>> print p.communicate()[0]
  160. GISDBASE='/opt/grass-data';
  161. LOCATION_NAME='spearfish60';
  162. MAPSET='glynn';
  163. GRASS_DB_ENCODING='ascii';
  164. GUI='text';
  165. MONITOR='x0';
  166. \endcode
  167. @param args list of unnamed arguments (see start_command() for details)
  168. @param kwargs list of named arguments (see start_command() for details)
  169. @return Popen object
  170. """
  171. kwargs['stdout'] = PIPE
  172. return start_command(*args, **kwargs)
  173. def feed_command(*args, **kwargs):
  174. """!Passes all arguments to start_command(), but also adds
  175. "stdin = PIPE". Returns the Popen object.
  176. @param args list of unnamed arguments (see start_command() for details)
  177. @param kwargs list of named arguments (see start_command() for details)
  178. @return Popen object
  179. """
  180. kwargs['stdin'] = PIPE
  181. return start_command(*args, **kwargs)
  182. def read_command(*args, **kwargs):
  183. """!Passes all arguments to pipe_command, then waits for the process to
  184. complete, returning its stdout (i.e. similar to shell `backticks`).
  185. @param args list of unnamed arguments (see start_command() for details)
  186. @param kwargs list of named arguments (see start_command() for details)
  187. @return stdout
  188. """
  189. ps = pipe_command(*args, **kwargs)
  190. return ps.communicate()[0]
  191. def parse_command(*args, **kwargs):
  192. """!Passes all arguments to read_command, then parses the output
  193. by parse_key_val().
  194. Parsing function can be optionally given by <em>parse</em> parameter
  195. including its arguments, e.g.
  196. @code
  197. parse_command(..., parse = (grass.parse_key_val, { 'sep' : ':' }))
  198. @endcode
  199. or you can simply define <em>delimiter</em>
  200. @code
  201. parse_command(..., delimiter = ':')
  202. @endcode
  203. @param args list of unnamed arguments (see start_command() for details)
  204. @param kwargs list of named arguments (see start_command() for details)
  205. @return parsed module output
  206. """
  207. parse = None
  208. parse_args = {}
  209. if 'parse' in kwargs:
  210. if type(kwargs['parse']) is types.TupleType:
  211. parse = kwargs['parse'][0]
  212. parse_args = kwargs['parse'][1]
  213. del kwargs['parse']
  214. if 'delimiter' in kwargs:
  215. parse_args = { 'sep' : kwargs['delimiter'] }
  216. del kwargs['delimiter']
  217. if not parse:
  218. parse = parse_key_val # use default fn
  219. res = read_command(*args, **kwargs)
  220. return parse(res, **parse_args)
  221. def write_command(*args, **kwargs):
  222. """!Passes all arguments to feed_command, with the string specified
  223. by the 'stdin' argument fed to the process' stdin.
  224. @param args list of unnamed arguments (see start_command() for details)
  225. @param kwargs list of named arguments (see start_command() for details)
  226. @return return code
  227. """
  228. stdin = kwargs['stdin']
  229. p = feed_command(*args, **kwargs)
  230. p.stdin.write(stdin)
  231. p.stdin.close()
  232. return p.wait()
  233. def exec_command(prog, flags = "", overwrite = False, quiet = False, verbose = False, env = None, **kwargs):
  234. """!Interface to os.execvpe(), but with the make_command() interface.
  235. @param prog GRASS module
  236. @param flags flags to be used (given as a string)
  237. @param overwrite True to enable overwriting the output (<tt>--o</tt>)
  238. @param quiet True to run quietly (<tt>--q</tt>)
  239. @param verbose True to run verbosely (<tt>--v</tt>)
  240. @param env directory with environmental variables
  241. @param kwargs module's parameters
  242. """
  243. args = make_command(prog, flags, overwrite, quiet, verbose, **kwargs)
  244. if env == None:
  245. env = os.environ
  246. os.execvpe(prog, args, env)
  247. # interface to g.message
  248. def message(msg, flag = None):
  249. """!Display a message using `g.message`
  250. @param msg message to be displayed
  251. @param flag flags (given as string)
  252. """
  253. run_command("g.message", flags = flag, message = msg)
  254. def debug(msg, debug = 1):
  255. """!Display a debugging message using `g.message -d`
  256. @param msg debugging message to be displayed
  257. @param debug debug level (0-5)
  258. """
  259. run_command("g.message", flags = 'd', message = msg, debug = debug)
  260. def verbose(msg):
  261. """!Display a verbose message using `g.message -v`
  262. @param msg verbose message to be displayed
  263. """
  264. message(msg, flag = 'v')
  265. def info(msg):
  266. """!Display an informational message using `g.message -i`
  267. @param msg informational message to be displayed
  268. """
  269. message(msg, flag = 'i')
  270. def percent(i, n, s):
  271. """!Display a progress info message using `g.message -p`
  272. @code
  273. message(_("Percent complete..."))
  274. n = 100
  275. for i in range(n):
  276. percent(i, n, 1)
  277. percent(1, 1, 1)
  278. @endcode
  279. @param i current item
  280. @param n total number of items
  281. @param s increment size
  282. """
  283. message("%d %d %d" % (i, n, s), flag = 'p')
  284. def warning(msg):
  285. """!Display a warning message using `g.message -w`
  286. @param msg warning message to be displayed
  287. """
  288. message(msg, flag = 'w')
  289. def error(msg):
  290. """!Display an error message using `g.message -e`
  291. @param msg error message to be displayed
  292. """
  293. message(msg, flag = 'e')
  294. def fatal(msg):
  295. """!Display an error message using `g.message -e`, then abort
  296. Raise exception when raise_on_error is 'True'.
  297. @param msg error message to be displayed
  298. """
  299. global raise_on_error
  300. if raise_on_error:
  301. raise ScriptError(msg)
  302. error(msg)
  303. sys.exit(1)
  304. def set_raise_on_error(raise_exp = True):
  305. """!Define behaviour on fatal error (fatal() called)
  306. @param raise_exp True to raise ScriptError instead of calling
  307. sys.exit(1) in fatal()
  308. @return current status
  309. """
  310. global raise_on_error
  311. tmp_raise = raise_on_error
  312. raise_on_error = raise_exp
  313. return tmp_raise
  314. # interface to g.parser
  315. def _parse_opts(lines):
  316. options = {}
  317. flags = {}
  318. for line in lines:
  319. line = line.rstrip('\r\n')
  320. if not line:
  321. break
  322. try:
  323. [var, val] = line.split('=', 1)
  324. except:
  325. raise SyntaxError("invalid output from g.parser: %s" % line)
  326. if var.startswith('flag_'):
  327. flags[var[5:]] = bool(int(val))
  328. elif var.startswith('opt_'):
  329. options[var[4:]] = val
  330. elif var in ['GRASS_OVERWRITE', 'GRASS_VERBOSE']:
  331. os.environ[var] = val
  332. else:
  333. raise SyntaxError("invalid output from g.parser: %s" % line)
  334. return (options, flags)
  335. def parser():
  336. """!Interface to g.parser, intended to be run from the top-level, e.g.:
  337. @code
  338. if __name__ == "__main__":
  339. options, flags = grass.parser()
  340. main()
  341. @endcode
  342. Thereafter, the global variables "options" and "flags" will be
  343. dictionaries containing option/flag values, keyed by lower-case
  344. option/flag names. The values in "options" are strings, those in
  345. "flags" are Python booleans.
  346. """
  347. if not os.getenv("GISBASE"):
  348. print >> sys.stderr, "You must be in GRASS GIS to run this program."
  349. sys.exit(1)
  350. cmdline = [basename(sys.argv[0])]
  351. cmdline += ['"' + arg + '"' for arg in sys.argv[1:]]
  352. os.environ['CMDLINE'] = ' '.join(cmdline)
  353. argv = sys.argv[:]
  354. name = argv[0]
  355. if not os.path.isabs(name):
  356. if os.sep in name or (os.altsep and os.altsep in name):
  357. argv[0] = os.path.abspath(name)
  358. else:
  359. argv[0] = os.path.join(sys.path[0], name)
  360. p = Popen(['g.parser', '-s'] + argv, stdout = PIPE)
  361. s = p.communicate()[0]
  362. lines = s.splitlines()
  363. if not lines or lines[0].rstrip('\r\n') != "@ARGS_PARSED@":
  364. sys.stdout.write(s)
  365. sys.exit(p.returncode)
  366. return _parse_opts(lines[1:])
  367. # interface to g.tempfile
  368. def tempfile(create = True):
  369. """!Returns the name of a temporary file, created with
  370. g.tempfile.
  371. @param create True to create a file
  372. @return path to a tmp file
  373. """
  374. flags = ''
  375. if not create:
  376. flags += 'd'
  377. return read_command("g.tempfile", flags = flags, pid = os.getpid()).strip()
  378. def tempdir():
  379. """!Returns the name of a temporary dir, created with g.tempfile."""
  380. tmp = tempfile(create = False)
  381. os.mkdir(tmp)
  382. return tmp
  383. class KeyValue(dict):
  384. """A general-purpose key-value store.
  385. KeyValue is a subclass of dict, but also allows entries to be read and
  386. written using attribute syntax. Example:
  387. \code
  388. >>> region = grass.region()
  389. >>> region['rows']
  390. 477
  391. >>> region.rows
  392. 477
  393. \endcode
  394. """
  395. def __getattr__(self, key):
  396. return self[key]
  397. def __setattr__(self, key, value):
  398. self[key] = value
  399. # key-value parsers
  400. def parse_key_val(s, sep = '=', dflt = None, val_type = None, vsep = None):
  401. """!Parse a string into a dictionary, where entries are separated
  402. by newlines and the key and value are separated by `sep' (default: `=')
  403. @param s string to be parsed
  404. @param sep key/value separator
  405. @param dflt default value to be used
  406. @param val_type value type (None for no cast)
  407. @param vsep vertical separator (default os.linesep)
  408. @return parsed input (dictionary of keys/values)
  409. """
  410. result = KeyValue()
  411. if not s:
  412. return result
  413. if vsep:
  414. lines = s.split(vsep)
  415. try:
  416. lines.remove('\n')
  417. except ValueError:
  418. pass
  419. else:
  420. lines = s.splitlines()
  421. for line in lines:
  422. kv = line.split(sep, 1)
  423. k = kv[0].strip()
  424. if len(kv) > 1:
  425. v = kv[1].strip()
  426. else:
  427. v = dflt
  428. if val_type:
  429. result[k] = val_type(v)
  430. else:
  431. result[k] = v
  432. return result
  433. def _text_to_key_value_dict(filename, sep=":", val_sep=","):
  434. """
  435. !Convert a key-value text file, where entries are separated
  436. by newlines and the key and value are separated by `sep',
  437. into a key-value dictionary and discover/use the correct
  438. data types (float, int or string) for values.
  439. @param filename The name or name and path of the text file to convert
  440. @param sep The character that separates the keys and values, default is ":"
  441. @param val_sep The character that separates the values of a single key, default is ","
  442. @return The dictionary
  443. A text file with this content:
  444. \code
  445. a: Hello
  446. b: 1.0
  447. c: 1,2,3,4,5
  448. d : hello,8,0.1
  449. \endcode
  450. Will be represented as this dictionary:
  451. \code
  452. {'a': ['Hello'], 'c': [1, 2, 3, 4, 5], 'b': [1.0], 'd': ['hello', 8, 0.1]}
  453. \endcode
  454. """
  455. text = open(filename, "r").readlines()
  456. kvdict = KeyValue()
  457. for line in text:
  458. if line.find(sep) >= 0:
  459. key, value = line.split(sep)
  460. key = key.strip()
  461. value = value.strip()
  462. else:
  463. # Jump over empty values
  464. continue
  465. values = value.split(val_sep)
  466. value_list = []
  467. for value in values:
  468. not_float = False
  469. not_int = False
  470. # Convert values into correct types
  471. # We first try integer then float
  472. try:
  473. value_converted = int(value)
  474. except:
  475. not_int = True
  476. if not_int:
  477. try:
  478. value_converted = float(value)
  479. except:
  480. not_float = True
  481. if not_int and not_float:
  482. value_converted = value.strip()
  483. value_list.append(value_converted)
  484. kvdict[key] = value_list
  485. return kvdict
  486. def compare_key_value_text_files(filename_a, filename_b, sep=":",
  487. val_sep=",", precision=0.000001):
  488. """
  489. !Compare two key-value text files that may contain projection parameter
  490. @param filename_a The name of the first key-value text file
  491. @param filenmae_b The name of the second key-value text file
  492. @param sep The character that separates the keys and values, default is ":"
  493. @param val_sep The character that separates the values of a single key, default is ","
  494. @param precision The precision with which the floating point values are compares
  495. if abs(a - b) > precision : return False
  496. @return True if full or almost identical, False if different
  497. This method will print a warning in case keys that are present in the first file
  498. are not present in the second one.
  499. The comparison method tries to convert the values into there native format (float, int or string)
  500. to allow correct comparison.
  501. An example key-value text file may have this content:
  502. \code
  503. a: Hello
  504. b: 1.0
  505. c: 1,2,3,4,5
  506. d : hello,8,0.1
  507. \endcode
  508. """
  509. dict_a = _text_to_key_value_dict(filename_a, sep)
  510. dict_b = _text_to_key_value_dict(filename_b, sep)
  511. missing_keys = 0
  512. # We compare matching keys
  513. for key in dict_a.keys():
  514. if dict_b.has_key(key):
  515. # Floating point values must be handled separately
  516. if isinstance(dict_a[key], float) and isinstance(dict_b[key], float):
  517. if abs(dict_a[key] - dict_b[key]) > precision:
  518. return False
  519. elif isinstance(dict_a[key], float) or isinstance(dict_b[key], float):
  520. return False
  521. else:
  522. if dict_a[key] != dict_b[key]:
  523. return False
  524. else:
  525. missing_keys += 1
  526. if missing_keys == len(dict_a):
  527. return False
  528. if missing_keys > 0:
  529. warning(_("Several keys (%i out of %i) are missing "
  530. "in the target file")%(missing_keys, len(dict_a)))
  531. return True
  532. # interface to g.gisenv
  533. def gisenv():
  534. """!Returns the output from running g.gisenv (with no arguments), as a
  535. dictionary. Example:
  536. \code
  537. >>> env = grass.gisenv()
  538. >>> print env['GISDBASE']
  539. /opt/grass-data
  540. \endcode
  541. @return list of GRASS variables
  542. """
  543. s = read_command("g.gisenv", flags='n')
  544. return parse_key_val(s)
  545. # interface to g.region
  546. def locn_is_latlong():
  547. """!Tests if location is lat/long. Value is obtained
  548. by checking the "g.region -p" projection code.
  549. @return True for a lat/long region, False otherwise
  550. """
  551. s = read_command("g.region", flags='p')
  552. kv = parse_key_val(s, ':')
  553. if kv['projection'].split(' ')[1] == '3':
  554. return True
  555. else:
  556. return False
  557. def region(region3d = False, complete = False):
  558. """!Returns the output from running "g.region -g", as a
  559. dictionary. Example:
  560. \param region3d True to get 3D region
  561. \code
  562. >>> region = grass.region()
  563. >>> [region[key] for key in "nsew"]
  564. [228500.0, 215000.0, 645000.0, 630000.0]
  565. >>> (region['nsres'], region['ewres'])
  566. (10.0, 10.0)
  567. \endcode
  568. @return dictionary of region values
  569. """
  570. flgs = 'g'
  571. if region3d:
  572. flgs += '3'
  573. if complete:
  574. flgs += 'cep'
  575. s = read_command("g.region", flags = flgs)
  576. reg = parse_key_val(s, val_type = float)
  577. for k in ['rows', 'cols', 'cells',
  578. 'rows3', 'cols3', 'cells3', 'depths']:
  579. if k not in reg:
  580. continue
  581. reg[k] = int(reg[k])
  582. return reg
  583. def region_env(region3d = False,
  584. **kwargs):
  585. """!Returns region settings as a string which can used as
  586. GRASS_REGION environmental variable.
  587. If no 'kwargs' are given then the current region is used. Note
  588. that this function doesn't modify the current region!
  589. See also use_temp_region() for alternative method how to define
  590. temporary region used for raster-based computation.
  591. \param region3d True to get 3D region
  592. \param kwargs g.region's parameters like 'rast', 'vect' or 'region'
  593. \code
  594. os.environ['GRASS_REGION'] = grass.region_env(region = 'detail')
  595. grass.mapcalc('map = 1', overwrite = True)
  596. os.environ.pop('GRASS_REGION')
  597. \endcode
  598. @return string with region values
  599. @return empty string on error
  600. """
  601. # read proj/zone from WIND file
  602. env = gisenv()
  603. windfile = os.path.join (env['GISDBASE'], env['LOCATION_NAME'],
  604. env['MAPSET'], "WIND")
  605. fd = open(windfile, "r")
  606. grass_region = ''
  607. for line in fd.readlines():
  608. key, value = map(lambda x: x.strip(), line.split(":", 1))
  609. if kwargs and key not in ('proj', 'zone'):
  610. continue
  611. if not kwargs and not region3d and \
  612. key in ('top', 'bottom', 'cols3', 'rows3',
  613. 'depths', 'e-w resol3', 'n-s resol3', 't-b resol'):
  614. continue
  615. grass_region += '%s: %s;' % (key, value)
  616. if not kwargs: # return current region
  617. return grass_region
  618. # read other values from `g.region -g`
  619. flgs = 'ug'
  620. if region3d:
  621. flgs += '3'
  622. s = read_command('g.region', flags = flgs, **kwargs)
  623. if not s:
  624. return ''
  625. reg = parse_key_val(s)
  626. kwdata = [('north', 'n'),
  627. ('south', 's'),
  628. ('east', 'e'),
  629. ('west', 'w'),
  630. ('cols', 'cols'),
  631. ('rows', 'rows'),
  632. ('e-w resol', 'ewres'),
  633. ('n-s resol', 'nsres')]
  634. if region3d:
  635. kwdata += [('top', 't'),
  636. ('bottom', 'b'),
  637. ('cols3', 'cols3'),
  638. ('rows3', 'rows3'),
  639. ('depths', 'depths'),
  640. ('e-w resol3', 'ewres3'),
  641. ('n-s resol3', 'nsres3'),
  642. ('t-b resol', 'tbres')]
  643. for wkey, rkey in kwdata:
  644. grass_region += '%s: %s;' % (wkey, reg[rkey])
  645. return grass_region
  646. def use_temp_region():
  647. """!Copies the current region to a temporary region with "g.region save=",
  648. then sets WIND_OVERRIDE to refer to that region. Installs an atexit
  649. handler to delete the temporary region upon termination.
  650. """
  651. name = "tmp.%s.%d" % (os.path.basename(sys.argv[0]), os.getpid())
  652. run_command("g.region", save = name, overwrite = True)
  653. os.environ['WIND_OVERRIDE'] = name
  654. atexit.register(del_temp_region)
  655. def del_temp_region():
  656. """!Unsets WIND_OVERRIDE and removes any region named by it."""
  657. try:
  658. name = os.environ.pop('WIND_OVERRIDE')
  659. run_command("g.remove", quiet = True, region = name)
  660. except:
  661. pass
  662. # interface to g.findfile
  663. def find_file(name, element = 'cell', mapset = None):
  664. """!Returns the output from running g.findfile as a
  665. dictionary. Example:
  666. \code
  667. >>> result = grass.find_file('fields', element = 'vector')
  668. >>> print result['fullname']
  669. fields@PERMANENT
  670. >>> print result['file']
  671. /opt/grass-data/spearfish60/PERMANENT/vector/fields
  672. \endcode
  673. @param name file name
  674. @param element element type (default 'cell')
  675. @param mapset mapset name (default all mapsets in search path)
  676. @return parsed output of g.findfile
  677. """
  678. if element == 'raster' or element == 'rast':
  679. verbose(_('Element type should be "cell" and not "%s"') % element)
  680. element = 'cell'
  681. s = read_command("g.findfile", flags='n', element = element, file = name, mapset = mapset)
  682. return parse_key_val(s)
  683. # interface to g.list
  684. def list_grouped(type, check_search_path = True):
  685. """!List elements grouped by mapsets.
  686. Returns the output from running g.list, as a dictionary where the
  687. keys are mapset names and the values are lists of maps in that
  688. mapset. Example:
  689. @code
  690. >>> grass.list_grouped('rast')['PERMANENT']
  691. ['aspect', 'erosion1', 'quads', 'soils', 'strm.dist', ...
  692. @endcode
  693. @param type element type (rast, vect, rast3d, region, ...)
  694. @param check_search_path True to add mapsets for the search path with no found elements
  695. @return directory of mapsets/elements
  696. """
  697. if type == 'raster' or type == 'cell':
  698. verbose(_('Element type should be "rast" and not "%s"') % element)
  699. type = 'rast'
  700. dashes_re = re.compile("^----+$")
  701. mapset_re = re.compile("<(.*)>")
  702. result = {}
  703. if check_search_path:
  704. for mapset in mapsets(search_path = True):
  705. result[mapset] = []
  706. mapset = None
  707. for line in read_command("g.list", type = type).splitlines():
  708. if line == "":
  709. continue
  710. if dashes_re.match(line):
  711. continue
  712. m = mapset_re.search(line)
  713. if m:
  714. mapset = m.group(1)
  715. if mapset not in result.keys():
  716. result[mapset] = []
  717. continue
  718. if mapset:
  719. result[mapset].extend(line.split())
  720. return result
  721. def _concat(xs):
  722. result = []
  723. for x in xs:
  724. result.extend(x)
  725. return result
  726. def list_pairs(type):
  727. """!List of elements as tuples.
  728. Returns the output from running g.list, as a list of (map, mapset)
  729. pairs. Example:
  730. @code
  731. >>> grass.list_pairs('rast')
  732. [('aspect', 'PERMANENT'), ('erosion1', 'PERMANENT'), ('quads', 'PERMANENT'), ...
  733. @endcode
  734. @param type element type (rast, vect, rast3d, region, ...)
  735. @return list of tuples (map, mapset)
  736. """
  737. return _concat([[(map, mapset) for map in maps]
  738. for mapset, maps in list_grouped(type).iteritems()])
  739. def list_strings(type):
  740. """!List of elements as strings.
  741. Returns the output from running g.list, as a list of qualified
  742. names. Example:
  743. @code
  744. >>> grass.list_strings('rast')
  745. ['aspect@PERMANENT', 'erosion1@PERMANENT', 'quads@PERMANENT', 'soils@PERMANENT', ...
  746. @endcode
  747. @param type element type
  748. @return list of strings ('map@@mapset')
  749. """
  750. return ["%s@%s" % pair for pair in list_pairs(type)]
  751. # interface to g.mlist
  752. def mlist_strings(type, pattern = None, mapset = None, flag = ''):
  753. """!List of elements as strings.
  754. Returns the output from running g.mlist, as a list of qualified
  755. names.
  756. @param type element type (rast, vect, rast3d, region, ...)
  757. @param pattern pattern string
  758. @param mapset mapset name (if not given use search path)
  759. @param flag pattern type: 'r' (basic regexp), 'e' (extended regexp), or '' (glob pattern)
  760. @return list of elements
  761. """
  762. if type == 'raster' or type == 'cell':
  763. verbose(_('Element type should be "rast" and not "%s"') % element)
  764. type = 'rast'
  765. result = list()
  766. for line in read_command("g.mlist",
  767. quiet = True,
  768. flags = 'm' + flag,
  769. type = type,
  770. pattern = pattern,
  771. mapset = mapset).splitlines():
  772. result.append(line.strip())
  773. return result
  774. def mlist_pairs(type, pattern = None, mapset = None, flag = ''):
  775. """!List of elements as pairs
  776. Returns the output from running g.mlist, as a list of
  777. (name, mapset) pairs
  778. @param type element type (rast, vect, rast3d, region, ...)
  779. @param pattern pattern string
  780. @param mapset mapset name (if not given use search path)
  781. @param flag pattern type: 'r' (basic regexp), 'e' (extended regexp), or '' (glob pattern)
  782. @return list of elements
  783. """
  784. return [tuple(map.split('@', 1)) for map in mlist_strings(type, pattern, mapset, flag)]
  785. def mlist_grouped(type, pattern = None, check_search_path = True, flag = ''):
  786. """!List of elements grouped by mapsets.
  787. Returns the output from running g.mlist, as a dictionary where the
  788. keys are mapset names and the values are lists of maps in that
  789. mapset. Example:
  790. @code
  791. >>> grass.mlist_grouped('rast', pattern='r*')['PERMANENT']
  792. ['railroads', 'roads', 'rstrct.areas', 'rushmore']
  793. @endcode
  794. @param type element type (rast, vect, rast3d, region, ...)
  795. @param pattern pattern string
  796. @param check_search_path True to add mapsets for the search path with no found elements
  797. @param flag pattern type: 'r' (basic regexp), 'e' (extended regexp), or '' (glob pattern)
  798. @return directory of mapsets/elements
  799. """
  800. if type == 'raster' or type == 'cell':
  801. verbose(_('Element type should be "rast" and not "%s"') % element)
  802. type = 'rast'
  803. result = {}
  804. if check_search_path:
  805. for mapset in mapsets(search_path = True):
  806. result[mapset] = []
  807. mapset = None
  808. for line in read_command("g.mlist", quiet = True, flags = "m" + flag,
  809. type = type, pattern = pattern).splitlines():
  810. try:
  811. name, mapset = line.split('@')
  812. except ValueError:
  813. warning(_("Invalid element '%s'") % line)
  814. continue
  815. if mapset in result:
  816. result[mapset].append(name)
  817. else:
  818. result[mapset] = [name, ]
  819. return result
  820. # color parsing
  821. named_colors = {
  822. "white": (1.00, 1.00, 1.00),
  823. "black": (0.00, 0.00, 0.00),
  824. "red": (1.00, 0.00, 0.00),
  825. "green": (0.00, 1.00, 0.00),
  826. "blue": (0.00, 0.00, 1.00),
  827. "yellow": (1.00, 1.00, 0.00),
  828. "magenta": (1.00, 0.00, 1.00),
  829. "cyan": (0.00, 1.00, 1.00),
  830. "aqua": (0.00, 0.75, 0.75),
  831. "grey": (0.75, 0.75, 0.75),
  832. "gray": (0.75, 0.75, 0.75),
  833. "orange": (1.00, 0.50, 0.00),
  834. "brown": (0.75, 0.50, 0.25),
  835. "purple": (0.50, 0.00, 1.00),
  836. "violet": (0.50, 0.00, 1.00),
  837. "indigo": (0.00, 0.50, 1.00)}
  838. def parse_color(val, dflt = None):
  839. """!Parses the string "val" as a GRASS colour, which can be either one of
  840. the named colours or an R:G:B tuple e.g. 255:255:255. Returns an
  841. (r,g,b) triple whose components are floating point values between 0
  842. and 1. Example:
  843. \code
  844. >>> grass.parse_color("red")
  845. (1.0, 0.0, 0.0)
  846. >>> grass.parse_color("255:0:0")
  847. (1.0, 0.0, 0.0)
  848. \endcode
  849. @param val color value
  850. @param dflt default color value
  851. @return tuple RGB
  852. """
  853. if val in named_colors:
  854. return named_colors[val]
  855. vals = val.split(':')
  856. if len(vals) == 3:
  857. return tuple(float(v) / 255 for v in vals)
  858. return dflt
  859. # check GRASS_OVERWRITE
  860. def overwrite():
  861. """!Return True if existing files may be overwritten"""
  862. owstr = 'GRASS_OVERWRITE'
  863. return owstr in os.environ and os.environ[owstr] != '0'
  864. # check GRASS_VERBOSE
  865. def verbosity():
  866. """!Return the verbosity level selected by GRASS_VERBOSE"""
  867. vbstr = os.getenv('GRASS_VERBOSE')
  868. if vbstr:
  869. return int(vbstr)
  870. else:
  871. return 2
  872. ## various utilities, not specific to GRASS
  873. # basename inc. extension stripping
  874. def basename(path, ext = None):
  875. """!Remove leading directory components and an optional extension
  876. from the specified path
  877. @param path path
  878. @param ext extension
  879. """
  880. name = os.path.basename(path)
  881. if not ext:
  882. return name
  883. fs = name.rsplit('.', 1)
  884. if len(fs) > 1 and fs[1].lower() == ext:
  885. name = fs[0]
  886. return name
  887. # find a program (replacement for "which")
  888. def find_program(pgm, args = []):
  889. """!Attempt to run a program, with optional arguments.
  890. @param pgm program name
  891. @param args list of arguments
  892. @return False if the attempt failed due to a missing executable
  893. @return True otherwise
  894. """
  895. nuldev = file(os.devnull, 'w+')
  896. try:
  897. ret = call([pgm] + args, stdin = nuldev, stdout = nuldev, stderr = nuldev)
  898. if ret == 0:
  899. found = True
  900. else:
  901. found = False
  902. except:
  903. found = False
  904. nuldev.close()
  905. return found
  906. # try to remove a file, without complaints
  907. def try_remove(path):
  908. """!Attempt to remove a file; no exception is generated if the
  909. attempt fails.
  910. @param path path to file to remove
  911. """
  912. try:
  913. os.remove(path)
  914. except:
  915. pass
  916. # try to remove a directory, without complaints
  917. def try_rmdir(path):
  918. """!Attempt to remove a directory; no exception is generated if the
  919. attempt fails.
  920. @param path path to directory to remove
  921. """
  922. try:
  923. os.rmdir(path)
  924. except:
  925. shutil.rmtree(path, ignore_errors = True)
  926. def float_or_dms(s):
  927. """!Convert DMS to float.
  928. @param s DMS value
  929. @return float value
  930. """
  931. return sum(float(x) / 60 ** n for (n, x) in enumerate(s.split(':')))
  932. # interface to g.mapsets
  933. def mapsets(search_path = False):
  934. """!List available mapsets
  935. @param search_path True to list mapsets only in search path
  936. @return list of mapsets
  937. """
  938. if search_path:
  939. flags = 'p'
  940. else:
  941. flags = 'l'
  942. mapsets = read_command('g.mapsets',
  943. flags = flags,
  944. sep = 'newline',
  945. quiet = True)
  946. if not mapsets:
  947. fatal(_("Unable to list mapsets"))
  948. return mapsets.splitlines()
  949. # interface to `g.proj -c`
  950. def create_location(dbase, location,
  951. epsg = None, proj4 = None, filename = None, wkt = None,
  952. datum = None, datum_trans = None, desc = None):
  953. """!Create new location
  954. Raise ScriptError on error.
  955. @param dbase path to GRASS database
  956. @param location location name to create
  957. @param epsg if given create new location based on EPSG code
  958. @param proj4 if given create new location based on Proj4 definition
  959. @param filename if given create new location based on georeferenced file
  960. @param wkt if given create new location based on WKT definition (path to PRJ file)
  961. @param datum GRASS format datum code
  962. @param datum_trans datum transformation parameters (used for epsg and proj4)
  963. @param desc description of the location (creates MYNAME file)
  964. """
  965. gisdbase = None
  966. if epsg or proj4 or filename or wkt:
  967. gisdbase = gisenv()['GISDBASE']
  968. run_command('g.gisenv',
  969. set = 'GISDBASE=%s' % dbase)
  970. if not os.path.exists(dbase):
  971. os.mkdir(dbase)
  972. kwargs = dict()
  973. if datum:
  974. kwargs['datum'] = datum
  975. if datum_trans:
  976. kwargs['datum_trans'] = datum_trans
  977. if epsg:
  978. ps = pipe_command('g.proj',
  979. quiet = True,
  980. epsg = epsg,
  981. location = location,
  982. stderr = PIPE,
  983. **kwargs)
  984. elif proj4:
  985. ps = pipe_command('g.proj',
  986. quiet = True,
  987. proj4 = proj4,
  988. location = location,
  989. stderr = PIPE,
  990. **kwargs)
  991. elif filename:
  992. ps = pipe_command('g.proj',
  993. quiet = True,
  994. georef = filename,
  995. location = location,
  996. stderr = PIPE)
  997. elif wkt:
  998. ps = pipe_command('g.proj',
  999. quiet = True,
  1000. wkt = wkt,
  1001. location = location,
  1002. stderr = PIPE)
  1003. else:
  1004. _create_location_xy(dbase, location)
  1005. if epsg or proj4 or filename or wkt:
  1006. error = ps.communicate()[1]
  1007. run_command('g.gisenv',
  1008. set = 'GISDBASE=%s' % gisdbase)
  1009. if ps.returncode != 0 and error:
  1010. raise ScriptError(repr(error))
  1011. try:
  1012. fd = codecs.open(os.path.join(dbase, location,
  1013. 'PERMANENT', 'MYNAME'),
  1014. encoding = 'utf-8', mode = 'w')
  1015. if desc:
  1016. fd.write(desc + os.linesep)
  1017. else:
  1018. fd.write(os.linesep)
  1019. fd.close()
  1020. except OSError, e:
  1021. raise ScriptError(repr(e))
  1022. def _create_location_xy(database, location):
  1023. """!Create unprojected location
  1024. Raise ScriptError on error.
  1025. @param database GRASS database where to create new location
  1026. @param location location name
  1027. """
  1028. cur_dir = os.getcwd()
  1029. try:
  1030. os.chdir(database)
  1031. os.mkdir(location)
  1032. os.mkdir(os.path.join(location, 'PERMANENT'))
  1033. # create DEFAULT_WIND and WIND files
  1034. regioninfo = ['proj: 0',
  1035. 'zone: 0',
  1036. 'north: 1',
  1037. 'south: 0',
  1038. 'east: 1',
  1039. 'west: 0',
  1040. 'cols: 1',
  1041. 'rows: 1',
  1042. 'e-w resol: 1',
  1043. 'n-s resol: 1',
  1044. 'top: 1',
  1045. 'bottom: 0',
  1046. 'cols3: 1',
  1047. 'rows3: 1',
  1048. 'depths: 1',
  1049. 'e-w resol3: 1',
  1050. 'n-s resol3: 1',
  1051. 't-b resol: 1']
  1052. defwind = open(os.path.join(location,
  1053. "PERMANENT", "DEFAULT_WIND"), 'w')
  1054. for param in regioninfo:
  1055. defwind.write(param + '%s' % os.linesep)
  1056. defwind.close()
  1057. shutil.copy(os.path.join(location, "PERMANENT", "DEFAULT_WIND"),
  1058. os.path.join(location, "PERMANENT", "WIND"))
  1059. os.chdir(cur_dir)
  1060. except OSError, e:
  1061. raise ScriptError(repr(e))
  1062. # interface to g.version
  1063. def version():
  1064. """!Get GRASS version as dictionary
  1065. @code
  1066. print version()
  1067. {'date': '2011', 'libgis_date': '2011-08-13 01:14:30 +0200 (Sat, 13 Aug 2011)',
  1068. 'version': '7.0.svn', 'libgis_revision': '47604', 'revision': '47963'}
  1069. @endcode
  1070. """
  1071. data = parse_command('g.version',
  1072. flags = 'rg')
  1073. for k, v in data.iteritems():
  1074. data[k.strip()] = v.replace('"', '').strip()
  1075. return data
  1076. # get debug_level
  1077. if find_program('g.gisenv', ['--help']):
  1078. debug_level = int(gisenv().get('DEBUG', 0))