module.py 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013
  1. # -*- coding: utf-8 -*-
  2. from __future__ import (nested_scopes, generators, division, absolute_import,
  3. with_statement, print_function, unicode_literals)
  4. import sys
  5. from multiprocessing import cpu_count, Process, Queue
  6. import time
  7. from xml.etree.ElementTree import fromstring
  8. from grass.exceptions import CalledModuleError, GrassError, ParameterError
  9. from grass.script.core import Popen, PIPE, use_temp_region, del_temp_region
  10. from .docstring import docstring_property
  11. from .parameter import Parameter
  12. from .flag import Flag
  13. from .typedict import TypeDict
  14. from .read import GETFROMTAG, DOC
  15. from .env import G_debug
  16. if sys.version_info[0] == 2:
  17. from itertools import izip_longest as zip_longest
  18. else:
  19. from itertools import zip_longest
  20. unicode = str
  21. def _get_bash(self, *args, **kargs):
  22. return self.get_bash()
  23. class ParallelModuleQueue(object):
  24. """This class is designed to run an arbitrary number of pygrass Module or MultiModule
  25. processes in parallel.
  26. Objects of type grass.pygrass.modules.Module or
  27. grass.pygrass.modules.MultiModule can be put into the
  28. queue using put() method. When the queue is full with the maximum
  29. number of parallel processes it will wait for all processes to finish,
  30. sets the stdout and stderr of the Module object and removes it
  31. from the queue when its finished.
  32. To finish the queue before the maximum number of parallel
  33. processes was reached call wait() .
  34. This class will raise a GrassError in case a Module process exits
  35. with a return code other than 0.
  36. Processes that were run asynchronously with the MultiModule class
  37. will not raise a GrassError in case of failure. This must be manually checked
  38. by accessing finished modules by calling get_finished_modules().
  39. Usage:
  40. Check with a queue size of 3 and 5 processes
  41. >>> import copy
  42. >>> from grass.pygrass.modules import Module, ParallelModuleQueue
  43. >>> mapcalc_list = []
  44. Setting run_ to False is important, otherwise a parallel processing is not possible
  45. >>> mapcalc = Module("r.mapcalc", overwrite=True, run_=False)
  46. >>> queue = ParallelModuleQueue(nprocs=3)
  47. >>> for i in xrange(5):
  48. ... new_mapcalc = copy.deepcopy(mapcalc)
  49. ... mapcalc_list.append(new_mapcalc)
  50. ... m = new_mapcalc(expression="test_pygrass_%i = %i"%(i, i))
  51. ... queue.put(m)
  52. >>> queue.wait()
  53. >>> mapcalc_list = queue.get_finished_modules()
  54. >>> queue.get_num_run_procs()
  55. 0
  56. >>> queue.get_max_num_procs()
  57. 3
  58. >>> for mapcalc in mapcalc_list:
  59. ... print(mapcalc.popen.returncode)
  60. 0
  61. 0
  62. 0
  63. 0
  64. 0
  65. Check with a queue size of 8 and 5 processes
  66. >>> queue = ParallelModuleQueue(nprocs=8)
  67. >>> mapcalc_list = []
  68. >>> for i in xrange(5):
  69. ... new_mapcalc = copy.deepcopy(mapcalc)
  70. ... mapcalc_list.append(new_mapcalc)
  71. ... m = new_mapcalc(expression="test_pygrass_%i = %i"%(i, i))
  72. ... queue.put(m)
  73. >>> queue.wait()
  74. >>> mapcalc_list = queue.get_finished_modules()
  75. >>> queue.get_num_run_procs()
  76. 0
  77. >>> queue.get_max_num_procs()
  78. 8
  79. >>> for mapcalc in mapcalc_list:
  80. ... print(mapcalc.popen.returncode)
  81. 0
  82. 0
  83. 0
  84. 0
  85. 0
  86. Check MultiModule approach with three by two processes running in a background process
  87. >>> gregion = Module("g.region", flags="p", run_=False)
  88. >>> queue = ParallelModuleQueue(nprocs=3)
  89. >>> proc_list = []
  90. >>> for i in xrange(3):
  91. ... new_gregion = copy.deepcopy(gregion)
  92. ... proc_list.append(new_gregion)
  93. ... new_mapcalc = copy.deepcopy(mapcalc)
  94. ... m = new_mapcalc(expression="test_pygrass_%i = %i"%(i, i))
  95. ... proc_list.append(new_mapcalc)
  96. ... mm = MultiModule(module_list=[new_gregion, new_mapcalc], sync=False, set_temp_region=True)
  97. ... queue.put(mm)
  98. >>> queue.wait()
  99. >>> proc_list = queue.get_finished_modules()
  100. >>> queue.get_num_run_procs()
  101. 0
  102. >>> queue.get_max_num_procs()
  103. 3
  104. >>> for proc in proc_list:
  105. ... print(proc.popen.returncode)
  106. 0
  107. 0
  108. 0
  109. 0
  110. 0
  111. 0
  112. Check with a queue size of 8 and 4 processes
  113. >>> queue = ParallelModuleQueue(nprocs=8)
  114. >>> mapcalc_list = []
  115. >>> new_mapcalc = copy.deepcopy(mapcalc)
  116. >>> mapcalc_list.append(new_mapcalc)
  117. >>> m = new_mapcalc(expression="test_pygrass_1 =1")
  118. >>> queue.put(m)
  119. >>> queue.get_num_run_procs()
  120. 1
  121. >>> new_mapcalc = copy.deepcopy(mapcalc)
  122. >>> mapcalc_list.append(new_mapcalc)
  123. >>> m = new_mapcalc(expression="test_pygrass_2 =2")
  124. >>> queue.put(m)
  125. >>> queue.get_num_run_procs()
  126. 2
  127. >>> new_mapcalc = copy.deepcopy(mapcalc)
  128. >>> mapcalc_list.append(new_mapcalc)
  129. >>> m = new_mapcalc(expression="test_pygrass_3 =3")
  130. >>> queue.put(m)
  131. >>> queue.get_num_run_procs()
  132. 3
  133. >>> new_mapcalc = copy.deepcopy(mapcalc)
  134. >>> mapcalc_list.append(new_mapcalc)
  135. >>> m = new_mapcalc(expression="test_pygrass_4 =4")
  136. >>> queue.put(m)
  137. >>> queue.get_num_run_procs()
  138. 4
  139. >>> queue.wait()
  140. >>> mapcalc_list = queue.get_finished_modules()
  141. >>> queue.get_num_run_procs()
  142. 0
  143. >>> queue.get_max_num_procs()
  144. 8
  145. >>> for mapcalc in mapcalc_list:
  146. ... print(mapcalc.popen.returncode)
  147. 0
  148. 0
  149. 0
  150. 0
  151. Check with a queue size of 3 and 4 processes
  152. >>> queue = ParallelModuleQueue(nprocs=3)
  153. >>> mapcalc_list = []
  154. >>> new_mapcalc = copy.deepcopy(mapcalc)
  155. >>> mapcalc_list.append(new_mapcalc)
  156. >>> m = new_mapcalc(expression="test_pygrass_1 =1")
  157. >>> queue.put(m)
  158. >>> queue.get_num_run_procs()
  159. 1
  160. >>> new_mapcalc = copy.deepcopy(mapcalc)
  161. >>> mapcalc_list.append(new_mapcalc)
  162. >>> m = new_mapcalc(expression="test_pygrass_2 =2")
  163. >>> queue.put(m)
  164. >>> queue.get_num_run_procs()
  165. 2
  166. >>> new_mapcalc = copy.deepcopy(mapcalc)
  167. >>> mapcalc_list.append(new_mapcalc)
  168. >>> m = new_mapcalc(expression="test_pygrass_3 =3")
  169. >>> queue.put(m) # Now it will wait until all procs finish and set the counter back to 0
  170. >>> queue.get_num_run_procs()
  171. 0
  172. >>> new_mapcalc = copy.deepcopy(mapcalc)
  173. >>> mapcalc_list.append(new_mapcalc)
  174. >>> m = new_mapcalc(expression="test_pygrass_%i = %i"%(i, i))
  175. >>> queue.put(m)
  176. >>> queue.get_num_run_procs()
  177. 1
  178. >>> queue.wait()
  179. >>> mapcalc_list = queue.get_finished_modules()
  180. >>> queue.get_num_run_procs()
  181. 0
  182. >>> queue.get_max_num_procs()
  183. 3
  184. >>> for mapcalc in mapcalc_list:
  185. ... print(mapcalc.popen.returncode)
  186. 0
  187. 0
  188. 0
  189. 0
  190. """
  191. def __init__(self, nprocs=1):
  192. """Constructor
  193. :param nprocs: The maximum number of Module processes that
  194. can be run in parallel, default is 1, if None
  195. then use all the available CPUs.
  196. :type nprocs: int
  197. """
  198. nprocs = int(nprocs) if nprocs else cpu_count()
  199. self._num_procs = nprocs
  200. self._list = nprocs * [None]
  201. self._proc_count = 0
  202. self._finished_modules = [] # Store all processed modules in a list
  203. def put(self, module):
  204. """Put the next Module or MultiModule object in the queue
  205. To run the Module objects in parallel the run\_ and finish\_ options
  206. of the Module must be set to False.
  207. :param module: a preconfigured Module or MultiModule object that were configured
  208. with run\_ and finish\_ set to False,
  209. :type module: Module or MultiModule object
  210. """
  211. self._list[self._proc_count] = module
  212. # Force that finish is False, otherwise the execution
  213. # will not be parallel
  214. self._list[self._proc_count].finish_ = False
  215. self._list[self._proc_count].run()
  216. self._proc_count += 1
  217. if self._proc_count == self._num_procs:
  218. self.wait()
  219. def get(self, num):
  220. """Get a Module object or list of Module objects from the queue
  221. :param num: the number of the object in queue
  222. :type num: int
  223. :returns: the Module object or list of Module objects or None if num is not in the queue
  224. """
  225. if num < self._num_procs:
  226. return self._list[num]
  227. return None
  228. def get_num_run_procs(self):
  229. """Get the number of Module processes that are in the queue running
  230. or finished
  231. :returns: the number fo Module processes running/finished in the queue
  232. """
  233. return self._proc_count
  234. def get_max_num_procs(self):
  235. """Return the maximum number of parallel Module processes
  236. :returns: the maximum number of parallel Module processes
  237. """
  238. return self._num_procs
  239. def set_max_num_procs(self, nprocs):
  240. """Set the maximum number of Module processes that should run
  241. in parallel
  242. :param nprocs: The maximum number of Module processes that can be
  243. run in parallel
  244. :type nprocs: int
  245. """
  246. self._num_procs = int(nprocs)
  247. self.wait()
  248. def get_finished_modules(self):
  249. """Return all finished processes that were run by this queue
  250. :return: A list of Module objects
  251. """
  252. return self._finished_modules
  253. def wait(self):
  254. """Wait for all Module processes that are in the list to finish
  255. and set the modules stdout and stderr output options
  256. :return: A list of modules that were run
  257. """
  258. for proc in self._list:
  259. if proc:
  260. if isinstance(proc, Module):
  261. self._finished_modules.extend([proc.wait(),])
  262. else:
  263. self._finished_modules.extend(proc.wait())
  264. self._list = self._num_procs * [None]
  265. self._proc_count = 0
  266. class Module(object):
  267. """This class is design to wrap/run/interact with the GRASS modules.
  268. The class during the init phase read the XML description generate using
  269. the ``--interface-description`` in order to understand which parameters
  270. are required which optionals. ::
  271. >>> from grass.pygrass.modules import Module
  272. >>> from subprocess import PIPE
  273. >>> import copy
  274. >>> region = Module("g.region")
  275. >>> region.flags.p = True # set flags
  276. >>> region.flags.u = True
  277. >>> region.flags["3"].value = True # set numeric flags
  278. >>> region.get_bash()
  279. u'g.region -p -3 -u'
  280. >>> new_region = copy.deepcopy(region)
  281. >>> new_region.inputs.res = "10"
  282. >>> new_region.get_bash()
  283. u'g.region res=10 -p -3 -u'
  284. >>> neighbors = Module("r.neighbors")
  285. >>> neighbors.inputs.input = "mapA"
  286. >>> neighbors.outputs.output = "mapB"
  287. >>> neighbors.inputs.size = 5
  288. >>> neighbors.inputs.quantile = 0.5
  289. >>> neighbors.get_bash()
  290. u'r.neighbors input=mapA method=average size=5 quantile=0.5 output=mapB'
  291. >>> new_neighbors1 = copy.deepcopy(neighbors)
  292. >>> new_neighbors1.inputs.input = "mapD"
  293. >>> new_neighbors1.inputs.size = 3
  294. >>> new_neighbors1.inputs.quantile = 0.5
  295. >>> new_neighbors1.get_bash()
  296. u'r.neighbors input=mapD method=average size=3 quantile=0.5 output=mapB'
  297. >>> new_neighbors2 = copy.deepcopy(neighbors)
  298. >>> new_neighbors2(input="mapD", size=3, run_=False)
  299. Module('r.neighbors')
  300. >>> new_neighbors2.get_bash()
  301. u'r.neighbors input=mapD method=average size=3 quantile=0.5 output=mapB'
  302. >>> neighbors = Module("r.neighbors")
  303. >>> neighbors.get_bash()
  304. u'r.neighbors method=average size=3'
  305. >>> new_neighbors3 = copy.deepcopy(neighbors)
  306. >>> new_neighbors3(input="mapA", size=3, output="mapB", run_=False)
  307. Module('r.neighbors')
  308. >>> new_neighbors3.get_bash()
  309. u'r.neighbors input=mapA method=average size=3 output=mapB'
  310. >>> mapcalc = Module("r.mapcalc", expression="test_a = 1",
  311. ... overwrite=True, run_=False)
  312. >>> mapcalc.run()
  313. Module('r.mapcalc')
  314. >>> mapcalc.popen.returncode
  315. 0
  316. >>> mapcalc = Module("r.mapcalc", expression="test_a = 1",
  317. ... overwrite=True, run_=False, finish_=False)
  318. >>> mapcalc.run()
  319. Module('r.mapcalc')
  320. >>> p = mapcalc.wait()
  321. >>> p.popen.returncode
  322. 0
  323. >>> mapcalc.run()
  324. Module('r.mapcalc')
  325. >>> p = mapcalc.wait()
  326. >>> p.popen.returncode
  327. 0
  328. >>> colors = Module("r.colors", map="test_a", rules="-",
  329. ... run_=False, stdout_=PIPE,
  330. ... stderr_=PIPE, stdin_="1 red")
  331. >>> colors.run()
  332. Module('r.colors')
  333. >>> p = mapcalc.wait()
  334. >>> p.popen.returncode
  335. 0
  336. >>> colors.inputs["stdin"].value
  337. u'1 red'
  338. >>> colors.outputs["stdout"].value
  339. u''
  340. >>> colors.outputs["stderr"].value.strip()
  341. "Color table for raster map <test_a> set to 'rules'"
  342. >>> colors = Module("r.colors", map="test_a", rules="-",
  343. ... run_=False, finish_=False, stdin_=PIPE)
  344. >>> colors.run()
  345. Module('r.colors')
  346. >>> stdout, stderr = colors.popen.communicate(input="1 red")
  347. >>> colors.popen.returncode
  348. 0
  349. >>> stdout
  350. >>> stderr
  351. >>> colors = Module("r.colors", map="test_a", rules="-",
  352. ... run_=False, finish_=False,
  353. ... stdin_=PIPE, stderr_=PIPE)
  354. >>> colors.run()
  355. Module('r.colors')
  356. >>> stdout, stderr = colors.popen.communicate(input="1 red")
  357. >>> colors.popen.returncode
  358. 0
  359. >>> stdout
  360. >>> stderr.strip()
  361. "Color table for raster map <test_a> set to 'rules'"
  362. Run a second time
  363. >>> colors.run()
  364. Module('r.colors')
  365. >>> stdout, stderr = colors.popen.communicate(input="1 blue")
  366. >>> colors.popen.returncode
  367. 0
  368. >>> stdout
  369. >>> stderr.strip()
  370. "Color table for raster map <test_a> set to 'rules'"
  371. Multiple run test
  372. >>> colors = Module("r.colors", map="test_a",
  373. ... color="ryb", run_=False)
  374. >>> colors.get_bash()
  375. u'r.colors map=test_a color=ryb'
  376. >>> colors.run()
  377. Module('r.colors')
  378. >>> colors(color="gyr")
  379. Module('r.colors')
  380. >>> colors.run()
  381. Module('r.colors')
  382. >>> colors(color="ryg")
  383. Module('r.colors')
  384. >>> colors(stderr_=PIPE)
  385. Module('r.colors')
  386. >>> colors.run()
  387. Module('r.colors')
  388. >>> print(colors.outputs["stderr"].value.strip())
  389. Color table for raster map <test_a> set to 'ryg'
  390. >>> colors(color="byg")
  391. Module('r.colors')
  392. >>> colors(stdout_=PIPE)
  393. Module('r.colors')
  394. >>> colors.run()
  395. Module('r.colors')
  396. >>> print(colors.outputs["stderr"].value.strip())
  397. Color table for raster map <test_a> set to 'byg'
  398. Often in the Module class you can find ``*args`` and ``kwargs`` annotation
  399. in methods, like in the __call__ method.
  400. Python allow developers to not specify all the arguments and
  401. keyword arguments of a method or function. ::
  402. def f(*args):
  403. for arg in args:
  404. print arg
  405. therefore if we call the function like:
  406. >>> f('grass', 'gis', 'modules') # doctest: +SKIP
  407. grass
  408. gis
  409. modules
  410. or we can define a new list:
  411. >>> words = ['grass', 'gis', 'modules'] # doctest: +SKIP
  412. >>> f(*words) # doctest: +SKIP
  413. grass
  414. gis
  415. modules
  416. we can do the same with keyword arguments, rewrite the above function: ::
  417. def f(*args, **kargs):
  418. for arg in args:
  419. print arg
  420. for key, value in kargs.items():
  421. print "%s = %r" % (key, value)
  422. now we can use the new function, with:
  423. >>> f('grass', 'gis', 'modules', os = 'linux', language = 'python')
  424. ... # doctest: +SKIP
  425. grass
  426. gis
  427. modules
  428. os = 'linux'
  429. language = 'python'
  430. or, as before we can, define a dictionary and give the dictionary to
  431. the function, like:
  432. >>> keywords = {'os' : 'linux', 'language' : 'python'} # doctest: +SKIP
  433. >>> f(*words, **keywords) # doctest: +SKIP
  434. grass
  435. gis
  436. modules
  437. os = 'linux'
  438. language = 'python'
  439. In the Module class we heavily use this language feature to pass arguments
  440. and keyword arguments to the grass module.
  441. """
  442. def __init__(self, cmd, *args, **kargs):
  443. if isinstance(cmd, unicode):
  444. self.name = str(cmd)
  445. elif isinstance(cmd, str):
  446. self.name = cmd
  447. else:
  448. raise GrassError("Problem initializing the module {s}".format(s=cmd))
  449. try:
  450. # call the command with --interface-description
  451. get_cmd_xml = Popen([cmd, "--interface-description"], stdout=PIPE)
  452. except OSError as e:
  453. print("OSError error({0}): {1}".format(e.errno, e.strerror))
  454. str_err = "Error running: `%s --interface-description`."
  455. raise GrassError(str_err % self.name)
  456. # get the xml of the module
  457. self.xml = get_cmd_xml.communicate()[0]
  458. # transform and parse the xml into an Element class:
  459. # http://docs.python.org/library/xml.etree.elementtree.html
  460. tree = fromstring(self.xml)
  461. for e in tree:
  462. if e.tag not in ('parameter', 'flag'):
  463. self.__setattr__(e.tag, GETFROMTAG[e.tag](e))
  464. #
  465. # extract parameters from the xml
  466. #
  467. self.params_list = [Parameter(p) for p in tree.findall("parameter")]
  468. self.inputs = TypeDict(Parameter)
  469. self.outputs = TypeDict(Parameter)
  470. self.required = []
  471. # Insert parameters into input/output and required
  472. for par in self.params_list:
  473. if par.input:
  474. self.inputs[par.name] = par
  475. else:
  476. self.outputs[par.name] = par
  477. if par.required:
  478. self.required.append(par.name)
  479. #
  480. # extract flags from the xml
  481. #
  482. flags_list = [Flag(f) for f in tree.findall("flag")]
  483. self.flags = TypeDict(Flag)
  484. for flag in flags_list:
  485. self.flags[flag.name] = flag
  486. #
  487. # Add new attributes to the class
  488. #
  489. self.run_ = True
  490. self.finish_ = True
  491. self.check_ = True
  492. self.env_ = None
  493. self.stdin_ = None
  494. self.stdin = None
  495. self.stdout_ = None
  496. self.stderr_ = None
  497. diz = {'name': 'stdin', 'required': False,
  498. 'multiple': False, 'type': 'all',
  499. 'value': None}
  500. self.inputs['stdin'] = Parameter(diz=diz)
  501. diz['name'] = 'stdout'
  502. self.outputs['stdout'] = Parameter(diz=diz)
  503. diz['name'] = 'stderr'
  504. self.outputs['stderr'] = Parameter(diz=diz)
  505. self.popen = None
  506. self.time = None
  507. self.start_time = None # This variable will be set in the run() function
  508. self._finished = False # This variable is set True if wait() was successfully called
  509. if args or kargs:
  510. self.__call__(*args, **kargs)
  511. self.__call__.__func__.__doc__ = self.__doc__
  512. def __call__(self, *args, **kargs):
  513. """Set module parameters to the class and, if run_ is True execute the
  514. module, therefore valid parameters are all the module parameters
  515. plus some extra parameters that are: run_, stdin_, stdout_, stderr_,
  516. env_ and finish_.
  517. """
  518. if not args and not kargs:
  519. self.run()
  520. return self
  521. #
  522. # check for extra kargs, set attribute and remove from dictionary
  523. #
  524. if 'flags' in kargs:
  525. for flg in kargs['flags']:
  526. self.flags[flg].value = True
  527. del(kargs['flags'])
  528. # set attributs
  529. for key in ('run_', 'env_', 'finish_', 'stdout_', 'stderr_', 'check_'):
  530. if key in kargs:
  531. setattr(self, key, kargs.pop(key))
  532. # set inputs
  533. for key in ('stdin_', ):
  534. if key in kargs:
  535. self.inputs[key[:-1]].value = kargs.pop(key)
  536. #
  537. # set/update args
  538. #
  539. for param, arg in zip(self.params_list, args):
  540. param.value = arg
  541. for key, val in kargs.items():
  542. if key in self.inputs:
  543. self.inputs[key].value = val
  544. elif key in self.outputs:
  545. self.outputs[key].value = val
  546. elif key in self.flags:
  547. # we need to add this, because some parameters (overwrite,
  548. # verbose and quiet) work like parameters
  549. self.flags[key].value = val
  550. else:
  551. raise ParameterError('%s is not a valid parameter.' % key)
  552. #
  553. # check if execute
  554. #
  555. if self.run_:
  556. #
  557. # check reqire parameters
  558. #
  559. if self.check_:
  560. self.check()
  561. return self.run()
  562. return self
  563. def get_bash(self):
  564. """Return a BASH representation of the Module."""
  565. return ' '.join(self.make_cmd())
  566. def get_python(self):
  567. """Return a Python representation of the Module."""
  568. prefix = self.name.split('.')[0]
  569. name = '_'.join(self.name.split('.')[1:])
  570. params = ', '.join([par.get_python() for par in self.params_list
  571. if par.get_python() != ''])
  572. flags = ''.join([flg.get_python()
  573. for flg in self.flags.values()
  574. if not flg.special and flg.get_python() != ''])
  575. special = ', '.join([flg.get_python()
  576. for flg in self.flags.values()
  577. if flg.special and flg.get_python() != ''])
  578. # pre name par flg special
  579. if flags and special:
  580. return "%s.%s(%s, flags=%r, %s)" % (prefix, name, params,
  581. flags, special)
  582. elif flags:
  583. return "%s.%s(%s, flags=%r)" % (prefix, name, params, flags)
  584. elif special:
  585. return "%s.%s(%s, %s)" % (prefix, name, params, special)
  586. else:
  587. return "%s.%s(%s)" % (prefix, name, params)
  588. def __str__(self):
  589. """Return the command string that can be executed in a shell"""
  590. return ' '.join(self.make_cmd())
  591. def __repr__(self):
  592. return "Module(%r)" % self.name
  593. @docstring_property(__doc__)
  594. def __doc__(self):
  595. """{cmd_name}({cmd_params})
  596. """
  597. head = DOC['head'].format(cmd_name=self.name,
  598. cmd_params=('\n' + # go to a new line
  599. # give space under the function name
  600. (' ' * (len(self.name) + 1))).join([', '.join(
  601. # transform each parameter in string
  602. [str(param) for param in line if param is not None])
  603. # make a list of parameters with only 3 param per line
  604. for line in zip_longest(*[iter(self.params_list)] * 3)]),)
  605. params = '\n'.join([par.__doc__ for par in self.params_list])
  606. flags = self.flags.__doc__
  607. return '\n'.join([head, params, DOC['flag_head'], flags, DOC['foot']])
  608. def check(self):
  609. """Check the correctness of the provide parameters"""
  610. required = True
  611. for flg in self.flags.values():
  612. if flg and flg.suppress_required:
  613. required = False
  614. if required:
  615. for k in self.required:
  616. if ((k in self.inputs and self.inputs[k].value is None) or
  617. (k in self.outputs and self.outputs[k].value is None)):
  618. msg = "Required parameter <%s> not set."
  619. raise ParameterError(msg % k)
  620. def get_dict(self):
  621. """Return a dictionary that includes the name, all valid
  622. inputs, outputs and flags
  623. """
  624. dic = {}
  625. dic['name'] = self.name
  626. dic['inputs'] = [(k, v.value) for k, v in self.inputs.items()
  627. if v.value]
  628. dic['outputs'] = [(k, v.value) for k, v in self.outputs.items()
  629. if v.value]
  630. dic['flags'] = [flg for flg in self.flags if self.flags[flg].value]
  631. return dic
  632. def make_cmd(self):
  633. """Create the command string that can be executed in a shell
  634. :returns: the command string
  635. """
  636. skip = ['stdin', 'stdout', 'stderr']
  637. args = [self.name, ]
  638. for key in self.inputs:
  639. if key not in skip and self.inputs[key].value is not None and self.inputs[key].value != '':
  640. args.append(self.inputs[key].get_bash())
  641. for key in self.outputs:
  642. if key not in skip and self.outputs[key].value is not None and self.outputs[key].value != '':
  643. args.append(self.outputs[key].get_bash())
  644. for flg in self.flags:
  645. if self.flags[flg].value:
  646. args.append(str(self.flags[flg]))
  647. return args
  648. def run(self):
  649. """Run the module
  650. This function will wait for the process to terminate in case
  651. finish_==True and sets up stdout and stderr. If finish_==False this
  652. function will return after starting the process. Use wait() to wait for
  653. the started process
  654. :return: A reference to this object
  655. """
  656. G_debug(1, self.get_bash())
  657. self._finished = False
  658. if self.inputs['stdin'].value:
  659. self.stdin = self.inputs['stdin'].value
  660. self.stdin_ = PIPE
  661. cmd = self.make_cmd()
  662. self.start_time = time.time()
  663. self.popen = Popen(cmd,
  664. stdin=self.stdin_,
  665. stdout=self.stdout_,
  666. stderr=self.stderr_,
  667. env=self.env_)
  668. if self.finish_ is True:
  669. self.wait()
  670. return self
  671. def wait(self):
  672. """Wait for the module to finish. Call this method if
  673. the run() call was performed with self.false_ = False.
  674. :return: A reference to this object
  675. """
  676. if self._finished is False:
  677. stdout, stderr = self.popen.communicate(input=self.stdin)
  678. self.outputs['stdout'].value = stdout if stdout else ''
  679. self.outputs['stderr'].value = stderr if stderr else ''
  680. self.time = time.time() - self.start_time
  681. self._finished = True
  682. if self.popen.poll():
  683. raise CalledModuleError(returncode=self.popen.returncode,
  684. code=self.get_bash(),
  685. module=self.name, errors=stderr)
  686. return self
  687. class MultiModule(object):
  688. """This class is designed to run a list of modules in serial in the provided order
  689. within a temporary region environment.
  690. Module can be run in serial synchronously or asynchronously.
  691. - Synchronously: When calling run() all modules will run in serial order
  692. until they are finished, The run() method will return until all modules finished.
  693. The modules objects can be accessed by calling get_modules() to check their return
  694. values.
  695. - Asynchronously: When calling run() all modules will run in serial order in a background process.
  696. Method run() will return after starting the modules without waiting for them to finish.
  697. The user must call the wait() method to wait for the modules to finish.
  698. Asynchronously called module can be optionally run in a temporary region
  699. environment, hence invokeing g.region will not alter the current
  700. region or the region of other MultiModule runs.
  701. Note:
  702. Modules run in asynchronous mode can only be accessed via the wait() method.
  703. The wait() method will return all finished module objects as list.
  704. Objects of this class can be passed to the ParallelModuleQueue to run serial stacks
  705. of modules in parallel. This is meaningful if region settings must be applied
  706. to each parallel module run.
  707. >>> from grass.pygrass.modules import Module
  708. >>> from grass.pygrass.modules import MultiModule
  709. >>> from multiprocessing import Process
  710. >>> import copy
  711. Synchronous module run
  712. >>> region_1 = Module("g.region", run_=False)
  713. >>> region_1.flags.p = True
  714. >>> region_2 = copy.deepcopy(region_1)
  715. >>> region_2.flags.p = True
  716. >>> mm = MultiModule(module_list=[region_1, region_2])
  717. >>> mm.run()
  718. >>> m_list = mm.get_modules()
  719. >>> m_list[0].popen.returncode
  720. 0
  721. >>> m_list[1].popen.returncode
  722. 0
  723. Asynchronous module run, setting finish = False
  724. >>> region_1 = Module("g.region", run_=False)
  725. >>> region_1.flags.p = True
  726. >>> region_2 = copy.deepcopy(region_1)
  727. >>> region_2.flags.p = True
  728. >>> region_3 = copy.deepcopy(region_1)
  729. >>> region_3.flags.p = True
  730. >>> region_4 = copy.deepcopy(region_1)
  731. >>> region_4.flags.p = True
  732. >>> region_5 = copy.deepcopy(region_1)
  733. >>> region_5.flags.p = True
  734. >>> mm = MultiModule(module_list=[region_1, region_2, region_3, region_4, region_5],
  735. ... sync=False)
  736. >>> t = mm.run()
  737. >>> isinstance(t, Process)
  738. True
  739. >>> m_list = mm.wait()
  740. >>> m_list[0].popen.returncode
  741. 0
  742. >>> m_list[1].popen.returncode
  743. 0
  744. >>> m_list[2].popen.returncode
  745. 0
  746. >>> m_list[3].popen.returncode
  747. 0
  748. >>> m_list[4].popen.returncode
  749. 0
  750. Asynchronous module run, setting finish = False and using temporary region
  751. >>> mm = MultiModule(module_list=[region_1, region_2, region_3, region_4, region_5],
  752. ... sync=False, set_temp_region=True)
  753. >>> str(mm)
  754. 'g.region -p ; g.region -p ; g.region -p ; g.region -p ; g.region -p'
  755. >>> t = mm.run()
  756. >>> isinstance(t, Process)
  757. True
  758. >>> m_list = mm.wait()
  759. >>> m_list[0].popen.returncode
  760. 0
  761. >>> m_list[1].popen.returncode
  762. 0
  763. >>> m_list[2].popen.returncode
  764. 0
  765. >>> m_list[3].popen.returncode
  766. 0
  767. >>> m_list[4].popen.returncode
  768. 0
  769. """
  770. def __init__(self, module_list, sync=True, set_temp_region=False):
  771. """Constructor of the multi module class
  772. :param module_list: A list of pre-configured Module objects that should be run
  773. :param sync: If set True the run() method will wait for all processes to finish -> synchronously run.
  774. If set False, the run() method will return after starting the processes -> asynchronously run.
  775. The wait() method must be called to finish the modules.
  776. :param set_temp_region: Set a temporary region in which the modules should be run, hence
  777. region settings in the process list will not affect the current
  778. computation region.
  779. Note:
  780. This flag is only available in asynchronous mode!
  781. :return:
  782. """
  783. self.module_list = module_list
  784. self.set_temp_region = set_temp_region
  785. self.finish_ = sync # We use the same variable name a Module
  786. self.p = None
  787. self.q = Queue()
  788. def __str__(self):
  789. """Return the command string that can be executed in a shell"""
  790. return ' ; '.join(str(string) for string in self.module_list)
  791. def get_modules(self):
  792. """Return the list of modules that have been run in synchronous mode
  793. Note: Asynchronously run module can only be accessed via the wait() method.
  794. :return: The list of modules
  795. """
  796. return self.module_list
  797. def run(self):
  798. """Start the modules in the list. If self.finished_ is set True
  799. this method will return after all processes finished.
  800. If self.finish_ is set False, this method will return
  801. after the process list was started for execution.
  802. In a background process, the processes in the list will
  803. be run one after the another.
  804. :return: None in case of self.finish_ is True,
  805. otherwise a multiprocessing.Process object that invokes the modules
  806. """
  807. if self.finish_ is True:
  808. for module in self.module_list:
  809. module.finish_ = True
  810. module.run()
  811. return None
  812. else:
  813. if self.set_temp_region is True:
  814. self.p = Process(target=run_modules_in_temp_region,
  815. args=[self.module_list, self.q])
  816. else:
  817. self.p = Process(target=run_modules,
  818. args=[self.module_list, self.q])
  819. self.p.start()
  820. return self.p
  821. def wait(self):
  822. """Wait for all processes to finish. Call this method
  823. in asynchronous mode, hence if finished was set False.
  824. :return: The process list with finished processes to check their return states
  825. """
  826. if self.p:
  827. proc_list = self.q.get()
  828. self.p.join()
  829. return proc_list
  830. def run_modules_in_temp_region(module_list, q):
  831. """Run the modules in a temporary region environment
  832. This function is the argument for multiprocessing.Process class
  833. in the MultiModule asynchronous execution.
  834. :param module_list: The list of modules to run in serial
  835. :param q: The process queue to put the finished process list
  836. """
  837. use_temp_region()
  838. try:
  839. for proc in module_list:
  840. proc.run()
  841. proc.wait()
  842. except:
  843. raise
  844. finally:
  845. q.put(module_list)
  846. del_temp_region()
  847. def run_modules(module_list, q):
  848. """Run the modules
  849. This function is the argument for multiprocessing.Process class
  850. in the MultiModule asynchronous execution.
  851. :param module_list: The list of modules to run in serial
  852. :param q: The process queue to put the finished process list
  853. """
  854. try:
  855. for proc in module_list:
  856. proc.run()
  857. proc.wait()
  858. except:
  859. raise
  860. finally:
  861. q.put(module_list)
  862. ###############################################################################
  863. if __name__ == "__main__":
  864. import doctest
  865. doctest.testmod()