__init__.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Thu Jul 12 10:23:15 2012
  4. @author: pietro
  5. """
  6. from __future__ import print_function
  7. import subprocess
  8. import fnmatch
  9. try:
  10. from collections import OrderedDict
  11. except:
  12. from pygrass.orderdict import OrderedDict
  13. from itertools import izip_longest
  14. from xml.etree.ElementTree import fromstring
  15. import numpy as np
  16. import grass
  17. #
  18. # this dictionary is used to extract the value of interest from the xml
  19. # the lambda experssion is used to define small simple functions,
  20. # is equivalent to: ::
  21. #
  22. # def f(p):
  23. # return p.text.strip()
  24. #
  25. # and then we call f(p)
  26. #
  27. _GETFROMTAG = {
  28. 'description': lambda p: p.text.strip(),
  29. 'keydesc': lambda p: p.text.strip(),
  30. 'gisprompt': lambda p: dict(p.items()),
  31. 'default': lambda p: p.text.strip(),
  32. 'values': lambda p: [e.text.strip() for e in p.findall('value/name')],
  33. 'value': lambda p: None,
  34. 'guisection': lambda p: p.text.strip(),
  35. 'label': lambda p: p.text.strip(),
  36. 'suppress_required': lambda p: None,
  37. 'keywords': lambda p: p.text.strip(),
  38. }
  39. _GETTYPE = {
  40. 'string': str,
  41. 'integer': int,
  42. 'float': float,
  43. 'double': float,
  44. }
  45. def stdout2dict(stdout, sep='=', default=None, val_type=None, vsep=None):
  46. """Return a dictionary where entries are separated
  47. by newlines and the key and value are separated by `sep' (default: `=').
  48. Use the grass.core.parse_key_val function
  49. sep: key/value separator
  50. default: default value to be used
  51. val_type: value type (None for no cast)
  52. vsep: vertical separator (default os.linesep)
  53. """
  54. return grass.script.core.parse_key_val(stdout, sep, default,
  55. val_type, vsep)
  56. class ParameterError(Exception):
  57. pass
  58. class FlagError(Exception):
  59. pass
  60. def _element2dict(xparameter):
  61. diz = dict(xparameter.items())
  62. for p in xparameter:
  63. if p.tag in _GETFROMTAG:
  64. diz[p.tag] = _GETFROMTAG[p.tag](p)
  65. else:
  66. print('New tag: %s, ignored' % p.tag)
  67. return diz
  68. # dictionary used to create docstring for the objects
  69. _DOC = {
  70. #------------------------------------------------------------
  71. # head
  72. 'head': """{cmd_name}({cmd_params})
  73. Parameters
  74. ----------
  75. """,
  76. #------------------------------------------------------------
  77. # param
  78. 'param': """{name}: {default}{required}{multi}{ptype}
  79. {description}{values}""",
  80. #------------------------------------------------------------
  81. # flag_head
  82. 'flag_head': """
  83. Flags
  84. ------
  85. """,
  86. #------------------------------------------------------------
  87. # flag
  88. 'flag': """{name}: {default}
  89. {description}""",
  90. #------------------------------------------------------------
  91. # foot
  92. 'foot': """
  93. Special Parameters
  94. ------------------
  95. The Module class have some optional parameters which are distinct using a final
  96. underscore.
  97. run_: True, optional
  98. If True execute the module.
  99. finish_: True, optional
  100. If True wait untill the end of the module execution, and store the module
  101. outputs into stdout, stderr attributes of the class.
  102. stdin_: PIPE,
  103. Set the standard input
  104. """}
  105. class Parameter(object):
  106. def __init__(self, xparameter=None, diz=None):
  107. self._value = None
  108. diz = _element2dict(xparameter) if xparameter is not None else diz
  109. if diz is None:
  110. raise TypeError('Xparameter or diz are required')
  111. self.name = diz['name']
  112. self.required = True if diz['required'] == 'yes' else False
  113. self.multiple = True if diz['multiple'] == 'yes' else False
  114. # check the type
  115. if diz['type'] in _GETTYPE:
  116. self.type = _GETTYPE[diz['type']]
  117. self.typedesc = diz['type']
  118. self._type = _GETTYPE[diz['type']]
  119. else:
  120. raise TypeError('New type: %s, ignored' % diz['type'])
  121. self.description = diz.get('description', None)
  122. self.keydesc = diz.get('keydesc', None)
  123. self.values = [self._type(
  124. i) for i in diz['values']] if 'values' in diz else None
  125. self.default = self._type(
  126. diz['default']) if 'default' in diz else None
  127. self.guisection = diz.get('guisection', None)
  128. if 'gisprompt' in diz:
  129. self.type = diz['gisprompt']['prompt']
  130. self.input = False if diz['gisprompt']['age'] == 'new' else True
  131. else:
  132. self.input = True
  133. def _get_value(self):
  134. return self._value
  135. def _set_value(self, value):
  136. if isinstance(value, list) or isinstance(value, tuple):
  137. if self.multiple:
  138. # check each value
  139. self._value = [
  140. val for val in value if isinstance(value, self._type)]
  141. else:
  142. str_err = 'The Parameter <%s>, not support multiple inputs'
  143. raise TypeError(str_err % self.name)
  144. elif isinstance(value, self._type):
  145. if self.values:
  146. if value in self.values:
  147. self._value = value
  148. else:
  149. raise ValueError('The Parameter <%s>, must be one of: %r' %
  150. (self.name, self.values))
  151. else:
  152. self._value = value
  153. else:
  154. str_err = 'The Parameter <%s>, require: %s, get: %s instead'
  155. raise TypeError(str_err % (self.name, self.typedesc, type(value)))
  156. # here the property function is used to transform value in an attribute
  157. # in this case we define which function must be use to get/set the value
  158. value = property(fget=_get_value, fset=_set_value)
  159. def __str__(self):
  160. if isinstance(self._value, list) or isinstance(self._value, tuple):
  161. value = ','.join([str(v) for v in self._value])
  162. else:
  163. value = str(self._value)
  164. return """%s=%s""" % (self.name, value)
  165. def __repr__(self):
  166. str_repr = "Parameter <%s> (required:%s, type:%s, multiple:%s)"
  167. return str_repr % (self.name,
  168. "yes" if self.required else "no",
  169. self.type if self.type in (
  170. 'raster', 'vector') else self.typedesc,
  171. "yes" if self.multiple else "no")
  172. # here we use property with a decorator, in this way we mask a method as
  173. # a class attribute
  174. @property
  175. def __doc__(self):
  176. """Return the docstring of the parameter
  177. {name}: {default}{required}{multi}{ptype}
  178. {description}{values}"","""
  179. return _DOC['param'].format(name=self.name,
  180. default=repr(self.default) + ', ' if self.default else '',
  181. required='required, ' if self.required else 'optional, ',
  182. multi='multi' if self.multiple else '',
  183. ptype=self.typedesc, description=self.description,
  184. values='\n Values: {0}'.format(', '.join([repr(val)
  185. for val in self.values]))
  186. if self.values else '')
  187. class TypeDict(OrderedDict):
  188. def __init__(self, dict_type, *args, **kargs):
  189. self.type = dict_type
  190. super(TypeDict, self).__init__(*args, **kargs)
  191. def __setitem__(self, key, value):
  192. if isinstance(value, self.type):
  193. super(TypeDict, self).__setitem__(key, value)
  194. else:
  195. cl = repr(self.type).translate(None, "'<> ").split('.')
  196. str_err = 'The value: %r is not a %s object'
  197. raise TypeError(str_err % (value, cl[-1].title()))
  198. @property
  199. def __doc__(self):
  200. return '\n'.join([self.__getitem__(obj).__doc__
  201. for obj in self.__iter__()])
  202. def __call__(self):
  203. return [self.__getitem__(obj) for obj in self.__iter__()]
  204. class Flag(object):
  205. def __init__(self, xflag=None, diz=None):
  206. self.value = None
  207. diz = _element2dict(xflag) if xflag is not None else diz
  208. self.name = diz['name']
  209. self.special = True if self.name in (
  210. 'verbose', 'overwrite', 'quiet', 'run') else False
  211. self.description = diz['description']
  212. self.default = diz.get('default', None)
  213. self.guisection = diz.get('guisection', None)
  214. def __str__(self):
  215. if self.value:
  216. if self.special:
  217. return '--%s' % self.name[0]
  218. else:
  219. return '-%s' % self.name
  220. else:
  221. return ''
  222. def __repr__(self):
  223. return "Flag <%s> (%s)" % (self.name, self.description)
  224. @property
  225. def __doc__(self):
  226. """
  227. {name}: {default}
  228. {description}"""
  229. return _DOC['flag'].format(name=self.name,
  230. default=repr(self.default),
  231. description=self.description)
  232. class Module(object):
  233. """
  234. Python allow developers to not specify all the arguments and
  235. keyword arguments of a method or function.
  236. ::
  237. def f(*args):
  238. for arg in args:
  239. print arg
  240. therefore if we call the function like: ::
  241. >>> f('grass', 'gis', 'modules')
  242. grass
  243. gis
  244. modules
  245. or we can define a new list: ::
  246. >>> words = ['grass', 'gis', 'modules']
  247. >>> f(*words)
  248. grass
  249. gis
  250. modules
  251. we can do the same with keyword arguments, rewrite the above function: ::
  252. def f(*args, **kargs):
  253. for arg in args:
  254. print arg
  255. for key, value in kargs.items():
  256. print "%s = %r" % (key, value)
  257. now we can use the new function, with: ::
  258. >>> f('grass', 'gis', 'modules', os = 'linux', language = 'python')
  259. grass
  260. gis
  261. modules
  262. os = 'linux'
  263. language = 'python'
  264. or, as before we can, define a dictionary and give the dictionary to
  265. the function, like: ::
  266. >>> keywords = {'os' : 'linux', 'language' : 'python'}
  267. >>> f(*words, **keywords)
  268. grass
  269. gis
  270. modules
  271. os = 'linux'
  272. language = 'python'
  273. In the Module class we heavily use this language feature to pass arguments
  274. and keyword arguments to the grass module.
  275. """
  276. def __init__(self, cmd, *args, **kargs):
  277. self.name = cmd
  278. # call the command with --interface-description
  279. get_cmd_xml = subprocess.Popen([cmd, "--interface-description"],
  280. stdout=subprocess.PIPE)
  281. # get the xml of the module
  282. self.xml = get_cmd_xml.communicate()[0]
  283. # transform and parse the xml into an Element class:
  284. # http://docs.python.org/library/xml.etree.elementtree.html
  285. tree = fromstring(self.xml)
  286. for e in tree:
  287. if e.tag not in ('parameter', 'flag'):
  288. self.__setattr__(e.tag, _GETFROMTAG[e.tag](e))
  289. #
  290. # extract parameters from the xml
  291. #
  292. self.params_list = [Parameter(p) for p in tree.findall("parameter")]
  293. self.inputs = TypeDict(Parameter)
  294. self.outputs = TypeDict(Parameter)
  295. self.required = []
  296. # Insert parameters into input/output and required
  297. for par in self.params_list:
  298. if par.input:
  299. self.inputs[par.name] = par
  300. else:
  301. self.outputs[par.name] = par
  302. if par.required:
  303. self.required.append(par)
  304. #
  305. # extract flags from the xml
  306. #
  307. flags_list = [Flag(f) for f in tree.findall("flag")]
  308. self.flags_dict = TypeDict(Flag)
  309. for flag in flags_list:
  310. self.flags_dict[flag.name] = flag
  311. #
  312. # Add new attributes to the class
  313. #
  314. self._flags = ''
  315. self.run_ = True
  316. self.finish_ = True
  317. self.stdin_ = None
  318. self.stdout_ = None
  319. self.stderr_ = None
  320. self.popen = None
  321. if args or kargs:
  322. self.__call__(*args, **kargs)
  323. def _get_flags(self):
  324. return self._flags
  325. def _set_flags(self, value):
  326. if isinstance(value, str):
  327. flgs = [flg for flg in self.flags_dict
  328. if not self.flags_dict[flg].special]
  329. # we need to check if the flag is valid, special flags are not
  330. # allow
  331. if value in flgs:
  332. self._flags = value
  333. else:
  334. raise ValueError('Flag not valid, valid flag are: %r' % flgs)
  335. else:
  336. raise TypeError('The flags attribute must be a string')
  337. flags = property(fget=_get_flags, fset=_set_flags)
  338. def __call__(self, *args, **kargs):
  339. if not args and not kargs:
  340. self.run()
  341. return
  342. #
  343. # check for extra kargs, set attribute and remove from dictionary
  344. #
  345. if 'flags' in kargs:
  346. self.flags = kargs['flags']
  347. del(kargs['flags'])
  348. if 'run_' in kargs:
  349. self.run_ = kargs['run_']
  350. del(kargs['run_'])
  351. if 'stdin_' in kargs:
  352. self.stdin_ = kargs['stdin_']
  353. del(kargs['stdin_'])
  354. if 'stdout_' in kargs:
  355. self.stdout_ = kargs['stdout_']
  356. del(kargs['stdout_'])
  357. if 'stderr_' in kargs:
  358. self.stderr_ = kargs['stderr_']
  359. del(kargs['stderr_'])
  360. if 'finish_' in kargs:
  361. self.finish_ = kargs['finish_']
  362. del(kargs['finish_'])
  363. #
  364. # check args
  365. #
  366. for param, arg in zip(self.params_list, args):
  367. param.value = arg
  368. for key, val in kargs.items():
  369. if key in self.inputs:
  370. self.inputs[key].value = val
  371. elif key in self.outputs:
  372. self.outputs[key].value = val
  373. elif key in self.flags_dict:
  374. # we need to add this, because some parameters (overwrite,
  375. # verbose and quiet) work like parameters
  376. self.flags_dict[key].value = val
  377. else:
  378. raise ParameterError('Parameter not found')
  379. #
  380. # check reqire parameters
  381. #
  382. for par in self.required:
  383. if par.value is None:
  384. raise ParameterError(
  385. "Required parameter <%s> not set." % par.name)
  386. #
  387. # check flags parameters
  388. #
  389. if self.flags:
  390. # check each character in flags
  391. for flag in self.flags:
  392. if flag in self.flags_dict:
  393. self.flags_dict[flag].value = True
  394. else:
  395. raise FlagError('Flag "%s" not valid.')
  396. #
  397. # check if execute
  398. #
  399. if self.run_:
  400. self.run()
  401. def __str__(self):
  402. return ' '.join(self.make_cmd())
  403. @property
  404. def __doc__(self):
  405. """{cmd_name}({cmd_params})
  406. """
  407. head = _DOC['head'].format(cmd_name=self.name,
  408. cmd_params=('\n' + # go to a new line
  409. # give space under the function name
  410. (' ' * (len(self.name) + 1))).join([', '.join(
  411. # transform each parameter in string
  412. [str(param) for param in line if param is not None])
  413. # make a list of parameters with only 3 param per line
  414. for line in izip_longest(*[iter(self.params_list)] * 3)]),)
  415. params = '\n'.join([par.__doc__ for par in self.params_list])
  416. flags = self.flags_dict.__doc__
  417. return '\n'.join([head, params, _DOC['flag_head'], flags])
  418. def make_cmd(self):
  419. args = [self.name, ]
  420. for par in self.params_list:
  421. if par.value is not None:
  422. args.append(str(par))
  423. for flg in self.flags_dict:
  424. if self.flags_dict[flg].value is not None:
  425. args.append(str(self.flags_dict[flg]))
  426. return args
  427. def run(self, node=None):
  428. cmd = self.make_cmd()
  429. #print(repr(cmd))
  430. self.popen = subprocess.Popen(cmd, stdin=self.stdin_,
  431. stdout=self.stdout_,
  432. stderr=self.stderr_)
  433. if self.finish_:
  434. self.popen.wait()
  435. self.stdout, self.stderr = self.popen.communicate()
  436. _CMDS = list(grass.script.core.get_commands()[0])
  437. _CMDS.sort()
  438. class MetaModule(object):
  439. def __init__(self, prefix):
  440. self.prefix = prefix
  441. def __dir__(self):
  442. return [mod[(len(self.prefix) + 1):].replace('.', '_')
  443. for mod in fnmatch.filter(_CMDS, "%s.*" % self.prefix)]
  444. def __getattr__(self, name):
  445. return Module('%s.%s' % (self.prefix, name.replace('_', '.')))
  446. # http://grass.osgeo.org/grass70/manuals/html70_user/full_index.html
  447. #[ d.* | db.* | g.* | i.* | m.* | ps.* | r.* | r3.* | t.* | v.* ]
  448. #
  449. # d.* display commands
  450. # db.* database commands
  451. # g.* general commands
  452. # i.* imagery commands
  453. # m.* miscellaneous commands
  454. # ps.* postscript commands
  455. # r.* raster commands
  456. # r3.* raster3D commands
  457. # t.* temporal commands
  458. # v.* vector commands
  459. display = MetaModule('d')
  460. database = MetaModule('db')
  461. general = MetaModule('g')
  462. imagery = MetaModule('i')
  463. miscellaneous = MetaModule('m')
  464. postscript = MetaModule('ps')
  465. raster = MetaModule('r')
  466. raster3D = MetaModule('r3')
  467. temporal = MetaModule('t')
  468. vector = MetaModule('v')