module.py 34 KB

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