module.py 34 KB

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