grid.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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(args):
  103. """Create a mapset, and execute a cmd inside."""
  104. bbox, mapnames, msetname, cmd = args
  105. mset = Mapset()
  106. try:
  107. make_mapset(msetname)
  108. except:
  109. pass
  110. ms = Mapset(msetname)
  111. ms.visible.extend(mset.visible)
  112. env = os.environ.copy()
  113. env['GISRC'] = write_gisrc(mset.gisdbase, mset.location, msetname)
  114. if mapnames:
  115. inputs = dict(cmd['inputs'])
  116. # reset the inputs to
  117. for key in mapnames:
  118. inputs[key] = mapnames[key]
  119. cmd['inputs'] = inputs.items()
  120. # set the region to the tile
  121. _GREG(env_=env, rast=key)
  122. else:
  123. #reg = Region() nsres=reg.nsres, ewres=reg.ewres,
  124. # set the computational region
  125. _GREG(env_=env, **bbox)
  126. # run the grass command
  127. #import ipdb; ipdb.set_trace()
  128. sub.Popen(get_cmd(cmd), env=env).wait()
  129. class GridModule(object):
  130. """Run GRASS raster commands in a multiproccessing mode.
  131. Parameters
  132. -----------
  133. cmd: raster GRASS command
  134. Only command staring with r.* are valid.
  135. width: integer
  136. Width of the tile, in pixel.
  137. height: integer
  138. Height of the tile, in pixel.
  139. overlap: integer
  140. Overlap between tiles, in pixel.
  141. nthreads: number of threads
  142. Default value is equal to the number of processor available.
  143. split: boolean
  144. If True use r.tile to split all the inputs.
  145. run_: boolean
  146. If False only instantiate the object.
  147. args and kargs: cmd parameters
  148. Give all the parameters to the command.
  149. Examples
  150. --------
  151. ::
  152. >>> grd = GridModule('r.slope.aspect',
  153. ... width=500, height=500, overlap=2,
  154. ... processes=None, split=True,
  155. ... elevation='elevation',
  156. ... slope='slope', aspect='aspect', overwrite=True)
  157. >>> grd.run()
  158. """
  159. def __init__(self, cmd, width=None, height=None, overlap=0, processes=None,
  160. split=False, debug=False, region=None, move=None,
  161. start_row=0, start_col=0, out_prefix='',
  162. *args, **kargs):
  163. kargs['run_'] = False
  164. self.mset = Mapset()
  165. self.module = Module(cmd, *args, **kargs)
  166. self.width = width
  167. self.height = height
  168. self.overlap = overlap
  169. self.processes = processes
  170. self.region = region if region else Region()
  171. self.start_row = start_row
  172. self.start_col = start_col
  173. self.out_prefix = out_prefix
  174. self.n_mset = None
  175. if move:
  176. self.n_mset = copy_mapset(self.mset, move)
  177. copy_raster(select(self.module.inputs, 'raster'),
  178. self.mset, self.n_mset, region=self.region)
  179. self.bboxes = split_region_tiles(region=region,
  180. width=width, height=height,
  181. overlap=overlap)
  182. self.msetstr = cmd.replace('.', '') + "_%03d_%03d"
  183. self.inlist = None
  184. if split:
  185. self.split()
  186. self.debug = debug
  187. def clean_location(self):
  188. """Remove all created mapsets."""
  189. mapsets = Location().mapsets(self.msetstr.split('_')[0] + '_*')
  190. for mset in mapsets:
  191. Mapset(mset).delete()
  192. def split(self):
  193. """Split all the raster inputs using r.tile"""
  194. rtile = Module('r.tile')
  195. inlist = {}
  196. for inm in select(self.module.inputs, 'raster'):
  197. rtile(input=inm.value, output=inm.value,
  198. width=self.width, height=self.height,
  199. overlap=self.overlap)
  200. patt = '%s-*' % inm.value
  201. inlist[inm.value] = sorted(self.mset.glist(type='rast',
  202. pattern=patt))
  203. self.inlist = inlist
  204. def get_works(self):
  205. """Return a list of tuble with the parameters for cmd_exe function"""
  206. works = []
  207. reg = Region()
  208. cmd = self.module.get_dict()
  209. for row, box_row in enumerate(self.bboxes):
  210. for col, box in enumerate(box_row):
  211. inms = None
  212. if self.inlist:
  213. inms = {}
  214. cols = len(box_row)
  215. for key in self.inlist:
  216. indx = row * cols + col
  217. inms[key] = "%s@%s" % (self.inlist[key][indx],
  218. self.mset.name)
  219. # set the computational region, prepare the region parameters
  220. bbox = dict([(k[0], str(v)) for k, v in box.items()[:-2]])
  221. bbox['nsres'] = '%f' % reg.nsres
  222. bbox['ewres'] = '%f' % reg.ewres
  223. works.append((bbox, inms,
  224. self.msetstr % (self.start_row + row,
  225. self.start_col + col),
  226. cmd))
  227. return works
  228. def define_mapset_inputs(self):
  229. for inmap in self.module.inputs:
  230. inm = self.module.inputs[inmap]
  231. # (inm.type == 'raster' or inm.typedesc == 'group') and inm.value:
  232. if inm.type == 'raster' and inm.value:
  233. if '@' not in inm.value:
  234. mset = get_mapset_raster(inm.value)
  235. inm.value = inm.value + '@%s' % mset
  236. def run(self, patch=True, clean=True):
  237. """Run the GRASS command."""
  238. self.module.flags.overwrite = True
  239. self.define_mapset_inputs()
  240. if self.debug:
  241. for wrk in self.get_works():
  242. cmd_exe(wrk)
  243. else:
  244. pool = mltp.Pool(processes=self.processes)
  245. result = pool.map_async(cmd_exe, self.get_works())
  246. result.wait()
  247. if not result.successful():
  248. raise RuntimeError
  249. if patch:
  250. self.patch()
  251. if clean:
  252. self.clean_location()
  253. self.rm_tiles()
  254. def patch(self):
  255. """Patch the final results."""
  256. # patch all the outputs
  257. for otmap in self.module.outputs:
  258. otm = self.module.outputs[otmap]
  259. if otm.typedesc == 'raster' and otm.value:
  260. patch_map(self.out_prefix + otm.value,
  261. self.mset.name, self.msetstr,
  262. split_region_tiles(width=self.width,
  263. height=self.height),
  264. self.module.flags.overwrite,
  265. self.start_row, self.start_col)
  266. def rm_tiles(self):
  267. """Remove all the tiles."""
  268. # if split, remove tiles
  269. if self.inlist:
  270. grm = Module('g.remove')
  271. for key in self.inlist:
  272. grm(rast=self.inlist[key])