grid.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Thu Mar 28 11:06:00 2013
  4. @author: pietro
  5. """
  6. import os
  7. import multiprocessing as mltp
  8. import subprocess as sub
  9. import shutil as sht
  10. from grass.script.setup import write_gisrc
  11. from grass.pygrass.gis import Mapset, Location, make_mapset
  12. from grass.pygrass.gis.region import Region
  13. from grass.pygrass.modules import Module
  14. from grass.pygrass.functions import get_mapset_raster
  15. from split import split_region_tiles
  16. from patch import patch_map
  17. _GREG = Module('g.region')
  18. def select(parms, ptype):
  19. """Select only a certain type of parameters. ::
  20. >>> slp = Module('r.slope.aspect',
  21. ... elevation='ele', slope='slp', aspect='asp',
  22. ... run_=False)
  23. >>> for rast in select(slp.outputs, 'raster'):
  24. ... print rast
  25. ...
  26. slp
  27. asp
  28. """
  29. for k in parms:
  30. par = parms[k]
  31. if par.type == ptype or par.typedesc == ptype and par.value:
  32. if par.multiple:
  33. for p in par.value:
  34. yield p
  35. else:
  36. yield par.value
  37. def copy_mapset(mapset, path):
  38. """Copy mapset to another place without copying raster and vector data.
  39. """
  40. per_old = os.path.join(mapset.gisdbase, mapset.location, 'PERMANENT')
  41. per_new = os.path.join(path, 'PERMANENT')
  42. map_old = mapset.path()
  43. map_new = os.path.join(path, mapset.name)
  44. if not os.path.isdir(path):
  45. os.makedirs(path)
  46. if not os.path.isdir(map_new):
  47. os.mkdir(map_new)
  48. for f in (fi for fi in os.listdir(per_old) if fi.isupper()):
  49. sht.copy(os.path.join(per_old, f), per_new)
  50. for f in (fi for fi in os.listdir(map_old) if fi.isupper()):
  51. sht.copy(os.path.join(map_old, f), map_new)
  52. gisdbase, location = os.path.split(path)
  53. return Mapset(mapset.name, location, gisdbase)
  54. def copy_raster(rasters, src, dst, region=None):
  55. """Copy raster from one mapset to another, crop the raster to the region.
  56. """
  57. # set region
  58. if region:
  59. region.set_current()
  60. nam = "copy%d__%s" % (id(dst), '%s')
  61. expr = "%s=%s"
  62. # instantiate modules
  63. mpclc = Module('r.mapcalc')
  64. rpck = Module('r.pack')
  65. rupck = Module('r.unpack')
  66. rm = Module('g.remove')
  67. # get and set GISRC
  68. gisrc_src = os.environ['GISRC']
  69. gisrc_dst = write_gisrc(dst.gisdbase, dst.location, dst.name)
  70. pdst = dst.path()
  71. for rast in rasters:
  72. # change gisdbase to src
  73. os.environ['GISRC'] = gisrc_src
  74. src.current()
  75. name = nam % rast
  76. mpclc(expression=expr % (name, rast), overwrite=True)
  77. file_dst = "%s.pack" % os.path.join(pdst, name)
  78. rpck(input=name, output=file_dst, overwrite=True)
  79. rm(rast=name)
  80. # change gisdbase to dst
  81. os.environ['GISRC'] = gisrc_dst
  82. dst.current()
  83. rupck(input=file_dst, output=rast, overwrite=True)
  84. os.remove(file_dst)
  85. def get_cmd(cmdd):
  86. """Transforma a cmd dictionary to a list of parameters"""
  87. cmd = [cmdd['name'], ]
  88. cmd.extend(("%s=%s" % (k, v) for k, v in cmdd['inputs']
  89. if not isinstance(v, list)))
  90. cmd.extend(("%s=%s" % (k, ','.join(vals if isinstance(vals[0], str)
  91. else map(repr, vals)))
  92. for k, vals in cmdd['inputs']
  93. if isinstance(vals, list)))
  94. cmd.extend(("%s=%s" % (k, v) for k, v in cmdd['outputs']
  95. if not isinstance(v, list)))
  96. cmd.extend(("%s=%s" % (k, ','.join(map(repr, vals)))
  97. for k, vals in cmdd['outputs']
  98. if isinstance(vals, list)))
  99. cmd.extend(("%s" % (flg) for flg in cmdd['flags'] if len(flg) == 1))
  100. cmd.extend(("--%s" % (flg[0]) for flg in cmdd['flags'] if len(flg) > 1))
  101. return cmd
  102. def cmd_exe((bbox, mapnames, msetname, cmd)):
  103. """Create a mapset, and execute a cmd inside."""
  104. mset = Mapset()
  105. try:
  106. make_mapset(msetname)
  107. except:
  108. pass
  109. ms = Mapset(msetname)
  110. ms.visible.extend(mset.visible)
  111. env = os.environ.copy()
  112. env['GISRC'] = write_gisrc(mset.gisdbase, mset.location, msetname)
  113. if mapnames:
  114. inputs = dict(cmd['inputs'])
  115. # reset the inputs to
  116. for key in mapnames:
  117. inputs[key] = mapnames[key]
  118. cmd['inputs'] = inputs.items()
  119. # set the region to the tile
  120. _GREG(env_=env, rast=key)
  121. else:
  122. #reg = Region() nsres=reg.nsres, ewres=reg.ewres,
  123. # set the computational region
  124. _GREG(env_=env, **bbox)
  125. # run the grass command
  126. #import ipdb; ipdb.set_trace()
  127. sub.Popen(get_cmd(cmd), env=env).wait()
  128. class GridModule(object):
  129. """Run GRASS raster commands in a multiproccessing mode.
  130. Parameters
  131. -----------
  132. cmd: raster GRASS command
  133. Only command staring with r.* are valid.
  134. width: integer
  135. Width of the tile, in pixel.
  136. height: integer
  137. Height of the tile, in pixel.
  138. overlap: integer
  139. Overlap between tiles, in pixel.
  140. nthreads: number of threads
  141. Default value is equal to the number of processor available.
  142. split: boolean
  143. If True use r.tile to split all the inputs.
  144. run_: boolean
  145. If False only instantiate the object.
  146. args and kargs: cmd parameters
  147. Give all the parameters to the command.
  148. Examples
  149. --------
  150. ::
  151. >>> grd = GridModule('r.slope.aspect',
  152. ... width=500, height=500, overlap=2,
  153. ... processes=None, split=True,
  154. ... elevation='elevation',
  155. ... slope='slope', aspect='aspect', overwrite=True)
  156. >>> grd.run()
  157. """
  158. def __init__(self, cmd, width=None, height=None, overlap=0, processes=None,
  159. split=False, debug=False, region=None, move=None,
  160. start_row=0, start_col=0, out_prefix='',
  161. *args, **kargs):
  162. kargs['run_'] = False
  163. self.mset = Mapset()
  164. self.module = Module(cmd, *args, **kargs)
  165. self.width = width
  166. self.height = height
  167. self.overlap = overlap
  168. self.processes = processes
  169. self.region = region if region else Region()
  170. self.start_row = start_row
  171. self.start_col = start_col
  172. self.out_prefix = out_prefix
  173. self.n_mset = None
  174. if move:
  175. self.n_mset = copy_mapset(self.mset, move)
  176. copy_raster(select(self.module.inputs, 'raster'),
  177. self.mset, self.n_mset, region=self.region)
  178. self.bboxes = split_region_tiles(region=region,
  179. width=width, height=height,
  180. overlap=overlap)
  181. self.msetstr = cmd.replace('.', '') + "_%03d_%03d"
  182. self.inlist = None
  183. if split:
  184. self.split()
  185. self.debug = debug
  186. def clean_location(self):
  187. """Remove all created mapsets."""
  188. mapsets = Location().mapsets(self.msetstr.split('_')[0] + '_*')
  189. for mset in mapsets:
  190. Mapset(mset).delete()
  191. def split(self):
  192. """Split all the raster inputs using r.tile"""
  193. rtile = Module('r.tile')
  194. inlist = {}
  195. for inm in select(self.module.inputs, 'raster'):
  196. rtile(input=inm.value, output=inm.value,
  197. width=self.width, height=self.height,
  198. overlap=self.overlap)
  199. patt = '%s-*' % inm.value
  200. inlist[inm.value] = sorted(self.mset.glist(type='rast',
  201. pattern=patt))
  202. self.inlist = inlist
  203. def get_works(self):
  204. """Return a list of tuble with the parameters for cmd_exe function"""
  205. works = []
  206. reg = Region()
  207. cmd = self.module.get_dict()
  208. for row, box_row in enumerate(self.bboxes):
  209. for col, box in enumerate(box_row):
  210. inms = None
  211. if self.inlist:
  212. inms = {}
  213. cols = len(box_row)
  214. for key in self.inlist:
  215. indx = row * cols + col
  216. inms[key] = "%s@%s" % (self.inlist[key][indx],
  217. self.mset.name)
  218. # set the computational region, prepare the region parameters
  219. bbox = dict([(k[0], str(v)) for k, v in box.items()[:-2]])
  220. bbox['nsres'] = '%f' % reg.nsres
  221. bbox['ewres'] = '%f' % reg.ewres
  222. works.append((bbox, inms,
  223. self.msetstr % (self.start_row + row,
  224. self.start_col + col),
  225. cmd))
  226. return works
  227. def define_mapset_inputs(self):
  228. for inmap in self.module.inputs:
  229. inm = self.module.inputs[inmap]
  230. # (inm.type == 'raster' or inm.typedesc == 'group') and inm.value:
  231. if inm.type == 'raster' and inm.value:
  232. if '@' not in inm.value:
  233. mset = get_mapset_raster(inm.value)
  234. inm.value = inm.value + '@%s' % mset
  235. def run(self, patch=True, clean=True):
  236. """Run the GRASS command."""
  237. self.module.flags.overwrite = True
  238. self.define_mapset_inputs()
  239. if self.debug:
  240. for wrk in self.get_works():
  241. cmd_exe(wrk)
  242. else:
  243. pool = mltp.Pool(processes=self.processes)
  244. result = pool.map_async(cmd_exe, self.get_works())
  245. result.wait()
  246. if not result.successful():
  247. raise RuntimeError
  248. if patch:
  249. self.patch()
  250. if clean:
  251. self.clean_location()
  252. self.rm_tiles()
  253. def patch(self):
  254. """Patch the final results."""
  255. # patch all the outputs
  256. for otmap in self.module.outputs:
  257. otm = self.module.outputs[otmap]
  258. if otm.typedesc == 'raster' and otm.value:
  259. patch_map(self.out_prefix + otm.value,
  260. self.mset.name, self.msetstr,
  261. split_region_tiles(width=self.width,
  262. height=self.height),
  263. self.module.flags.overwrite,
  264. self.start_row, self.start_col)
  265. def rm_tiles(self):
  266. """Remove all the tiles."""
  267. # if split, remove tiles
  268. if self.inlist:
  269. grm = Module('g.remove')
  270. for key in self.inlist:
  271. grm(rast=self.inlist[key])