module.py 34 KB

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