module.py 17 KB

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