grid.py 21 KB

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