grid.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  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. [u'DEFAULT_WIND', u'PROJ_EPSG', u'PROJ_INFO', u'PROJ_UNITS', u'VAR', u'WIND']
  72. >>> sorted(os.listdir(os.path.join(path, mname))) # doctest: +ELLIPSIS
  73. [...u'SEARCH_PATH',...u'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. visible.append(src.name)
  126. dst.visible.extend(visible)
  127. return src, dst
  128. def copy_groups(groups, gisrc_src, gisrc_dst, region=None):
  129. """Copy group from one mapset to another, crop the raster to the region
  130. :param groups: a list of strings with the group that must be copied
  131. from a master to another.
  132. :type groups: list of strings
  133. :param gisrc_src: path of the GISRC file from where we want to copy the groups
  134. :type gisrc_src: str
  135. :param gisrc_dst: path of the GISRC file where the groups will be created
  136. :type gisrc_dst: str
  137. :param region: a region like object or a dictionary with the region
  138. parameters that will be used to crop the rasters of the
  139. groups
  140. :type region: Region object or dictionary
  141. :returns: None
  142. """
  143. env = os.environ.copy()
  144. # instantiate modules
  145. get_grp = Module('i.group', flags='lg', stdout_=sub.PIPE, run_=False)
  146. set_grp = Module('i.group')
  147. get_grp.run_ = True
  148. rmloc = lambda r: r.split('@')[0] if '@' in r else r
  149. src = read_gisrc(gisrc_src)
  150. dst = read_gisrc(gisrc_dst)
  151. rm = True if src[2] != dst[2] else False
  152. all_rasts = [r[0]
  153. for r in findmaps('raster', location=dst[1], gisdbase=dst[2])]
  154. for grp in groups:
  155. # change gisdbase to src
  156. env['GISRC'] = gisrc_src
  157. get_grp(group=grp, env_=env)
  158. rasts = [r for r in get_grp.outputs.stdout.split()]
  159. # change gisdbase to dst
  160. env['GISRC'] = gisrc_dst
  161. rast2cp = [r for r in rasts if rmloc(r) not in all_rasts]
  162. if rast2cp:
  163. copy_rasters(rast2cp, gisrc_src, gisrc_dst, region=region)
  164. set_grp(group=grp,
  165. input=[rmloc(r) for r in rasts] if rast2cp or rm else rasts,
  166. env_=env)
  167. def set_region(region, gisrc_src, gisrc_dst, env):
  168. """Set a region into two different mapsets.
  169. :param region: a region like object or a dictionary with the region
  170. parameters that will be used to crop the rasters of the
  171. groups
  172. :type region: Region object or dictionary
  173. :param gisrc_src: path of the GISRC file from where we want to copy the groups
  174. :type gisrc_src: str
  175. :param gisrc_dst: path of the GISRC file where the groups will be created
  176. :type gisrc_dst: str
  177. :param env:
  178. :type env:
  179. :returns: None
  180. """
  181. reg_str = "g.region n=%(north)r s=%(south)r " \
  182. "e=%(east)r w=%(west)r " \
  183. "nsres=%(nsres)r ewres=%(ewres)r"
  184. reg_cmd = reg_str % dict(region.items())
  185. env['GISRC'] = gisrc_src
  186. sub.Popen(reg_cmd, shell=True, env=env)
  187. env['GISRC'] = gisrc_dst
  188. sub.Popen(reg_cmd, shell=True, env=env)
  189. def copy_rasters(rasters, gisrc_src, gisrc_dst, region=None):
  190. """Copy rasters from one mapset to another, crop the raster to the region.
  191. :param rasters: a list of strings with the raster map that must be copied
  192. from a master to another.
  193. :type rasters: list
  194. :param gisrc_src: path of the GISRC file from where we want to copy the groups
  195. :type gisrc_src: str
  196. :param gisrc_dst: path of the GISRC file where the groups will be created
  197. :type gisrc_dst: str
  198. :param region: a region like object or a dictionary with the region
  199. parameters that will be used to crop the rasters of the
  200. groups
  201. :type region: Region object or dictionary
  202. :returns: None
  203. """
  204. env = os.environ.copy()
  205. if region:
  206. set_region(region, gisrc_src, gisrc_dst, env)
  207. path_dst = os.path.join(*read_gisrc(gisrc_dst)[::-1])
  208. nam = "copy%d__%s" % (id(gisrc_dst), '%s')
  209. # instantiate modules
  210. mpclc = Module('r.mapcalc')
  211. rpck = Module('r.pack')
  212. rupck = Module('r.unpack')
  213. remove = Module('g.remove')
  214. for rast in rasters:
  215. rast_clean = rast.split('@')[0] if '@' in rast else rast
  216. # change gisdbase to src
  217. env['GISRC'] = gisrc_src
  218. name = nam % rast_clean
  219. mpclc(expression="%s=%s" % (name, rast), overwrite=True, env_=env)
  220. file_dst = "%s.pack" % os.path.join(path_dst, name)
  221. rpck(input=name, output=file_dst, overwrite=True, env_=env)
  222. remove(flags='f', type='raster', name=name, env_=env)
  223. # change gisdbase to dst
  224. env['GISRC'] = gisrc_dst
  225. rupck(input=file_dst, output=rast_clean, overwrite=True, env_=env)
  226. os.remove(file_dst)
  227. def copy_vectors(vectors, gisrc_src, gisrc_dst):
  228. """Copy vectors from one mapset to another, crop the raster to the region.
  229. :param vectors: a list of strings with the vector map that must be copied
  230. from a master to another.
  231. :type vectors: list
  232. :param gisrc_src: path of the GISRC file from where we want to copy the groups
  233. :type gisrc_src: str
  234. :param gisrc_dst: path of the GISRC file where the groups will be created
  235. :type gisrc_dst: str
  236. :returns: None
  237. """
  238. env = os.environ.copy()
  239. path_dst = os.path.join(*read_gisrc(gisrc_dst))
  240. nam = "copy%d__%s" % (id(gisrc_dst), '%s')
  241. # instantiate modules
  242. vpck = Module('v.pack')
  243. vupck = Module('v.unpack')
  244. remove = Module('g.remove')
  245. for vect in vectors:
  246. # change gisdbase to src
  247. env['GISRC'] = gisrc_src
  248. name = nam % vect
  249. file_dst = "%s.pack" % os.path.join(path_dst, name)
  250. vpck(input=name, output=file_dst, overwrite=True, env_=env)
  251. remove(flags='f', type='vector', name=name, env_=env)
  252. # change gisdbase to dst
  253. env['GISRC'] = gisrc_dst
  254. vupck(input=file_dst, output=vect, overwrite=True, env_=env)
  255. os.remove(file_dst)
  256. def get_cmd(cmdd):
  257. """Transform a cmd dictionary to a list of parameters. It is useful to
  258. pickle a Module class and cnvert into a string that can be used with
  259. `Popen(get_cmd(cmdd), shell=True)`.
  260. :param cmdd: a module dictionary with all the parameters
  261. :type cmdd: dict
  262. >>> slp = Module('r.slope.aspect',
  263. ... elevation='ele', slope='slp', aspect='asp',
  264. ... overwrite=True, run_=False)
  265. >>> get_cmd(slp.get_dict()) # doctest: +ELLIPSIS
  266. ['r.slope.aspect', u'elevation=ele', u'format=degrees', ..., u'--o']
  267. """
  268. cmd = [cmdd['name'], ]
  269. cmd.extend(("%s=%s" % (k, v) for k, v in cmdd['inputs']
  270. if not isinstance(v, list)))
  271. cmd.extend(("%s=%s" % (k, ','.join(vals if isinstance(vals[0], str)
  272. else [repr(v) for v in vals]))
  273. for k, vals in cmdd['inputs']
  274. if isinstance(vals, list)))
  275. cmd.extend(("%s=%s" % (k, v) for k, v in cmdd['outputs']
  276. if not isinstance(v, list)))
  277. cmd.extend(("%s=%s" % (k, ','.join([repr(v) for v in vals]))
  278. for k, vals in cmdd['outputs'] if isinstance(vals, list)))
  279. cmd.extend(("-%s" % (flg) for flg in cmdd['flags'] if len(flg) == 1))
  280. cmd.extend(("--%s" % (flg[0]) for flg in cmdd['flags'] if len(flg) > 1))
  281. return cmd
  282. def cmd_exe(args):
  283. """Create a mapset, and execute a cmd inside.
  284. :param args: is a tuple that contains several information see below
  285. :type args: tuple
  286. :returns: None
  287. The puple has to contain:
  288. - bbox (dict): a dict with the region parameters (n, s, e, w, etc.)
  289. that we want to set before to apply the command.
  290. - mapnames (dict): a dictionary to substitute the input if the domain has
  291. been splitted in several tiles.
  292. - gisrc_src (str): path of the GISRC file from where we want to copy the
  293. groups.
  294. - gisrc_dst (str): path of the GISRC file where the groups will be created.
  295. - cmd (dict): a dictionary with all the parameter of a GRASS module.
  296. - groups (list): a list of strings with the groups that we want to copy in
  297. the mapset.
  298. """
  299. bbox, mapnames, gisrc_src, gisrc_dst, cmd, groups = args
  300. src, dst = get_mapset(gisrc_src, gisrc_dst)
  301. env = os.environ.copy()
  302. env['GISRC'] = gisrc_dst
  303. shell = True if sys.platform == 'win32' else False
  304. if mapnames:
  305. inputs = dict(cmd['inputs'])
  306. # reset the inputs to
  307. for key in mapnames:
  308. inputs[key] = mapnames[key]
  309. cmd['inputs'] = inputs.items()
  310. # set the region to the tile
  311. sub.Popen(['g.region', 'raster=%s' % key], shell=shell, env=env).wait()
  312. else:
  313. # set the computational region
  314. lcmd = ['g.region', ]
  315. lcmd.extend(["%s=%s" % (k, v) for k, v in bbox.items()])
  316. sub.Popen(lcmd, shell=shell, env=env).wait()
  317. if groups:
  318. copy_groups(groups, gisrc_src, gisrc_dst)
  319. # run the grass command
  320. sub.Popen(get_cmd(cmd), shell=shell, env=env).wait()
  321. # remove temp GISRC
  322. os.remove(gisrc_dst)
  323. class GridModule(object):
  324. # TODO maybe also i.* could be supported easily
  325. """Run GRASS raster commands in a multiprocessing mode.
  326. :param cmd: raster GRASS command, only command staring with r.* are valid.
  327. :type cmd: str
  328. :param width: width of the tile, in pixel
  329. :type width: int
  330. :param height: height of the tile, in pixel.
  331. :type height: int
  332. :param overlap: overlap between tiles, in pixel.
  333. :type overlap: int
  334. :param processes: number of threads, default value is equal to the number
  335. of processor available.
  336. :param split: if True use r.tile to split all the inputs.
  337. :type split: bool
  338. :param mapset_prefix: if specified created mapsets start with this prefix
  339. :type mapset_prefix: str
  340. :param run_: if False only instantiate the object
  341. :type run_: bool
  342. :param args: give all the parameters to the command
  343. :param kargs: give all the parameters to the command
  344. >>> grd = GridModule('r.slope.aspect',
  345. ... width=500, height=500, overlap=2,
  346. ... processes=None, split=False,
  347. ... elevation='elevation',
  348. ... slope='slope', aspect='aspect', overwrite=True)
  349. >>> grd.run()
  350. """
  351. def __init__(self, cmd, width=None, height=None, overlap=0, processes=None,
  352. split=False, debug=False, region=None, move=None, log=False,
  353. start_row=0, start_col=0, out_prefix='', mapset_prefix=None,
  354. *args, **kargs):
  355. kargs['run_'] = False
  356. self.mset = Mapset()
  357. self.module = Module(cmd, *args, **kargs)
  358. self.width = width
  359. self.height = height
  360. self.overlap = overlap
  361. self.processes = processes
  362. self.region = region if region else Region()
  363. self.start_row = start_row
  364. self.start_col = start_col
  365. self.out_prefix = out_prefix
  366. self.log = log
  367. self.move = move
  368. self.gisrc_src = os.environ['GISRC']
  369. self.n_mset, self.gisrc_dst = None, None
  370. if self.move:
  371. self.n_mset = copy_mapset(self.mset, self.move)
  372. self.gisrc_dst = write_gisrc(self.n_mset.gisdbase,
  373. self.n_mset.location,
  374. self.n_mset.name)
  375. rasters = [r for r in select(self.module.inputs, 'raster')]
  376. if rasters:
  377. copy_rasters(rasters, self.gisrc_src, self.gisrc_dst,
  378. region=self.region)
  379. vectors = [v for v in select(self.module.inputs, 'vector')]
  380. if vectors:
  381. copy_vectors(vectors, self.gisrc_src, self.gisrc_dst)
  382. groups = [g for g in select(self.module.inputs, 'group')]
  383. if groups:
  384. copy_groups(groups, self.gisrc_src, self.gisrc_dst,
  385. region=self.region)
  386. self.bboxes = split_region_tiles(region=region,
  387. width=width, height=height,
  388. overlap=overlap)
  389. if mapset_prefix:
  390. self.msetstr = mapset_prefix + "_%03d_%03d"
  391. else:
  392. self.msetstr = cmd.replace('.', '') + "_%03d_%03d"
  393. self.inlist = None
  394. if split:
  395. self.split()
  396. self.debug = debug
  397. def __del__(self):
  398. if self.gisrc_dst:
  399. # remove GISRC file
  400. os.remove(self.gisrc_dst)
  401. def clean_location(self, location=None):
  402. """Remove all created mapsets.
  403. :param location: a Location instance where we are running the analysis
  404. :type location: Location object
  405. """
  406. if location is None:
  407. if self.n_mset:
  408. self.n_mset.current()
  409. location = Location()
  410. mapsets = location.mapsets(self.msetstr.split('_')[0] + '_*')
  411. for mset in mapsets:
  412. Mapset(mset).delete()
  413. if self.n_mset and self.n_mset.is_current():
  414. self.mset.current()
  415. def split(self):
  416. """Split all the raster inputs using r.tile"""
  417. rtile = Module('r.tile')
  418. inlist = {}
  419. for inm in select(self.module.inputs, 'raster'):
  420. rtile(input=inm.value, output=inm.value,
  421. width=self.width, height=self.height,
  422. overlap=self.overlap)
  423. patt = '%s-*' % inm.value
  424. inlist[inm.value] = sorted(self.mset.glist(type='raster',
  425. pattern=patt))
  426. self.inlist = inlist
  427. def get_works(self):
  428. """Return a list of tuble with the parameters for cmd_exe function"""
  429. works = []
  430. reg = Region()
  431. if self.move:
  432. mdst, ldst, gdst = read_gisrc(self.gisrc_dst)
  433. else:
  434. ldst, gdst = self.mset.location, self.mset.gisdbase
  435. cmd = self.module.get_dict()
  436. groups = [g for g in select(self.module.inputs, 'group')]
  437. for row, box_row in enumerate(self.bboxes):
  438. for col, box in enumerate(box_row):
  439. inms = None
  440. if self.inlist:
  441. inms = {}
  442. cols = len(box_row)
  443. for key in self.inlist:
  444. indx = row * cols + col
  445. inms[key] = "%s@%s" % (self.inlist[key][indx],
  446. self.mset.name)
  447. # set the computational region, prepare the region parameters
  448. bbox = dict([(k[0], str(v)) for k, v in box.items()[:-2]])
  449. bbox['nsres'] = '%f' % reg.nsres
  450. bbox['ewres'] = '%f' % reg.ewres
  451. new_mset = self.msetstr % (self.start_row + row,
  452. self.start_col + col),
  453. works.append((bbox, inms,
  454. self.gisrc_src,
  455. write_gisrc(gdst, ldst, new_mset),
  456. cmd, groups))
  457. return works
  458. def define_mapset_inputs(self):
  459. """Add the mapset information to the input maps
  460. """
  461. for inmap in self.module.inputs:
  462. inm = self.module.inputs[inmap]
  463. if inm.type in ('raster', 'vector') and inm.value:
  464. if '@' not in inm.value:
  465. mset = get_mapset_raster(inm.value)
  466. inm.value = inm.value + '@%s' % mset
  467. def run(self, patch=True, clean=True):
  468. """Run the GRASS command
  469. :param patch: set False if you does not want to patch the results
  470. :type patch: bool
  471. :param clean: set False if you does not want to remove all the stuff
  472. created by GridModule
  473. :type clean: bool
  474. """
  475. self.module.flags.overwrite = True
  476. self.define_mapset_inputs()
  477. if self.debug:
  478. for wrk in self.get_works():
  479. cmd_exe(wrk)
  480. else:
  481. pool = mltp.Pool(processes=self.processes)
  482. result = pool.map_async(cmd_exe, self.get_works())
  483. result.wait()
  484. pool.close()
  485. pool.join()
  486. if not result.successful():
  487. raise RuntimeError(_("Execution of subprocesses was not successful"))
  488. if patch:
  489. if self.move:
  490. os.environ['GISRC'] = self.gisrc_dst
  491. self.n_mset.current()
  492. self.patch()
  493. os.environ['GISRC'] = self.gisrc_src
  494. self.mset.current()
  495. # copy the outputs from dst => src
  496. routputs = [self.out_prefix + o
  497. for o in select(self.module.outputs, 'raster')]
  498. copy_rasters(routputs, self.gisrc_dst, self.gisrc_src)
  499. else:
  500. self.patch()
  501. if self.log:
  502. # record in the temp directory
  503. from grass.lib.gis import G_tempfile
  504. tmp, dummy = os.path.split(G_tempfile())
  505. tmpdir = os.path.join(tmp, self.module.name)
  506. for k in self.module.outputs:
  507. par = self.module.outputs[k]
  508. if par.typedesc == 'raster' and par.value:
  509. dirpath = os.path.join(tmpdir, par.name)
  510. if not os.path.isdir(dirpath):
  511. os.makedirs(dirpath)
  512. fil = open(os.path.join(dirpath,
  513. self.out_prefix + par.value), 'w+')
  514. fil.close()
  515. if clean:
  516. self.clean_location()
  517. self.rm_tiles()
  518. if self.n_mset:
  519. gisdbase, location = os.path.split(self.move)
  520. self.clean_location(Location(location, gisdbase))
  521. # rm temporary gis_rc
  522. os.remove(self.gisrc_dst)
  523. self.gisrc_dst = None
  524. sht.rmtree(os.path.join(self.move, 'PERMANENT'))
  525. sht.rmtree(os.path.join(self.move, self.mset.name))
  526. def patch(self):
  527. """Patch the final results."""
  528. bboxes = split_region_tiles(width=self.width, height=self.height)
  529. loc = Location()
  530. mset = loc[self.mset.name]
  531. mset.visible.extend(loc.mapsets())
  532. for otmap in self.module.outputs:
  533. otm = self.module.outputs[otmap]
  534. if otm.typedesc == 'raster' and otm.value:
  535. rpatch_map(otm.value,
  536. self.mset.name, self.msetstr, bboxes,
  537. self.module.flags.overwrite,
  538. self.start_row, self.start_col, self.out_prefix)
  539. def rm_tiles(self):
  540. """Remove all the tiles."""
  541. # if split, remove tiles
  542. if self.inlist:
  543. grm = Module('g.remove')
  544. for key in self.inlist:
  545. grm(flags='f', type='raster', name=self.inlist[key])