grid.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  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 os
  11. import sys
  12. import multiprocessing as mltp
  13. import subprocess as sub
  14. import shutil as sht
  15. from grass.script.setup import write_gisrc
  16. from grass.pygrass.gis import Mapset, Location
  17. from grass.pygrass.gis.region import Region
  18. from grass.pygrass.modules import Module
  19. from grass.pygrass.utils import get_mapset_raster, findmaps
  20. from grass.pygrass.modules.grid.split import split_region_tiles
  21. from grass.pygrass.modules.grid.patch import rpatch_map
  22. def select(parms, ptype):
  23. """Select only a certain type of parameters.
  24. :param parms: a DictType parameter with inputs or outputs of a Module class
  25. :type parms: DictType parameters
  26. :param ptype: String define the type of parameter that we want to select,
  27. valid ptype are: 'raster', 'vector', 'group'
  28. :type ptype: str
  29. :returns: An iterator with the value of the parameter.
  30. >>> slp = Module('r.slope.aspect',
  31. ... elevation='ele', slope='slp', aspect='asp',
  32. ... run_=False)
  33. >>> for rast in select(slp.outputs, 'raster'):
  34. ... print(rast)
  35. ...
  36. slp
  37. asp
  38. """
  39. for k in parms:
  40. par = parms[k]
  41. if par.type == ptype or par.typedesc == ptype and par.value:
  42. if par.multiple:
  43. for val in par.value:
  44. yield val
  45. else:
  46. yield par.value
  47. def copy_special_mapset_files(path_src, path_dst):
  48. """Copy all the special GRASS files that are contained in
  49. a mapset to another mapset
  50. :param path_src: the path to the original mapset
  51. :type path_src: str
  52. :param path_dst: the path to the new mapset
  53. :type path_dst: str
  54. """
  55. for fil in (fi for fi in os.listdir(path_src) if fi.isupper()):
  56. sht.copy(os.path.join(path_src, fil), path_dst)
  57. def copy_mapset(mapset, path):
  58. """Copy mapset to another place without copying raster and vector data.
  59. :param mapset: a Mapset instance to copy
  60. :type mapset: Mapset object
  61. :param path: path where the new mapset must be copied
  62. :type path: str
  63. :returns: the instance of the new Mapset.
  64. >>> from grass.script.core import gisenv
  65. >>> mname = gisenv()['MAPSET']
  66. >>> mset = Mapset()
  67. >>> mset.name == mname
  68. True
  69. >>> import tempfile as tmp
  70. >>> import os
  71. >>> path = os.path.join(tmp.gettempdir(), 'my_loc', 'my_mset')
  72. >>> copy_mapset(mset, path) # doctest: +ELLIPSIS
  73. Mapset(...)
  74. >>> sorted(os.listdir(path)) # doctest: +ELLIPSIS
  75. [...'PERMANENT'...]
  76. >>> sorted(os.listdir(os.path.join(path, 'PERMANENT')))
  77. ['DEFAULT_WIND', 'PROJ_INFO', 'PROJ_UNITS', 'VAR', 'WIND']
  78. >>> sorted(os.listdir(os.path.join(path, mname))) # doctest: +ELLIPSIS
  79. [...'SEARCH_PATH',...'WIND']
  80. >>> import shutil
  81. >>> shutil.rmtree(path)
  82. """
  83. per_old = os.path.join(mapset.gisdbase, mapset.location, "PERMANENT")
  84. per_new = os.path.join(path, "PERMANENT")
  85. map_old = mapset.path()
  86. map_new = os.path.join(path, mapset.name)
  87. if not os.path.isdir(per_new):
  88. os.makedirs(per_new)
  89. if not os.path.isdir(map_new):
  90. os.mkdir(map_new)
  91. copy_special_mapset_files(per_old, per_new)
  92. copy_special_mapset_files(map_old, map_new)
  93. gisdbase, location = os.path.split(path)
  94. return Mapset(mapset.name, location, gisdbase)
  95. def read_gisrc(gisrc):
  96. """Read a GISRC file and return a tuple with the mapset, location
  97. and gisdbase.
  98. :param gisrc: the path to GISRC file
  99. :type gisrc: str
  100. :returns: a tuple with the mapset, location and gisdbase
  101. >>> import os
  102. >>> from grass.script.core import gisenv
  103. >>> genv = gisenv()
  104. >>> (read_gisrc(os.environ['GISRC']) == (genv['MAPSET'],
  105. ... genv['LOCATION_NAME'],
  106. ... genv['GISDBASE']))
  107. True
  108. """
  109. with open(gisrc, "r") as gfile:
  110. gis = dict(
  111. [(k.strip(), v.strip()) for k, v in [row.split(":", 1) for row in gfile]]
  112. )
  113. return gis["MAPSET"], gis["LOCATION_NAME"], gis["GISDBASE"]
  114. def get_mapset(gisrc_src, gisrc_dst):
  115. """Get mapset from a GISRC source to a GISRC destination.
  116. :param gisrc_src: path to the GISRC source
  117. :type gisrc_src: str
  118. :param gisrc_dst: path to the GISRC destination
  119. :type gisrc_dst: str
  120. :returns: a tuple with Mapset(src), Mapset(dst)
  121. """
  122. msrc, lsrc, gsrc = read_gisrc(gisrc_src)
  123. mdst, ldst, gdst = read_gisrc(gisrc_dst)
  124. path_src = os.path.join(gsrc, lsrc, msrc)
  125. path_dst = os.path.join(gdst, ldst, mdst)
  126. if not os.path.isdir(path_dst):
  127. os.makedirs(path_dst)
  128. copy_special_mapset_files(path_src, path_dst)
  129. src = Mapset(msrc, lsrc, gsrc)
  130. dst = Mapset(mdst, ldst, gdst)
  131. visible = [m for m in src.visible]
  132. if src.name not in visible:
  133. visible.append(src.name)
  134. dst.visible.extend(visible)
  135. return src, dst
  136. def copy_groups(groups, gisrc_src, gisrc_dst, region=None):
  137. """Copy group from one mapset to another, crop the raster to the region
  138. :param groups: a list of strings with the group that must be copied
  139. from a master to another.
  140. :type groups: list of strings
  141. :param gisrc_src: path of the GISRC file from where we want to copy the groups
  142. :type gisrc_src: str
  143. :param gisrc_dst: path of the GISRC file where the groups will be created
  144. :type gisrc_dst: str
  145. :param region: a region like object or a dictionary with the region
  146. parameters that will be used to crop the rasters of the
  147. groups
  148. :type region: Region object or dictionary
  149. :returns: None
  150. """
  151. def rmloc(r):
  152. return r.split("@")[0] if "@" in r else r
  153. env = os.environ.copy()
  154. # instantiate modules
  155. get_grp = Module("i.group", flags="lg", stdout_=sub.PIPE, run_=False)
  156. set_grp = Module("i.group")
  157. get_grp.run_ = True
  158. src = read_gisrc(gisrc_src)
  159. dst = read_gisrc(gisrc_dst)
  160. rm = True if src[2] != dst[2] else False
  161. all_rasts = [r[0] for r in findmaps("raster", location=dst[1], gisdbase=dst[2])]
  162. for grp in groups:
  163. # change gisdbase to src
  164. env["GISRC"] = gisrc_src
  165. get_grp(group=grp, env_=env)
  166. rasts = [r for r in get_grp.outputs.stdout.split()]
  167. # change gisdbase to dst
  168. env["GISRC"] = gisrc_dst
  169. rast2cp = [r for r in rasts if rmloc(r) not in all_rasts]
  170. if rast2cp:
  171. copy_rasters(rast2cp, gisrc_src, gisrc_dst, region=region)
  172. set_grp(
  173. group=grp,
  174. input=[rmloc(r) for r in rasts] if rast2cp or rm else rasts,
  175. env_=env,
  176. )
  177. def set_region(region, gisrc_src, gisrc_dst, env):
  178. """Set a region into two different mapsets.
  179. :param region: a region like object or a dictionary with the region
  180. parameters that will be used to crop the rasters of the
  181. groups
  182. :type region: Region object or dictionary
  183. :param gisrc_src: path of the GISRC file from where we want to copy the groups
  184. :type gisrc_src: str
  185. :param gisrc_dst: path of the GISRC file where the groups will be created
  186. :type gisrc_dst: str
  187. :param env:
  188. :type env:
  189. :returns: None
  190. """
  191. reg_str = (
  192. "g.region n=%(north)r s=%(south)r "
  193. "e=%(east)r w=%(west)r "
  194. "nsres=%(nsres)r ewres=%(ewres)r"
  195. )
  196. reg_cmd = reg_str % dict(region.items())
  197. env["GISRC"] = gisrc_src
  198. sub.Popen(reg_cmd, shell=True, env=env)
  199. env["GISRC"] = gisrc_dst
  200. sub.Popen(reg_cmd, shell=True, env=env)
  201. def copy_rasters(rasters, gisrc_src, gisrc_dst, region=None):
  202. """Copy rasters from one mapset to another, crop the raster to the region.
  203. :param rasters: a list of strings with the raster map that must be copied
  204. from a master to another.
  205. :type rasters: list
  206. :param gisrc_src: path of the GISRC file from where we want to copy the groups
  207. :type gisrc_src: str
  208. :param gisrc_dst: path of the GISRC file where the groups will be created
  209. :type gisrc_dst: str
  210. :param region: a region like object or a dictionary with the region
  211. parameters that will be used to crop the rasters of the
  212. groups
  213. :type region: Region object or dictionary
  214. :returns: None
  215. """
  216. env = os.environ.copy()
  217. if region:
  218. set_region(region, gisrc_src, gisrc_dst, env)
  219. path_dst = os.path.join(*read_gisrc(gisrc_dst)[::-1])
  220. nam = "copy%d__%s" % (id(gisrc_dst), "%s")
  221. # instantiate modules
  222. mpclc = Module("r.mapcalc")
  223. rpck = Module("r.pack")
  224. rupck = Module("r.unpack")
  225. remove = Module("g.remove")
  226. for rast in rasters:
  227. rast_clean = rast.split("@")[0] if "@" in rast else rast
  228. # change gisdbase to src
  229. env["GISRC"] = gisrc_src
  230. name = nam % rast_clean
  231. mpclc(expression="%s=%s" % (name, rast), overwrite=True, env_=env)
  232. file_dst = "%s.pack" % os.path.join(path_dst, name)
  233. rpck(input=name, output=file_dst, overwrite=True, env_=env)
  234. remove(flags="f", type="raster", name=name, env_=env)
  235. # change gisdbase to dst
  236. env["GISRC"] = gisrc_dst
  237. rupck(input=file_dst, output=rast_clean, overwrite=True, env_=env)
  238. os.remove(file_dst)
  239. def copy_vectors(vectors, gisrc_src, gisrc_dst):
  240. """Copy vectors from one mapset to another, crop the raster to the region.
  241. :param vectors: a list of strings with the vector map that must be copied
  242. from a master to another.
  243. :type vectors: list
  244. :param gisrc_src: path of the GISRC file from where we want to copy the groups
  245. :type gisrc_src: str
  246. :param gisrc_dst: path of the GISRC file where the groups will be created
  247. :type gisrc_dst: str
  248. :returns: None
  249. """
  250. env = os.environ.copy()
  251. path_dst = os.path.join(*read_gisrc(gisrc_dst))
  252. nam = "copy%d__%s" % (id(gisrc_dst), "%s")
  253. # instantiate modules
  254. vpck = Module("v.pack")
  255. vupck = Module("v.unpack")
  256. remove = Module("g.remove")
  257. for vect in vectors:
  258. # change gisdbase to src
  259. env["GISRC"] = gisrc_src
  260. name = nam % vect
  261. file_dst = "%s.pack" % os.path.join(path_dst, name)
  262. vpck(input=name, output=file_dst, overwrite=True, env_=env)
  263. remove(flags="f", type="vector", name=name, env_=env)
  264. # change gisdbase to dst
  265. env["GISRC"] = gisrc_dst
  266. vupck(input=file_dst, output=vect, overwrite=True, env_=env)
  267. os.remove(file_dst)
  268. def get_cmd(cmdd):
  269. """Transform a cmd dictionary to a list of parameters. It is useful to
  270. pickle a Module class and cnvert into a string that can be used with
  271. `Popen(get_cmd(cmdd), shell=True)`.
  272. :param cmdd: a module dictionary with all the parameters
  273. :type cmdd: dict
  274. >>> slp = Module('r.slope.aspect',
  275. ... elevation='ele', slope='slp', aspect='asp',
  276. ... overwrite=True, run_=False)
  277. >>> get_cmd(slp.get_dict()) # doctest: +ELLIPSIS
  278. ['r.slope.aspect', 'elevation=ele', 'format=degrees', ..., '--o']
  279. """
  280. cmd = [
  281. cmdd["name"],
  282. ]
  283. cmd.extend(("%s=%s" % (k, v) for k, v in cmdd["inputs"] if not isinstance(v, list)))
  284. cmd.extend(
  285. (
  286. "%s=%s"
  287. % (
  288. k,
  289. ",".join(vals if isinstance(vals[0], str) else [repr(v) for v in vals]),
  290. )
  291. for k, vals in cmdd["inputs"]
  292. if isinstance(vals, list)
  293. )
  294. )
  295. cmd.extend(
  296. ("%s=%s" % (k, v) for k, v in cmdd["outputs"] if not isinstance(v, list))
  297. )
  298. cmd.extend(
  299. (
  300. "%s=%s" % (k, ",".join([repr(v) for v in vals]))
  301. for k, vals in cmdd["outputs"]
  302. if isinstance(vals, list)
  303. )
  304. )
  305. cmd.extend(("-%s" % (flg) for flg in cmdd["flags"] if len(flg) == 1))
  306. cmd.extend(("--%s" % (flg[0]) for flg in cmdd["flags"] if len(flg) > 1))
  307. return cmd
  308. def cmd_exe(args):
  309. """Create a mapset, and execute a cmd inside.
  310. :param args: is a tuple that contains several information see below
  311. :type args: tuple
  312. :returns: None
  313. The puple has to contain:
  314. - bbox (dict): a dict with the region parameters (n, s, e, w, etc.)
  315. that we want to set before to apply the command.
  316. - mapnames (dict): a dictionary to substitute the input if the domain has
  317. been split in several tiles.
  318. - gisrc_src (str): path of the GISRC file from where we want to copy the
  319. groups.
  320. - gisrc_dst (str): path of the GISRC file where the groups will be created.
  321. - cmd (dict): a dictionary with all the parameter of a GRASS module.
  322. - groups (list): a list of strings with the groups that we want to copy in
  323. the mapset.
  324. """
  325. bbox, mapnames, gisrc_src, gisrc_dst, cmd, groups = args
  326. src, dst = get_mapset(gisrc_src, gisrc_dst)
  327. env = os.environ.copy()
  328. env["GISRC"] = gisrc_dst
  329. shell = True if sys.platform == "win32" else False
  330. if mapnames:
  331. inputs = dict(cmd["inputs"])
  332. # reset the inputs to
  333. for key in mapnames:
  334. inputs[key] = mapnames[key]
  335. cmd["inputs"] = inputs.items()
  336. # set the region to the tile
  337. sub.Popen(["g.region", "raster=%s" % key], shell=shell, env=env).wait()
  338. else:
  339. # set the computational region
  340. lcmd = [
  341. "g.region",
  342. ]
  343. lcmd.extend(["%s=%s" % (k, v) for k, v in bbox.items()])
  344. sub.Popen(lcmd, shell=shell, env=env).wait()
  345. if groups:
  346. copy_groups(groups, gisrc_src, gisrc_dst)
  347. # run the grass command
  348. sub.Popen(get_cmd(cmd), shell=shell, env=env).wait()
  349. # remove temp GISRC
  350. os.remove(gisrc_dst)
  351. class GridModule(object):
  352. # TODO maybe also i.* could be supported easily
  353. """Run GRASS raster commands in a multiprocessing mode.
  354. :param cmd: raster GRASS command, only command staring with r.* are valid.
  355. :type cmd: str
  356. :param width: width of the tile, in pixel
  357. :type width: int
  358. :param height: height of the tile, in pixel.
  359. :type height: int
  360. :param overlap: overlap between tiles, in pixel.
  361. :type overlap: int
  362. :param processes: number of threads, default value is equal to the number
  363. of processor available.
  364. :param split: if True use r.tile to split all the inputs.
  365. :type split: bool
  366. :param mapset_prefix: if specified created mapsets start with this prefix
  367. :type mapset_prefix: str
  368. :param run_: if False only instantiate the object
  369. :type run_: bool
  370. :param args: give all the parameters to the command
  371. :param kargs: give all the parameters to the command
  372. >>> grd = GridModule('r.slope.aspect',
  373. ... width=500, height=500, overlap=2,
  374. ... processes=None, split=False,
  375. ... elevation='elevation',
  376. ... slope='slope', aspect='aspect', overwrite=True)
  377. >>> grd.run()
  378. """
  379. def __init__(
  380. self,
  381. cmd,
  382. width=None,
  383. height=None,
  384. overlap=0,
  385. processes=None,
  386. split=False,
  387. debug=False,
  388. region=None,
  389. move=None,
  390. log=False,
  391. start_row=0,
  392. start_col=0,
  393. out_prefix="",
  394. mapset_prefix=None,
  395. *args,
  396. **kargs,
  397. ):
  398. kargs["run_"] = False
  399. self.mset = Mapset()
  400. self.module = Module(cmd, *args, **kargs)
  401. self.width = width
  402. self.height = height
  403. self.overlap = overlap
  404. self.processes = processes
  405. self.region = region if region else Region()
  406. self.start_row = start_row
  407. self.start_col = start_col
  408. self.out_prefix = out_prefix
  409. self.log = log
  410. self.move = move
  411. self.gisrc_src = os.environ["GISRC"]
  412. self.n_mset, self.gisrc_dst = None, None
  413. if self.move:
  414. self.n_mset = copy_mapset(self.mset, self.move)
  415. self.gisrc_dst = write_gisrc(
  416. self.n_mset.gisdbase, self.n_mset.location, self.n_mset.name
  417. )
  418. rasters = [r for r in select(self.module.inputs, "raster")]
  419. if rasters:
  420. copy_rasters(
  421. rasters, self.gisrc_src, self.gisrc_dst, region=self.region
  422. )
  423. vectors = [v for v in select(self.module.inputs, "vector")]
  424. if vectors:
  425. copy_vectors(vectors, self.gisrc_src, self.gisrc_dst)
  426. groups = [g for g in select(self.module.inputs, "group")]
  427. if groups:
  428. copy_groups(groups, self.gisrc_src, self.gisrc_dst, region=self.region)
  429. self.bboxes = split_region_tiles(
  430. region=region, width=width, height=height, overlap=overlap
  431. )
  432. if mapset_prefix:
  433. self.msetstr = mapset_prefix + "_%03d_%03d"
  434. else:
  435. self.msetstr = cmd.replace(".", "") + "_%03d_%03d"
  436. self.inlist = None
  437. if split:
  438. self.split()
  439. self.debug = debug
  440. def __del__(self):
  441. if self.gisrc_dst:
  442. # remove GISRC file
  443. os.remove(self.gisrc_dst)
  444. def clean_location(self, location=None):
  445. """Remove all created mapsets.
  446. :param location: a Location instance where we are running the analysis
  447. :type location: Location object
  448. """
  449. if location is None:
  450. if self.n_mset:
  451. self.n_mset.current()
  452. location = Location()
  453. mapsets = location.mapsets(self.msetstr.split("_")[0] + "_*")
  454. for mset in mapsets:
  455. Mapset(mset).delete()
  456. if self.n_mset and self.n_mset.is_current():
  457. self.mset.current()
  458. def split(self):
  459. """Split all the raster inputs using r.tile"""
  460. rtile = Module("r.tile")
  461. inlist = {}
  462. for inm in select(self.module.inputs, "raster"):
  463. rtile(
  464. input=inm.value,
  465. output=inm.value,
  466. width=self.width,
  467. height=self.height,
  468. overlap=self.overlap,
  469. )
  470. patt = "%s-*" % inm.value
  471. inlist[inm.value] = sorted(self.mset.glist(type="raster", pattern=patt))
  472. self.inlist = inlist
  473. def get_works(self):
  474. """Return a list of tuble with the parameters for cmd_exe function"""
  475. works = []
  476. reg = Region()
  477. if self.move:
  478. mdst, ldst, gdst = read_gisrc(self.gisrc_dst)
  479. else:
  480. ldst, gdst = self.mset.location, self.mset.gisdbase
  481. cmd = self.module.get_dict()
  482. groups = [g for g in select(self.module.inputs, "group")]
  483. for row, box_row in enumerate(self.bboxes):
  484. for col, box in enumerate(box_row):
  485. inms = None
  486. if self.inlist:
  487. inms = {}
  488. cols = len(box_row)
  489. for key in self.inlist:
  490. indx = row * cols + col
  491. inms[key] = "%s@%s" % (self.inlist[key][indx], self.mset.name)
  492. # set the computational region, prepare the region parameters
  493. bbox = dict([(k[0], str(v)) for k, v in box.items()[:-2]])
  494. bbox["nsres"] = "%f" % reg.nsres
  495. bbox["ewres"] = "%f" % reg.ewres
  496. new_mset = (
  497. self.msetstr % (self.start_row + row, self.start_col + col),
  498. )
  499. works.append(
  500. (
  501. bbox,
  502. inms,
  503. self.gisrc_src,
  504. write_gisrc(gdst, ldst, new_mset),
  505. cmd,
  506. groups,
  507. )
  508. )
  509. return works
  510. def define_mapset_inputs(self):
  511. """Add the mapset information to the input maps"""
  512. for inmap in self.module.inputs:
  513. inm = self.module.inputs[inmap]
  514. if inm.type in ("raster", "vector") and inm.value:
  515. if "@" not in inm.value:
  516. mset = get_mapset_raster(inm.value)
  517. inm.value = inm.value + "@%s" % mset
  518. def run(self, patch=True, clean=True):
  519. """Run the GRASS command
  520. :param patch: set False if you does not want to patch the results
  521. :type patch: bool
  522. :param clean: set False if you does not want to remove all the stuff
  523. created by GridModule
  524. :type clean: bool
  525. """
  526. self.module.flags.overwrite = True
  527. self.define_mapset_inputs()
  528. if self.debug:
  529. for wrk in self.get_works():
  530. cmd_exe(wrk)
  531. else:
  532. pool = mltp.Pool(processes=self.processes)
  533. result = pool.map_async(cmd_exe, self.get_works())
  534. result.wait()
  535. pool.close()
  536. pool.join()
  537. if not result.successful():
  538. raise RuntimeError(_("Execution of subprocesses was not successful"))
  539. if patch:
  540. if self.move:
  541. os.environ["GISRC"] = self.gisrc_dst
  542. self.n_mset.current()
  543. self.patch()
  544. os.environ["GISRC"] = self.gisrc_src
  545. self.mset.current()
  546. # copy the outputs from dst => src
  547. routputs = [
  548. self.out_prefix + o for o in select(self.module.outputs, "raster")
  549. ]
  550. copy_rasters(routputs, self.gisrc_dst, self.gisrc_src)
  551. else:
  552. self.patch()
  553. if self.log:
  554. # record in the temp directory
  555. from grass.lib.gis import G_tempfile
  556. tmp, dummy = os.path.split(G_tempfile())
  557. tmpdir = os.path.join(tmp, self.module.name)
  558. for k in self.module.outputs:
  559. par = self.module.outputs[k]
  560. if par.typedesc == "raster" and par.value:
  561. dirpath = os.path.join(tmpdir, par.name)
  562. if not os.path.isdir(dirpath):
  563. os.makedirs(dirpath)
  564. fil = open(os.path.join(dirpath, self.out_prefix + par.value), "w+")
  565. fil.close()
  566. if clean:
  567. self.clean_location()
  568. self.rm_tiles()
  569. if self.n_mset:
  570. gisdbase, location = os.path.split(self.move)
  571. self.clean_location(Location(location, gisdbase))
  572. # rm temporary gis_rc
  573. os.remove(self.gisrc_dst)
  574. self.gisrc_dst = None
  575. sht.rmtree(os.path.join(self.move, "PERMANENT"))
  576. sht.rmtree(os.path.join(self.move, self.mset.name))
  577. def patch(self):
  578. """Patch the final results."""
  579. bboxes = split_region_tiles(width=self.width, height=self.height)
  580. loc = Location()
  581. mset = loc[self.mset.name]
  582. mset.visible.extend(loc.mapsets())
  583. noutputs = 0
  584. for otmap in self.module.outputs:
  585. otm = self.module.outputs[otmap]
  586. if otm.typedesc == "raster" and otm.value:
  587. rpatch_map(
  588. otm.value,
  589. self.mset.name,
  590. self.msetstr,
  591. bboxes,
  592. self.module.flags.overwrite,
  593. self.start_row,
  594. self.start_col,
  595. self.out_prefix,
  596. )
  597. noutputs += 1
  598. if noutputs < 1:
  599. msg = "No raster output option defined for <{}>".format(self.module.name)
  600. if self.module.name == "r.mapcalc":
  601. msg += ". Use <{}.simple> instead".format(self.module.name)
  602. raise RuntimeError(msg)
  603. def rm_tiles(self):
  604. """Remove all the tiles."""
  605. # if split, remove tiles
  606. if self.inlist:
  607. grm = Module("g.remove")
  608. for key in self.inlist:
  609. grm(flags="f", type="raster", name=self.inlist[key])