module.py 19 KB

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