grid.py 24 KB

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