module.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Tue Apr 2 18:41:27 2013
  4. @author: pietro
  5. @code
  6. >>> import grass.pygrass.modules as pymod
  7. >>> import copy
  8. >>> region = pymod.Module("g.region")
  9. >>> region.flags["p"].value = True
  10. >>> region.flags["u"].value = True
  11. >>> region.flags["3"].value = True
  12. >>> region.get_bash()
  13. u'g.region -p -3 -u'
  14. >>> new_region = copy.deepcopy(region)
  15. >>> new_region.inputs["res"].value = "10"
  16. >>> new_region.get_bash()
  17. u'g.region res=10 -p -3 -u'
  18. >>> neighbors = pymod.Module("r.neighbors")
  19. >>> neighbors.inputs["input"].value = "mapA"
  20. >>> neighbors.outputs["output"].value = "mapB"
  21. >>> neighbors.inputs["size"].value = 5
  22. >>> neighbors.get_bash()
  23. u'r.neighbors input=mapA method=average size=5 quantile=0.5 output=mapB'
  24. >>> new_neighbors1 = copy.deepcopy(neighbors)
  25. >>> new_neighbors1.inputs["input"].value = "mapD"
  26. >>> new_neighbors1.inputs["size"].value = 3
  27. >>> new_neighbors1.get_bash()
  28. u'r.neighbors input=mapD method=average size=3 quantile=0.5 output=mapB'
  29. >>> new_neighbors2 = copy.deepcopy(neighbors)
  30. >>> new_neighbors2(input="mapD", size=3, run_=False)
  31. >>> new_neighbors2.get_bash()
  32. u'r.neighbors input=mapD method=average size=3 quantile=0.5 output=mapB'
  33. >>> neighbors = pymod.Module("r.neighbors")
  34. >>> neighbors.get_bash()
  35. u'r.neighbors method=average size=3 quantile=0.5'
  36. >>> new_neighbors3 = copy.deepcopy(neighbors)
  37. >>> new_neighbors3(input="mapA", size=3, output="mapB", run_=False)
  38. >>> new_neighbors3.get_bash()
  39. u'r.neighbors input=mapA method=average size=3 quantile=0.5 output=mapB'
  40. Run a second time
  41. >>> colors.run()
  42. Module('r.colors')
  43. >>> stdout, stderr = colors.popen.communicate(input="1 blue")
  44. >>> colors.popen.returncode
  45. 0
  46. >>> stdout
  47. >>> stderr.strip()
  48. "Color table for raster map <test_a> set to 'rules'"
  49. Multiple run test
  50. >>> colors = pymod.Module("r.colors", map="test_a",
  51. ... color="ryb", run_=False)
  52. >>> colors.run()
  53. Module('r.colors')
  54. >>> colors(color="gyr")
  55. >>> colors.run()
  56. Module('r.colors')
  57. >>> colors(color="ryg")
  58. >>> colors(stderr_=PIPE)
  59. >>> colors.run()
  60. Module('r.colors')
  61. >>> print(colors.outputs["stderr"].value.strip())
  62. Color table for raster map <test_a> set to 'ryg'
  63. >>> colors(color="byg")
  64. >>> colors(stdout_=PIPE)
  65. >>> colors.run()
  66. Module('r.colors')
  67. >>> print(colors.outputs["stderr"].value.strip())
  68. Color table for raster map <test_a> set to 'byg'
  69. @endcode
  70. """
  71. from __future__ import (nested_scopes, generators, division, absolute_import,
  72. with_statement, print_function, unicode_literals)
  73. import sys
  74. if sys.version_info[0] == 2:
  75. from itertools import izip_longest as zip_longest
  76. else:
  77. from itertools import zip_longest
  78. from xml.etree.ElementTree import fromstring
  79. import time
  80. from grass.script.core import Popen, PIPE
  81. from grass.pygrass.errors import GrassError, ParameterError
  82. from grass.pygrass.modules.interface.parameter import Parameter
  83. from grass.pygrass.modules.interface.flag import Flag
  84. from grass.pygrass.modules.interface.typedict import TypeDict
  85. from grass.pygrass.modules.interface.read import GETFROMTAG, DOC
  86. class ParallelModuleQueue(object):
  87. """This class is designed to run an arbitrary number of pygrass Module
  88. processes in parallel.
  89. Objects of type grass.pygrass.modules.Module can be put into the
  90. queue using put() method. When the queue is full with the maximum
  91. number of parallel processes it will wait for all processes to finish,
  92. sets the stdout and stderr of the Module object and removes it
  93. from the queue when its finished.
  94. This class will raise a GrassError in case a Module process exits
  95. with a return code other than 0.
  96. Usage:
  97. >>> import copy
  98. >>> import grass.pygrass.modules as pymod
  99. >>> mapcalc_list = []
  100. >>> mapcalc = pymod.Module("r.mapcalc",
  101. ... overwrite=True,
  102. ... run_=False,
  103. ... finish_=False)
  104. >>> queue = pymod.ParallelModuleQueue(max_num_procs=3)
  105. >>> for i in xrange(5):
  106. ... new_mapcalc = copy.deepcopy(mapcalc)
  107. ... mapcalc_list.append(new_mapcalc)
  108. ... new_mapcalc(expression="test_pygrass_%i = %i"%(i, i))
  109. ... queue.put(new_mapcalc)
  110. >>> queue.wait()
  111. >>> for mapcalc in mapcalc_list:
  112. ... print(mapcalc.popen.returncode)
  113. 0
  114. 0
  115. 0
  116. 0
  117. 0
  118. """
  119. def __init__(self, max_num_procs=1):
  120. """Constructor
  121. :param max_num_procs: The maximum number of Module processes that
  122. can be run in parallel
  123. :type max_num_procs: int
  124. """
  125. self._num_procs = int(max_num_procs)
  126. self._list = int(max_num_procs) * [None]
  127. self._proc_count = 0
  128. def put(self, module):
  129. """Put the next Module object in the queue
  130. To run the Module objects in parallel the run_ and finish_ options
  131. of the Module must be set to False.
  132. :param module: a preconfigured Module object with run_ and finish_
  133. set to False
  134. :type module: Module object
  135. """
  136. self._list[self._proc_count] = module
  137. self._list[self._proc_count].run()
  138. self._proc_count += 1
  139. if self._proc_count == self._num_procs:
  140. self.wait()
  141. def get(self, num):
  142. """Get a Module object from the queue
  143. :param num: the number of the object in queue
  144. :type num: int
  145. :returns: the Module object or None if num is not in the queue
  146. """
  147. if num < self._num_procs:
  148. return self._list[num]
  149. return None
  150. def get_num_run_procs(self):
  151. """Get the number of Module processes that are in the queue running
  152. or finished
  153. :returns: the maximum number fo Module processes running/finished in
  154. the queue
  155. """
  156. return len(self._list)
  157. def get_max_num_procs(self):
  158. """Return the maximum number of parallel Module processes
  159. """
  160. return self._num_procs
  161. def set_max_num_procs(self, max_num_procs):
  162. """Set the maximum number of Module processes that should run
  163. in parallel
  164. :param max_num_procs: The maximum number of Module processes that
  165. can be run in parallel
  166. :type max_num_procs: int
  167. """
  168. self._num_procs = int(max_num_procs)
  169. self.wait()
  170. def wait(self):
  171. """Wait for all Module processes that are in the list to finish
  172. and set the modules stdout and stderr output options
  173. """
  174. for proc in self._list:
  175. if proc:
  176. stdout, stderr = proc.popen.communicate(input=proc.stdin)
  177. proc.outputs['stdout'].value = stdout if stdout else ''
  178. proc.outputs['stderr'].value = stderr if stderr else ''
  179. if proc.popen.returncode != 0:
  180. GrassError(("Error running module %s") % (proc.name))
  181. self._list = self._num_procs * [None]
  182. self._proc_count = 0
  183. class Module(object):
  184. """
  185. Python allow developers to not specify all the arguments and
  186. keyword arguments of a method or function.
  187. def f(*args):
  188. for arg in args:
  189. print arg
  190. therefore if we call the function like:
  191. >>> f('grass', 'gis', 'modules')
  192. grass
  193. gis
  194. modules
  195. or we can define a new list:
  196. >>> words = ['grass', 'gis', 'modules']
  197. >>> f(*words)
  198. grass
  199. gis
  200. modules
  201. we can do the same with keyword arguments, rewrite the above function:
  202. def f(*args, **kargs):
  203. for arg in args:
  204. print arg
  205. for key, value in kargs.items():
  206. print "%s = %r" % (key, value)
  207. now we can use the new function, with:
  208. >>> f('grass', 'gis', 'modules', os = 'linux', language = 'python')
  209. grass
  210. gis
  211. modules
  212. os = 'linux'
  213. language = 'python'
  214. or, as before we can, define a dictionary and give the dictionary to
  215. the function, like:
  216. >>> keywords = {'os' : 'linux', 'language' : 'python'}
  217. >>> f(*words, **keywords)
  218. grass
  219. gis
  220. modules
  221. os = 'linux'
  222. language = 'python'
  223. In the Module class we heavily use this language feature to pass arguments
  224. and keyword arguments to the grass module.
  225. """
  226. def __init__(self, cmd, *args, **kargs):
  227. if isinstance(cmd, unicode):
  228. self.name = str(cmd)
  229. elif isinstance(cmd, str):
  230. self.name = cmd
  231. else:
  232. raise GrassError("Problem initializing the module {s}".format(s=cmd))
  233. try:
  234. # call the command with --interface-description
  235. get_cmd_xml = Popen([cmd, "--interface-description"], stdout=PIPE)
  236. except OSError as e:
  237. print("OSError error({0}): {1}".format(e.errno, e.strerror))
  238. str_err = "Error running: `%s --interface-description`."
  239. raise GrassError(str_err % self.name)
  240. # get the xml of the module
  241. self.xml = get_cmd_xml.communicate()[0]
  242. # transform and parse the xml into an Element class:
  243. # http://docs.python.org/library/xml.etree.elementtree.html
  244. tree = fromstring(self.xml)
  245. for e in tree:
  246. if e.tag not in ('parameter', 'flag'):
  247. self.__setattr__(e.tag, GETFROMTAG[e.tag](e))
  248. #
  249. # extract parameters from the xml
  250. #
  251. self.params_list = [Parameter(p) for p in tree.findall("parameter")]
  252. self.inputs = TypeDict(Parameter)
  253. self.outputs = TypeDict(Parameter)
  254. self.required = []
  255. # Insert parameters into input/output and required
  256. for par in self.params_list:
  257. if par.input:
  258. self.inputs[par.name] = par
  259. else:
  260. self.outputs[par.name] = par
  261. if par.required:
  262. self.required.append(par.name)
  263. #
  264. # extract flags from the xml
  265. #
  266. flags_list = [Flag(f) for f in tree.findall("flag")]
  267. self.flags = TypeDict(Flag)
  268. for flag in flags_list:
  269. self.flags[flag.name] = flag
  270. #
  271. # Add new attributes to the class
  272. #
  273. self.run_ = True
  274. self.finish_ = True
  275. self.env_ = None
  276. self.stdin_ = None
  277. self.stdin = None
  278. self.stdout_ = None
  279. self.stderr_ = None
  280. diz = {'name': 'stdin', 'required': False,
  281. 'multiple': False, 'type': 'all',
  282. 'value': None}
  283. self.inputs['stdin'] = Parameter(diz=diz)
  284. diz['name'] = 'stdout'
  285. self.outputs['stdout'] = Parameter(diz=diz)
  286. diz['name'] = 'stderr'
  287. self.outputs['stderr'] = Parameter(diz=diz)
  288. self.popen = None
  289. self.time = None
  290. if args or kargs:
  291. self.__call__(*args, **kargs)
  292. self.__call__.__func__.__doc__ = self.__doc__
  293. def __call__(self, *args, **kargs):
  294. if not args and not kargs:
  295. self.run()
  296. return
  297. #
  298. # check for extra kargs, set attribute and remove from dictionary
  299. #
  300. if 'flags' in kargs:
  301. for flg in kargs['flags']:
  302. self.flags[flg].value = True
  303. del(kargs['flags'])
  304. if 'run_' in kargs:
  305. self.run_ = kargs['run_']
  306. del(kargs['run_'])
  307. if 'stdin_' in kargs:
  308. self.inputs['stdin'].value = kargs['stdin_']
  309. del(kargs['stdin_'])
  310. if 'stdout_' in kargs:
  311. self.stdout_ = kargs['stdout_']
  312. del(kargs['stdout_'])
  313. if 'stderr_' in kargs:
  314. self.stderr_ = kargs['stderr_']
  315. del(kargs['stderr_'])
  316. if 'env_' in kargs:
  317. self.env_ = kargs['env_']
  318. del(kargs['env_'])
  319. if 'finish_' in kargs:
  320. self.finish_ = kargs['finish_']
  321. del(kargs['finish_'])
  322. #
  323. # check args
  324. #
  325. for param, arg in zip(self.params_list, args):
  326. param.value = arg
  327. for key, val in kargs.items():
  328. if key in self.inputs:
  329. self.inputs[key].value = val
  330. elif key in self.outputs:
  331. self.outputs[key].value = val
  332. elif key in self.flags:
  333. # we need to add this, because some parameters (overwrite,
  334. # verbose and quiet) work like parameters
  335. self.flags[key].value = val
  336. else:
  337. raise ParameterError('%s is not a valid parameter.' % key)
  338. #
  339. # check if execute
  340. #
  341. if self.run_:
  342. #
  343. # check reqire parameters
  344. #
  345. for k in self.required:
  346. if ((k in self.inputs and self.inputs[k].value is None) or
  347. (k in self.outputs and self.outputs[k].value is None)):
  348. msg = "Required parameter <%s> not set."
  349. raise ParameterError(msg % k)
  350. return self.run()
  351. def get_bash(self):
  352. """Prova"""
  353. return ' '.join(self.make_cmd())
  354. def get_python(self):
  355. """Prova"""
  356. prefix = self.name.split('.')[0]
  357. name = '_'.join(self.name.split('.')[1:])
  358. params = ', '.join([par.get_python() for par in self.params_list
  359. if par.get_python() != ''])
  360. flags = ''.join([flg.get_python()
  361. for flg in self.flags.values()
  362. if not flg.special and flg.get_python() != ''])
  363. special = ', '.join([flg.get_python()
  364. for flg in self.flags.values()
  365. if flg.special and flg.get_python() != ''])
  366. # pre name par flg special
  367. if flags and special:
  368. return "%s.%s(%s, flags=%r, %s)" % (prefix, name, params,
  369. flags, special)
  370. elif flags:
  371. return "%s.%s(%s, flags=%r)" % (prefix, name, params, flags)
  372. elif special:
  373. return "%s.%s(%s, %s)" % (prefix, name, params, special)
  374. else:
  375. return "%s.%s(%s)" % (prefix, name, params)
  376. def __str__(self):
  377. """Return the command string that can be executed in a shell
  378. """
  379. return ' '.join(self.make_cmd())
  380. def __repr__(self):
  381. return "Module(%r)" % self.name
  382. @property
  383. def __doc__(self):
  384. """{cmd_name}({cmd_params})
  385. """
  386. head = DOC['head'].format(cmd_name=self.name,
  387. cmd_params=('\n' + # go to a new line
  388. # give space under the function name
  389. (' ' * (len(self.name) + 1))).join([', '.join(
  390. # transform each parameter in string
  391. [str(param) for param in line if param is not None])
  392. # make a list of parameters with only 3 param per line
  393. for line in zip_longest(*[iter(self.params_list)] * 3)]),)
  394. params = '\n'.join([par.__doc__ for par in self.params_list])
  395. flags = self.flags.__doc__
  396. return '\n'.join([head, params, DOC['flag_head'], flags, DOC['foot']])
  397. def get_dict(self):
  398. """Return a dictionary that includes the name, all valid
  399. inputs, outputs and flags
  400. """
  401. dic = {}
  402. dic['name'] = self.name
  403. dic['inputs'] = [(k, v.value) for k, v in self.inputs.items()
  404. if v.value]
  405. dic['outputs'] = [(k, v.value) for k, v in self.outputs.items()
  406. if v.value]
  407. dic['flags'] = [flg for flg in self.flags if self.flags[flg].value]
  408. return dic
  409. def make_cmd(self):
  410. """Create the command string that can be executed in a shell
  411. :returns: the command string
  412. """
  413. skip = ['stdin', 'stdout', 'stderr']
  414. args = [self.name, ]
  415. for key in self.inputs:
  416. if key not in skip and self.inputs[key].value:
  417. args.append(self.inputs[key].get_bash())
  418. for key in self.outputs:
  419. if key not in skip and self.outputs[key].value:
  420. args.append(self.outputs[key].get_bash())
  421. for flg in self.flags:
  422. if self.flags[flg].value:
  423. args.append(str(self.flags[flg]))
  424. return args
  425. def run(self, node=None):
  426. """Run the module
  427. :param node:
  428. :type node:
  429. This function will wait for the process to terminate in case
  430. finish_==True and sets up stdout and stderr. If finish_==False this
  431. function will return after starting the process. Use
  432. self.popen.communicate() of self.popen.wait() to wait for the process
  433. termination. The handling of stdout and stderr must then be done
  434. outside of this function.
  435. """
  436. if self.inputs['stdin'].value:
  437. self.stdin = self.inputs['stdin'].value
  438. self.stdin_ = PIPE
  439. cmd = self.make_cmd()
  440. start = time.time()
  441. self.popen = Popen(cmd,
  442. stdin=self.stdin_,
  443. stdout=self.stdout_,
  444. stderr=self.stderr_,
  445. env=self.env_)
  446. if self.finish_:
  447. stdout, stderr = self.popen.communicate(input=self.stdin)
  448. self.outputs['stdout'].value = stdout if stdout else ''
  449. self.outputs['stderr'].value = stderr if stderr else ''
  450. self.time = time.time() - start
  451. return self
  452. ###############################################################################
  453. if __name__ == "__main__":
  454. import doctest
  455. doctest.testmod()