grid.py 21 KB

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