module.py 34 KB

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