__init__.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. # -*- coding: utf-8 -*-
  2. #!/usr/bin/env python2.7
  3. from __future__ import (nested_scopes, generators, division, absolute_import,
  4. with_statement, print_function, unicode_literals)
  5. from os import listdir
  6. from os.path import join, exists, isdir
  7. import shutil
  8. import ctypes as ct
  9. import fnmatch
  10. from grass import script
  11. #from grass.script import setup
  12. #
  13. #
  14. #GISBASE = "/home/pietro/docdat/src/gis/grass/grass70/dist.x86_64-unknown-linux-gnu"
  15. #LOCATION = "nc_basic_spm_grass7'"
  16. #GISDBASE = "/home/pietro/docdat/gis"
  17. #MAPSET = "sqlite"
  18. #GUI = "wxpython"
  19. #
  20. #setup.init(GISBASE, GISDBASE, LOCATION, MAPSET)
  21. script.gisenv()
  22. import grass.lib.gis as libgis
  23. from grass.pygrass.functions import getenv
  24. from grass.pygrass.errors import GrassError
  25. from . import region
  26. #write dec to check if user have permissions or not
  27. ETYPE = {'rast': libgis.G_ELEMENT_RASTER,
  28. 'rast3d': libgis.G_ELEMENT_RASTER3D,
  29. 'vect': libgis.G_ELEMENT_VECTOR,
  30. 'oldvect': libgis.G_ELEMENT_OLDVECTOR,
  31. 'asciivect': libgis.G_ELEMENT_ASCIIVECTOR,
  32. 'icon': libgis.G_ELEMENT_ICON,
  33. 'labels': libgis.G_ELEMENT_LABEL,
  34. 'sites': libgis.G_ELEMENT_SITE,
  35. 'region': libgis.G_ELEMENT_REGION,
  36. 'region3d': libgis.G_ELEMENT_REGION3D,
  37. 'group': libgis.G_ELEMENT_GROUP,
  38. 'view3d': libgis.G_ELEMENT_3DVIEW}
  39. CHECK_IS = {"GISBASE": libgis.G_is_gisbase,
  40. "GISDBASE": lambda x: True,
  41. "LOCATION_NAME": libgis.G_is_location,
  42. "MAPSET": libgis.G_is_mapset}
  43. def _check(value, path, type):
  44. if value and CHECK_IS[type](join(path, value)):
  45. return value
  46. elif value is '':
  47. return getenv(type)
  48. else:
  49. raise GrassError("%s <%s> not found." % (type.title(),
  50. join(path, value)))
  51. def set_current_mapset(mapset, location=None, gisdbase=None):
  52. libgis.G_setenv('MAPSET', mapset)
  53. if location:
  54. libgis.G_setenv('LOCATION_NAME', location)
  55. if gisdbase:
  56. libgis.G_setenv('GISDBASE', gisdbase)
  57. def make_mapset(mapset, location=None, gisdbase=None):
  58. res = libgis.G_make_mapset(gisdbase, location, mapset)
  59. if res == -1:
  60. raise GrassError("I cannot create a new mapset.")
  61. elif res == -2:
  62. raise GrassError("Illegal name.")
  63. class Gisdbase(object):
  64. """Return Gisdbase object. ::
  65. >>> from grass.script.core import gisenv
  66. >>> gisdbase = Gisdbase()
  67. >>> gisdbase.name == gisenv()['GISDBASE']
  68. True
  69. """
  70. def __init__(self, gisdbase=''):
  71. self.name = gisdbase
  72. def _get_name(self):
  73. return self._name
  74. def _set_name(self, name):
  75. self._name = _check(name, '', "GISDBASE")
  76. name = property(fget=_get_name, fset=_set_name)
  77. def __str__(self):
  78. return self.name
  79. def __repr__(self):
  80. return 'Gisdbase(%s)' % self.name
  81. def __getitem__(self, location):
  82. """Return a Location object. ::
  83. >>> from grass.script.core import gisenv
  84. >>> loc_env = gisenv()['LOCATION_NAME']
  85. >>> gisdbase = Gisdbase()
  86. >>> loc_py = gisdbase[loc_env]
  87. >>> loc_env == loc_py.name
  88. True
  89. ..
  90. """
  91. if location in self.locations():
  92. return Location(location, self.name)
  93. else:
  94. raise KeyError('Location: %s does not exist' % location)
  95. def __iter__(self):
  96. for loc in self.locations():
  97. yield Location(loc, self.name)
  98. def new_location(self):
  99. if libgis.G__make_location() != 0:
  100. raise GrassError("I cannot create a new mapset.")
  101. def locations(self):
  102. """Return a list of locations that are available in the gisdbase: ::
  103. >>> gisdbase = Gisdbase()
  104. >>> gisdbase.locations() # doctest: +ELLIPSIS
  105. [...]
  106. ..
  107. """
  108. locations = []
  109. for loc in listdir(self.name):
  110. if libgis.G_is_location(join(self.name, loc)):
  111. locations.append(loc)
  112. locations.sort()
  113. return locations
  114. class Location(object):
  115. """Location object ::
  116. >>> from grass.script.core import gisenv
  117. >>> location = Location()
  118. >>> location # doctest: +ELLIPSIS
  119. Location(...)
  120. >>> location.gisdbase == gisenv()['GISDBASE']
  121. True
  122. >>> location.name == gisenv()['LOCATION_NAME']
  123. True
  124. """
  125. def __init__(self, location='', gisdbase=''):
  126. self.gisdbase = gisdbase
  127. self.name = location
  128. def _get_gisdb(self):
  129. return self._gisdb
  130. def _set_gisdb(self, gisdb):
  131. self._gisdb = _check(gisdb, '', "GISDBASE")
  132. gisdbase = property(fget=_get_gisdb, fset=_set_gisdb)
  133. def _get_name(self):
  134. return self._name
  135. def _set_name(self, name):
  136. self._name = _check(name, self._gisdb, "LOCATION_NAME")
  137. name = property(fget=_get_name, fset=_set_name)
  138. def __getitem__(self, mapset):
  139. if mapset in self.mapsets():
  140. return Mapset(mapset)
  141. else:
  142. raise KeyError('Mapset: %s does not exist' % mapset)
  143. def __iter__(self):
  144. lpath = self.path()
  145. return (m for m in listdir(lpath)
  146. if (isdir(join(lpath, m)) and _check(m, lpath, "MAPSET")))
  147. def __len__(self):
  148. return len(self.mapsets())
  149. def __str__(self):
  150. return self.name
  151. def __repr__(self):
  152. return 'Location(%r)' % self.name
  153. def mapsets(self, pattern=None, permissions=True):
  154. """Return a list of the available mapsets. ::
  155. >>> location = Location()
  156. >>> location.mapsets()
  157. ['PERMANENT', 'user1']
  158. """
  159. mapsets = [mapset for mapset in self]
  160. if permissions:
  161. mapsets = [mapset for mapset in mapsets
  162. if libgis.G__mapset_permissions(mapset)]
  163. if pattern:
  164. return fnmatch.filter(mapsets, pattern)
  165. return mapsets
  166. def path(self):
  167. return join(self.gisdbase, self.name)
  168. class Mapset(object):
  169. """Mapset ::
  170. >>> mapset = Mapset()
  171. >>> mapset
  172. Mapset('user1')
  173. >>> mapset.gisdbase # doctest: +ELLIPSIS
  174. '/home/...'
  175. >>> mapset.location
  176. 'nc_basic_spm_grass7'
  177. >>> mapset.name
  178. 'user1'
  179. """
  180. def __init__(self, mapset='', location='', gisdbase=''):
  181. self.gisdbase = gisdbase
  182. self.location = location
  183. self.name = mapset
  184. self.visible = VisibleMapset(self.name, self.location, self.gisdbase)
  185. def _get_gisdb(self):
  186. return self._gisdb
  187. def _set_gisdb(self, gisdb):
  188. self._gisdb = _check(gisdb, '', "GISDBASE")
  189. gisdbase = property(fget=_get_gisdb, fset=_set_gisdb)
  190. def _get_loc(self):
  191. return self._loc
  192. def _set_loc(self, loc):
  193. self._loc = _check(loc, self._gisdb, "LOCATION_NAME")
  194. location = property(fget=_get_loc, fset=_set_loc)
  195. def _get_name(self):
  196. return self._name
  197. def _set_name(self, name):
  198. self._name = _check(name, join(self._gisdb, self._loc), "MAPSET")
  199. name = property(fget=_get_name, fset=_set_name)
  200. def __str__(self):
  201. return self.name
  202. def __repr__(self):
  203. return 'Mapset(%r)' % self.name
  204. def glist(self, type, pattern=None):
  205. """Return a list of grass types like:
  206. * 'asciivect',
  207. * 'group',
  208. * 'icon',
  209. * 'labels',
  210. * 'oldvect',
  211. * 'rast',
  212. * 'rast3d',
  213. * 'region',
  214. * 'region3d',
  215. * 'sites',
  216. * 'vect',
  217. * 'view3d'
  218. ::
  219. >>> mapset = Mapset('PERMANENT')
  220. >>> rast = mapset.glist('rast')
  221. >>> rast.sort()
  222. >>> rast # doctest: +ELLIPSIS
  223. ['basins', 'elevation', ...]
  224. >>> mapset.glist('rast', pattern='el*')
  225. ['elevation_shade', 'elevation']
  226. """
  227. if type not in ETYPE:
  228. str_err = "Type %s is not valid, valid types are: %s."
  229. raise TypeError(str_err % (type, ', '.join(ETYPE.keys())))
  230. clist = libgis.G_list(ETYPE[type], self.gisdbase,
  231. self.location, self.name)
  232. elist = []
  233. for el in clist:
  234. el_name = ct.cast(el, ct.c_char_p).value
  235. if el_name:
  236. elist.append(el_name)
  237. else:
  238. if pattern:
  239. return fnmatch.filter(elist, pattern)
  240. return elist
  241. def is_current(self):
  242. return (self.name == libgis.G_getenv('MAPSET') and
  243. self.location == libgis.G_getenv('LOCATION_NAME') and
  244. self.gisdbase == libgis.G_getenv('GISDBASE'))
  245. def current(self):
  246. """Set the mapset as current"""
  247. set_current_mapset(self.name, self.location, self.gisdbase)
  248. def delete(self):
  249. """Delete the mapset"""
  250. if self.is_current():
  251. raise GrassError('The mapset is in use.')
  252. shutil.rmtree(self.path())
  253. def path(self):
  254. return join(self.gisdbase, self.location, self.name)
  255. class VisibleMapset(object):
  256. def __init__(self, mapset, location='', gisdbase=''):
  257. self.mapset = mapset
  258. self.location = Location(location, gisdbase)
  259. self._list = []
  260. self.spath = join(self.location.path(), self.mapset, 'SEARCH_PATH')
  261. def __repr__(self):
  262. return repr(self.read())
  263. def __iter__(self):
  264. for mapset in self.read():
  265. yield mapset
  266. def read(self):
  267. with open(self.spath, "a+") as f:
  268. lines = f.readlines()
  269. #lines.remove('')
  270. if lines:
  271. return [l.strip() for l in lines]
  272. lns = ['PERMANENT', ]
  273. self.write(lns)
  274. return lns
  275. def write(self, mapsets):
  276. with open(self.spath, "w+") as f:
  277. ms = self.location.mapsets()
  278. f.write('%s' % '\n'.join([m for m in mapsets if m in ms]))
  279. def add(self, mapset):
  280. if mapset not in self.read() and mapset in self.location:
  281. with open(self.spath, "a+") as f:
  282. f.write('\n%s' % mapset)
  283. else:
  284. raise TypeError('Mapset not found')
  285. def remove(self, mapset):
  286. mapsets = self.read()
  287. mapsets.remove(mapset)
  288. self.write(mapsets)
  289. def extend(self, mapsets):
  290. ms = self.location.mapsets()
  291. final = self.read()
  292. final.extend([m for m in mapsets if m in ms and m not in final])
  293. self.write(final)