abstract.py 15 KB

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