abstract.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Fri Aug 17 17:24:03 2012
  4. @author: pietro
  5. """
  6. import ctypes
  7. import datetime
  8. import grass.lib.vector as libvect
  9. from grass.pygrass.vector.vector_type import MAPTYPE
  10. from grass.pygrass import utils
  11. from grass.pygrass.errors import must_be_open
  12. from grass.pygrass.vector.table import DBlinks, Link
  13. from grass.pygrass.vector.find import PointFinder, BboxFinder, PolygonFinder
  14. from grass.exceptions import GrassError, OpenError
  15. test_vector_name = "abstract_doctest_map"
  16. def is_open(c_mapinfo):
  17. """Return if the Vector is open"""
  18. return (c_mapinfo.contents.open != 0 and
  19. c_mapinfo.contents.open != libvect.VECT_CLOSED_CODE)
  20. #=============================================
  21. # VECTOR ABSTRACT CLASS
  22. #=============================================
  23. class Info(object):
  24. """Basic vector info.
  25. To get access to the vector info the map must be opened. ::
  26. >>> test_vect = Info(test_vector_name)
  27. >>> test_vect.open(mode='r')
  28. Then it is possible to read and write the following map attributes: ::
  29. >>> test_vect.organization
  30. 'Thuenen Institut'
  31. >>> test_vect.person
  32. 'Soeren Gebbert'
  33. >>> test_vect.title
  34. 'Test dataset'
  35. >>> test_vect.scale
  36. 1
  37. >>> test_vect.comment
  38. 'This is a comment'
  39. >>> test_vect.comment = "One useful comment!"
  40. >>> test_vect.comment
  41. 'One useful comment!'
  42. There are some read only attributes: ::
  43. >>> test_vect.maptype
  44. 'native'
  45. And some basic methods: ::
  46. >>> test_vect.is_3D()
  47. False
  48. >>> test_vect.exist()
  49. True
  50. >>> test_vect.is_open()
  51. True
  52. >>> test_vect.close()
  53. """
  54. def __init__(self, name, mapset='', *aopen, **kwopen):
  55. self._name = ''
  56. self._mapset = ''
  57. # Set map name and mapset
  58. self.name = name
  59. self.mapset = mapset
  60. self._aopen = aopen
  61. self._kwopen = kwopen
  62. self.c_mapinfo = ctypes.pointer(libvect.Map_info())
  63. self._topo_level = 1
  64. self._class_name = 'Vector'
  65. self._mode = 'r'
  66. self.overwrite = False
  67. self.date_fmt = '%a %b %d %H:%M:%S %Y'
  68. def __enter__(self):
  69. self.open(*self._aopen, **self._kwopen)
  70. return self
  71. def __exit__(self, exc_type, exc_value, traceback):
  72. self.close()
  73. def _get_mode(self):
  74. return self._mode
  75. def _set_mode(self, mode):
  76. if mode.upper() not in 'RW':
  77. str_err = _("Mode type: {0} not supported ('r', 'w')")
  78. raise ValueError(str_err.format(mode))
  79. self._mode = mode
  80. mode = property(fget=_get_mode, fset=_set_mode)
  81. def _get_name(self):
  82. """Private method to obtain the Vector name"""
  83. return self._name
  84. def _set_name(self, newname):
  85. """Private method to change the Vector name"""
  86. if not utils.is_clean_name(newname):
  87. str_err = _("Map name {0} not valid")
  88. raise ValueError(str_err.format(newname))
  89. self._name = newname
  90. name = property(fget=_get_name, fset=_set_name,
  91. doc="Set or obtain the Vector name")
  92. def _get_mapset(self):
  93. """Private method to obtain the Vector mapset"""
  94. return self._mapset
  95. def _set_mapset(self, mapset):
  96. """Private method to change the Vector mapset"""
  97. if mapset:
  98. self._mapset = mapset
  99. mapset = property(fget=_get_mapset, fset=_set_mapset,
  100. doc="Set or obtain the Vector mapset")
  101. def _get_organization(self):
  102. """Private method to obtain the Vector organization"""
  103. return utils.decode(libvect.Vect_get_organization(self.c_mapinfo))
  104. def _set_organization(self, org):
  105. """Private method to change the Vector organization"""
  106. libvect.Vect_set_organization(self.c_mapinfo, org)
  107. organization = property(fget=_get_organization, fset=_set_organization,
  108. doc="Set or obtain the Vector organization")
  109. def _get_date(self):
  110. """Private method to obtain the Vector date"""
  111. return utils.decode(libvect.Vect_get_date(self.c_mapinfo))
  112. def _set_date(self, date):
  113. """Private method to change the Vector date"""
  114. return libvect.Vect_set_date(self.c_mapinfo, date)
  115. date = property(fget=_get_date, fset=_set_date,
  116. doc="Set or obtain the Vector date")
  117. def _get_person(self):
  118. """Private method to obtain the Vector person"""
  119. return utils.decode(libvect.Vect_get_person(self.c_mapinfo))
  120. def _set_person(self, person):
  121. """Private method to change the Vector person"""
  122. libvect.Vect_set_person(self.c_mapinfo, person)
  123. person = property(fget=_get_person, fset=_set_person,
  124. doc="Set or obtain the Vector author")
  125. def _get_title(self):
  126. """Private method to obtain the Vector title"""
  127. return utils.decode(libvect.Vect_get_map_name(self.c_mapinfo))
  128. def _set_title(self, title):
  129. """Private method to change the Vector title"""
  130. libvect.Vect_set_map_name(self.c_mapinfo, title)
  131. title = property(fget=_get_title, fset=_set_title,
  132. doc="Set or obtain the Vector title")
  133. def _get_map_date(self):
  134. """Private method to obtain the Vector map date"""
  135. date_str = utils.decode(libvect.Vect_get_map_date(self.c_mapinfo))
  136. try:
  137. return datetime.datetime.strptime(date_str, self.date_fmt)
  138. except:
  139. return date_str
  140. def _set_map_date(self, datetimeobj):
  141. """Private method to change the Vector map date"""
  142. date_str = datetimeobj.strftime(self.date_fmt)
  143. libvect.Vect_set_map_date(self.c_mapinfo, date_str)
  144. map_date = property(fget=_get_map_date, fset=_set_map_date,
  145. doc="Set or obtain the Vector map date")
  146. def _get_scale(self):
  147. """Private method to obtain the Vector scale"""
  148. return libvect.Vect_get_scale(self.c_mapinfo)
  149. def _set_scale(self, scale):
  150. """Private method to set the Vector scale"""
  151. return libvect.Vect_set_scale(self.c_mapinfo, ctypes.c_int(scale))
  152. scale = property(fget=_get_scale, fset=_set_scale,
  153. doc="Set or obtain the Vector scale")
  154. def _get_comment(self):
  155. """Private method to obtain the Vector comment"""
  156. return utils.decode(libvect.Vect_get_comment(self.c_mapinfo))
  157. def _set_comment(self, comm):
  158. """Private method to set the Vector comment"""
  159. return libvect.Vect_set_comment(self.c_mapinfo, comm)
  160. comment = property(fget=_get_comment, fset=_set_comment,
  161. doc="Set or obtain the Vector comment")
  162. def _get_zone(self):
  163. """Private method to obtain the Vector projection zone"""
  164. return libvect.Vect_get_zone(self.c_mapinfo)
  165. def _set_zone(self, zone):
  166. """Private method to set the Vector projection zone"""
  167. return libvect.Vect_set_zone(self.c_mapinfo, ctypes.c_int(zone))
  168. zone = property(fget=_get_zone, fset=_set_zone,
  169. doc="Set or obtain the Vector projection zone")
  170. def _get_proj(self):
  171. """Private method to obtain the Vector projection code"""
  172. return libvect.Vect_get_proj(self.c_mapinfo)
  173. def _set_proj(self, proj):
  174. """Private method to set the Vector projection code"""
  175. libvect.Vect_set_proj(self.c_mapinfo, ctypes.c_int(proj))
  176. proj = property(fget=_get_proj, fset=_set_proj,
  177. doc="Set or obtain the Vector projection code")
  178. def _get_thresh(self):
  179. """Private method to obtain the Vector threshold"""
  180. return libvect.Vect_get_thresh(self.c_mapinfo)
  181. def _set_thresh(self, thresh):
  182. """Private method to set the Vector threshold"""
  183. return libvect.Vect_set_thresh(self.c_mapinfo, ctypes.c_double(thresh))
  184. thresh = property(fget=_get_thresh, fset=_set_thresh,
  185. doc="Set or obtain the Vector threshold")
  186. @property
  187. @must_be_open
  188. def full_name(self):
  189. """Return the full name of Vector"""
  190. return libvect.Vect_get_full_name(self.c_mapinfo)
  191. @property
  192. @must_be_open
  193. def maptype(self):
  194. """Return the map type of Vector"""
  195. return MAPTYPE[libvect.Vect_maptype(self.c_mapinfo)]
  196. @property
  197. @must_be_open
  198. def proj_name(self):
  199. """Return the project name of Vector"""
  200. return libvect.Vect_get_proj_name(self.c_mapinfo)
  201. def write_header(self):
  202. """Save the change in the C struct permanently to disk."""
  203. libvect.Vect_write_header(self.c_mapinfo)
  204. def rename(self, newname):
  205. """Method to rename the Vector map
  206. :param newname: the new name for the Vector map
  207. :type newname: str
  208. """
  209. if self.exist():
  210. if not self.is_open():
  211. utils.rename(self.name, newname, 'vect')
  212. else:
  213. raise GrassError("The map is open, not able to renamed it.")
  214. self._name = newname
  215. def is_3D(self):
  216. """Return if the Vector is 3D"""
  217. return bool(libvect.Vect_is_3d(self.c_mapinfo))
  218. def exist(self):
  219. """Return if the Vector exists or not"""
  220. if self.name:
  221. if self.mapset == '':
  222. mapset = utils.get_mapset_vector(self.name, self.mapset)
  223. self.mapset = mapset if mapset else ''
  224. return True if mapset else False
  225. return bool(utils.get_mapset_vector(self.name, self.mapset))
  226. else:
  227. return False
  228. def is_open(self):
  229. """Return if the Vector is open"""
  230. return is_open(self.c_mapinfo)
  231. def open(self, mode=None, layer=1, overwrite=None, with_z=None,
  232. # parameters valid only if mode == 'w'
  233. tab_name='', tab_cols=None, link_name=None, link_key='cat',
  234. link_db='$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db',
  235. link_driver='sqlite'):
  236. """Open a Vector map.
  237. :param mode: open a vector map in ``r`` in reading, ``w`` in writing
  238. and in ``rw`` read and write mode
  239. :type mode: str
  240. :param layer: specify the layer that you want to use
  241. :type layer: int
  242. :param overwrite: valid only for ``w`` mode
  243. :type overwrite: bool
  244. :param with_z: specify if vector map must be open with third dimension
  245. enabled or not. Valid only for ``w`` mode,
  246. default: False
  247. :type with_z: bool
  248. :param tab_name: define the name of the table that will be generate
  249. :type tab_name: str
  250. :param tab_cols: define the name and type of the columns of the
  251. attribute table of the vecto map
  252. :type tab_cols: list of pairs
  253. :param link_name: define the name of the link connecttion with the
  254. database
  255. :type link_name: str
  256. :param link_key: define the nema of the column that will be use as
  257. vector category
  258. :type link_key: str
  259. :param link_db: define the database connection parameters
  260. :type link_db: str
  261. :param link_driver: define witch database driver will be used
  262. :param link_driver: str
  263. Some of the parameters are valid only with mode ``w`` or ``rw``
  264. See more examples in the documentation of the ``read`` and ``write``
  265. methods
  266. """
  267. self.mode = mode if mode else self.mode
  268. with_z = libvect.WITH_Z if with_z else libvect.WITHOUT_Z
  269. # check if map exists or not
  270. if not self.exist() and self.mode != 'w':
  271. raise OpenError("Map <%s> not found." % self._name)
  272. if libvect.Vect_set_open_level(self._topo_level) != 0:
  273. raise OpenError("Invalid access level.")
  274. # update the overwrite attribute
  275. self.overwrite = overwrite if overwrite is not None else self.overwrite
  276. # check if the mode is valid
  277. if self.mode not in ('r', 'rw', 'w'):
  278. raise ValueError("Mode not supported. Use one of: 'r', 'rw', 'w'.")
  279. # check if the map exist
  280. if self.exist() and self.mode in ('r', 'rw'):
  281. # open in READ mode
  282. if self.mode == 'r':
  283. openvect = libvect.Vect_open_old2(self.c_mapinfo, self.name,
  284. self.mapset, str(layer))
  285. # open in READ and WRITE mode
  286. elif self.mode == 'rw':
  287. openvect = libvect.Vect_open_update2(self.c_mapinfo, self.name,
  288. self.mapset, str(layer))
  289. # instantiate class attributes
  290. self.dblinks = DBlinks(self.c_mapinfo)
  291. # If it is opened in write mode
  292. if self.mode == 'w':
  293. openvect = libvect.Vect_open_new(self.c_mapinfo, self.name, with_z)
  294. self.dblinks = DBlinks(self.c_mapinfo)
  295. if self.mode in ('w', 'rw') and tab_cols:
  296. # create a link
  297. link = Link(layer,
  298. link_name if link_name else self.name,
  299. tab_name if tab_name else self.name,
  300. link_key, link_db, link_driver)
  301. # add the new link
  302. self.dblinks.add(link)
  303. # create the table
  304. table = link.table()
  305. table.create(tab_cols, overwrite=overwrite)
  306. table.conn.commit()
  307. # check the C function result.
  308. if openvect == -1:
  309. str_err = "Not able to open the map, C function return %d."
  310. raise OpenError(str_err % openvect)
  311. if len(self.dblinks) == 0:
  312. self.layer = layer
  313. self.table = None
  314. self.n_lines = 0
  315. else:
  316. self.layer = self.dblinks.by_layer(layer).layer
  317. self.table = self.dblinks.by_layer(layer).table()
  318. self.n_lines = self.table.n_rows()
  319. self.writeable = self.mapset == utils.getenv("MAPSET")
  320. # Initialize the finder
  321. self.find = {'by_point': PointFinder(self.c_mapinfo, self.table,
  322. self.writeable),
  323. 'by_bbox': BboxFinder(self.c_mapinfo, self.table,
  324. self.writeable),
  325. 'by_polygon': PolygonFinder(self.c_mapinfo, self.table,
  326. self.writeable), }
  327. self.find_by_point = self.find["by_point"]
  328. self.find_by_bbox = self.find["by_bbox"]
  329. self.find_by_polygon = self.find["by_polygon"]
  330. def close(self, build=False):
  331. """Method to close the Vector
  332. :param build: True if the vector map should be build before close it
  333. :type build: bool
  334. """
  335. if hasattr(self, 'table') and self.table is not None:
  336. self.table.conn.close()
  337. if self.is_open():
  338. if libvect.Vect_close(self.c_mapinfo) != 0:
  339. str_err = 'Error when trying to close the map with Vect_close'
  340. raise GrassError(str_err)
  341. if ((self.c_mapinfo.contents.mode == libvect.GV_MODE_RW or
  342. self.c_mapinfo.contents.mode == libvect.GV_MODE_WRITE) and
  343. build):
  344. self.build()
  345. def remove(self):
  346. """Remove vector map"""
  347. if self.is_open():
  348. self.close()
  349. utils.remove(self.name, 'vect')
  350. def build(self):
  351. """Close the vector map and build vector Topology"""
  352. self.close()
  353. libvect.Vect_set_open_level(1)
  354. if libvect.Vect_open_old2(self.c_mapinfo, self.name,
  355. self.mapset, '0') != 1:
  356. str_err = 'Error when trying to open the vector map.'
  357. raise GrassError(str_err)
  358. # Vect_build returns 1 on success and 0 on error (bool approach)
  359. if libvect.Vect_build(self.c_mapinfo) != 1:
  360. str_err = 'Error when trying build topology with Vect_build'
  361. raise GrassError(str_err)
  362. libvect.Vect_close(self.c_mapinfo)
  363. if __name__ == "__main__":
  364. import doctest
  365. utils.create_test_vector_map(test_vector_name)
  366. doctest.testmod()