abstract.py 16 KB

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