__init__.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  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, isdir
  7. import shutil
  8. import ctypes as ct
  9. import fnmatch
  10. import grass.lib.gis as libgis
  11. from grass.pygrass.errors import GrassError
  12. libgis.G_gisinit('')
  13. ETYPE = {'raster': libgis.G_ELEMENT_RASTER,
  14. 'raster_3d': libgis.G_ELEMENT_RASTER3D,
  15. 'vector': libgis.G_ELEMENT_VECTOR,
  16. 'label': libgis.G_ELEMENT_LABEL,
  17. 'region': libgis.G_ELEMENT_REGION,
  18. 'group': libgis.G_ELEMENT_GROUP}
  19. CHECK_IS = {"GISBASE": libgis.G_is_gisbase,
  20. "GISDBASE": lambda x: True,
  21. "LOCATION_NAME": libgis.G_is_location,
  22. "MAPSET": libgis.G_is_mapset}
  23. def is_valid(value, path, type):
  24. """Private function to check the correctness of a value.
  25. :param value: Name of the directory
  26. :type value: str
  27. :param path: Path where the directory is located
  28. :type path: path
  29. :param type: it is a string defining the type that will e checked,
  30. valid types are: GISBASE, GISDBASE, LOCATION_NAME, MAPSET
  31. :type type: str
  32. :return: True if valid else False
  33. :rtype: str
  34. """
  35. return bool(CHECK_IS[type](join(path, value)))
  36. def _check_raise(value, path, type):
  37. """Private function to check the correctness of a value.
  38. :param value: Name of the directory
  39. :type value: str
  40. :param path: Path where the directory is located
  41. :type path: path
  42. :param type: it is a string defining the type that will e checked,
  43. valid types are: GISBASE, GISDBASE, LOCATION_NAME, MAPSET
  44. :type type: str
  45. :return: the value if verify else None and
  46. if value is empty return environmental variable
  47. :rtype: str
  48. """
  49. if value is '':
  50. from grass.pygrass.utils import getenv
  51. return getenv(type)
  52. if is_valid(value, path, type):
  53. return value
  54. raise GrassError("%s <%s> not found" % (type.title(), join(path, value)))
  55. def set_current_mapset(mapset, location=None, gisdbase=None):
  56. """Set the current mapset as working area
  57. :param mapset: Name of the mapset
  58. :type value: str
  59. :param location: Name of the location
  60. :type location: str
  61. :param gisdbase: Name of the gisdbase
  62. :type gisdbase: str
  63. """
  64. libgis.G_setenv('MAPSET', mapset)
  65. if location:
  66. libgis.G_setenv('LOCATION_NAME', location)
  67. if gisdbase:
  68. libgis.G_setenv('GISDBASE', gisdbase)
  69. def make_mapset(mapset, location=None, gisdbase=None):
  70. """Create a new mapset
  71. :param mapset: Name of the mapset
  72. :type value: str
  73. :param location: Name of the location
  74. :type location: str
  75. :param gisdbase: Name of the gisdbase
  76. :type gisdbase: str"""
  77. res = libgis.G_make_mapset(gisdbase, location, mapset)
  78. if res == -1:
  79. raise GrassError("Cannot create new mapset")
  80. elif res == -2:
  81. raise GrassError("Illegal name")
  82. class Gisdbase(object):
  83. """Return Gisdbase object. ::
  84. >>> from grass.script.core import gisenv
  85. >>> gisdbase = Gisdbase()
  86. >>> gisdbase.name == gisenv()['GISDBASE']
  87. True
  88. ..
  89. """
  90. def __init__(self, gisdbase=''):
  91. self.name = gisdbase
  92. def _get_name(self):
  93. return self._name
  94. def _set_name(self, name):
  95. self._name = _check_raise(name, '', "GISDBASE")
  96. name = property(fget=_get_name, fset=_set_name,
  97. doc="Set or obtain the name of GISDBASE")
  98. def __str__(self):
  99. return self.name
  100. def __repr__(self):
  101. return 'Gisdbase(%s)' % self.name
  102. def __getitem__(self, location):
  103. """Return a Location object. ::
  104. >>> from grass.script.core import gisenv
  105. >>> loc_env = gisenv()['LOCATION_NAME']
  106. >>> gisdbase = Gisdbase()
  107. >>> loc_py = gisdbase[loc_env]
  108. >>> loc_env == loc_py.name
  109. True
  110. ..
  111. """
  112. if location in self.locations():
  113. return Location(location, self.name)
  114. else:
  115. raise KeyError('Location: %s does not exist' % location)
  116. def __iter__(self):
  117. for loc in self.locations():
  118. yield Location(loc, self.name)
  119. # TODO remove or complete this function
  120. def new_location(self):
  121. if libgis.G_make_location() != 0:
  122. raise GrassError("Cannot create new location")
  123. def locations(self):
  124. """Return a list of locations that are available in the gisdbase: ::
  125. >>> gisdbase = Gisdbase()
  126. >>> gisdbase.locations() # doctest: +ELLIPSIS
  127. [...]
  128. ..
  129. """
  130. return sorted([loc for loc in listdir(self.name)
  131. if libgis.G_is_location(join(self.name, loc))])
  132. class Location(object):
  133. """Location object ::
  134. >>> from grass.script.core import gisenv
  135. >>> location = Location()
  136. >>> location # doctest: +ELLIPSIS
  137. Location(...)
  138. >>> location.gisdbase == gisenv()['GISDBASE']
  139. True
  140. >>> location.name == gisenv()['LOCATION_NAME']
  141. True
  142. ..
  143. """
  144. def __init__(self, location='', gisdbase=''):
  145. self.gisdbase = gisdbase
  146. self.name = location
  147. def _get_gisdb(self):
  148. return self._gisdb
  149. def _set_gisdb(self, gisdb):
  150. self._gisdb = _check_raise(gisdb, '', "GISDBASE")
  151. gisdbase = property(fget=_get_gisdb, fset=_set_gisdb,
  152. doc="Set or obtain the name of GISDBASE")
  153. def _get_name(self):
  154. return self._name
  155. def _set_name(self, name):
  156. self._name = _check_raise(name, self._gisdb, "LOCATION_NAME")
  157. name = property(fget=_get_name, fset=_set_name,
  158. doc="Set or obtain the name of LOCATION")
  159. def __getitem__(self, mapset):
  160. if mapset in self.mapsets():
  161. return Mapset(mapset)
  162. else:
  163. raise KeyError('Mapset: %s does not exist' % mapset)
  164. def __iter__(self):
  165. lpath = self.path()
  166. return (m for m in listdir(lpath)
  167. if (isdir(join(lpath, m)) and is_valid(m, lpath, "MAPSET")))
  168. def __len__(self):
  169. return len(self.mapsets())
  170. def __str__(self):
  171. return self.name
  172. def __repr__(self):
  173. return 'Location(%r)' % self.name
  174. def mapsets(self, pattern=None, permissions=True):
  175. """Return a list of the available mapsets.
  176. :param pattern: the pattern to filter the result
  177. :type pattern: str
  178. :param permissions: check the permission of mapset
  179. :type permissions: bool
  180. :return: a list of mapset's names
  181. :rtype: list of strings
  182. ::
  183. >>> location = Location()
  184. >>> sorted(location.mapsets()) # doctest: +ELLIPSIS
  185. [...]
  186. """
  187. mapsets = [mapset for mapset in self]
  188. if permissions:
  189. mapsets = [mapset for mapset in mapsets
  190. if libgis.G_mapset_permissions(mapset)]
  191. if pattern:
  192. return fnmatch.filter(mapsets, pattern)
  193. return mapsets
  194. def path(self):
  195. """Return the complete path of the location"""
  196. return join(self.gisdbase, self.name)
  197. class Mapset(object):
  198. """Mapset ::
  199. >>> from grass.script.core import gisenv
  200. >>> genv = gisenv()
  201. >>> mapset = Mapset()
  202. >>> mapset # doctest: +ELLIPSIS
  203. Mapset(...)
  204. >>> mapset.gisdbase == genv['GISDBASE']
  205. True
  206. >>> mapset.location == genv['LOCATION_NAME']
  207. True
  208. >>> mapset.name == genv['MAPSET']
  209. True
  210. ..
  211. """
  212. def __init__(self, mapset='', location='', gisdbase=''):
  213. self.gisdbase = gisdbase
  214. self.location = location
  215. self.name = mapset
  216. self.visible = VisibleMapset(self.name, self.location, self.gisdbase)
  217. def _get_gisdb(self):
  218. return self._gisdb
  219. def _set_gisdb(self, gisdb):
  220. self._gisdb = _check_raise(gisdb, '', "GISDBASE")
  221. gisdbase = property(fget=_get_gisdb, fset=_set_gisdb,
  222. doc="Set or obtain the name of GISDBASE")
  223. def _get_loc(self):
  224. return self._loc
  225. def _set_loc(self, loc):
  226. self._loc = _check_raise(loc, self._gisdb, "LOCATION_NAME")
  227. location = property(fget=_get_loc, fset=_set_loc,
  228. doc="Set or obtain the name of LOCATION")
  229. def _get_name(self):
  230. return self._name
  231. def _set_name(self, name):
  232. self._name = _check_raise(name, join(self._gisdb, self._loc), "MAPSET")
  233. name = property(fget=_get_name, fset=_set_name,
  234. doc="Set or obtain the name of MAPSET")
  235. def __str__(self):
  236. return self.name
  237. def __repr__(self):
  238. return 'Mapset(%r)' % self.name
  239. def glist(self, type, pattern=None):
  240. """Return a list of grass types like:
  241. * 'group',
  242. * 'label',
  243. * 'raster',
  244. * 'raster_3d',
  245. * 'region',
  246. * 'vector',
  247. :param type: the type of element to query
  248. :type type: str
  249. :param pattern: the pattern to filter the result
  250. :type pattern: str
  251. ::
  252. >>> mapset = Mapset()
  253. >>> mapset.current()
  254. >>> rast = mapset.glist('raster')
  255. >>> test_raster_name in rast
  256. True
  257. >>> vect = mapset.glist('vector')
  258. >>> test_vector_name in vect
  259. True
  260. ..
  261. """
  262. if type not in ETYPE:
  263. str_err = "Type %s is not valid, valid types are: %s."
  264. raise TypeError(str_err % (type, ', '.join(ETYPE.keys())))
  265. clist = libgis.G_list(ETYPE[type], self.gisdbase,
  266. self.location, self.name)
  267. elist = []
  268. for el in clist:
  269. el_name = ct.cast(el, ct.c_char_p).value
  270. if el_name:
  271. elist.append(el_name)
  272. else:
  273. if pattern:
  274. return fnmatch.filter(elist, pattern)
  275. return elist
  276. def is_current(self):
  277. """Check if the MAPSET is the working MAPSET"""
  278. return (self.name == libgis.G_getenv('MAPSET') and
  279. self.location == libgis.G_getenv('LOCATION_NAME') and
  280. self.gisdbase == libgis.G_getenv('GISDBASE'))
  281. def current(self):
  282. """Set the mapset as current"""
  283. set_current_mapset(self.name, self.location, self.gisdbase)
  284. def delete(self):
  285. """Delete the mapset"""
  286. if self.is_current():
  287. raise GrassError('The mapset is in use.')
  288. shutil.rmtree(self.path())
  289. def path(self):
  290. """Return the complete path of the mapset"""
  291. return join(self.gisdbase, self.location, self.name)
  292. class VisibleMapset(object):
  293. """VisibleMapset object
  294. """
  295. def __init__(self, mapset, location='', gisdbase=''):
  296. self.mapset = mapset
  297. self.location = Location(location, gisdbase)
  298. self._list = []
  299. self.spath = join(self.location.path(), self.mapset, 'SEARCH_PATH')
  300. def __repr__(self):
  301. return repr(self.read())
  302. def __iter__(self):
  303. for mapset in self.read():
  304. yield mapset
  305. def read(self):
  306. """Return the mapsets in the search path"""
  307. with open(self.spath, "a+") as f:
  308. lines = f.readlines()
  309. if lines:
  310. return [l.strip() for l in lines]
  311. lns = ['PERMANENT', ]
  312. self._write(lns)
  313. return lns
  314. def _write(self, mapsets):
  315. """Write to SEARCH_PATH file the changes in the search path
  316. :param mapsets: a list of mapset's names
  317. :type mapsets: list
  318. """
  319. with open(self.spath, "w+") as f:
  320. ms = self.location.mapsets()
  321. f.write('%s' % '\n'.join([m for m in mapsets if m in ms]))
  322. def add(self, mapset):
  323. """Add a mapset to the search path
  324. :param mapset: a mapset's name
  325. :type mapset: str
  326. """
  327. if mapset not in self.read() and mapset in self.location:
  328. with open(self.spath, "a+") as f:
  329. f.write('\n%s' % mapset)
  330. else:
  331. raise TypeError('Mapset not found')
  332. def remove(self, mapset):
  333. """Remove mapset to the search path
  334. :param mapset: a mapset's name
  335. :type mapset: str
  336. """
  337. mapsets = self.read()
  338. mapsets.remove(mapset)
  339. self._write(mapsets)
  340. def extend(self, mapsets):
  341. """Add more mapsets to the search path
  342. :param mapsets: a list of mapset's names
  343. :type mapsets: list
  344. """
  345. ms = self.location.mapsets()
  346. final = self.read()
  347. final.extend([m for m in mapsets if m in ms and m not in final])
  348. self._write(final)
  349. def reset(self):
  350. """Reset to the original search path"""
  351. final = [self.mapset, 'PERMANENT']
  352. self._write(final)
  353. if __name__ == "__main__":
  354. import doctest
  355. from grass.pygrass import utils
  356. from grass.script.core import run_command
  357. test_vector_name = "Gis_test_vector"
  358. test_raster_name = "Gis_test_raster"
  359. utils.create_test_vector_map(test_vector_name)
  360. run_command("g.region", n=50, s=0, e=60, w=0, res=1)
  361. run_command("r.mapcalc", expression="%s = 1" % (test_raster_name),
  362. overwrite=True)
  363. run_command("g.region", n=40, s=0, e=40, w=0, res=2)
  364. doctest.testmod()
  365. # Remove the generated vector map, if exist
  366. mset = utils.get_mapset_vector(test_vector_name, mapset='')
  367. if mset:
  368. run_command("g.remove", flags='f', type='vector',
  369. name=test_vector_name)
  370. mset = utils.get_mapset_raster(test_raster_name, mapset='')
  371. if mset:
  372. run_command("g.remove", flags='f', type='raster',
  373. name=test_raster_name)