abstract.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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 functions
  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. def is_open(c_mapinfo):
  15. """Return if the Vector is open"""
  16. return (c_mapinfo.contents.open != 0 and
  17. c_mapinfo.contents.open != libvect.VECT_CLOSED_CODE)
  18. #=============================================
  19. # VECTOR ABSTRACT CLASS
  20. #=============================================
  21. class Info(object):
  22. """Basic vector info.
  23. To get access to the vector info the map must be opened. ::
  24. >>> cens = Info('census')
  25. >>> cens.open()
  26. Then it is possible to read and write the following map attributes: ::
  27. >>> cens.organization
  28. 'NC OneMap'
  29. >>> cens.person
  30. 'hmitaso'
  31. >>> cens.title
  32. 'Wake County census blocks with attributes, clipped (polygon map)'
  33. >>> cens.map_date
  34. datetime.datetime(2007, 3, 19, 22, 1, 37)
  35. >>> cens.date
  36. ''
  37. >>> cens.scale
  38. 1
  39. >>> cens.comment
  40. ''
  41. >>> cens.comment = "One useful comment!"
  42. >>> cens.comment
  43. 'One useful comment!'
  44. >>> cens.zone
  45. 0
  46. >>> cens.proj
  47. 99
  48. There are some read only attributes: ::
  49. >>> cens.full_name
  50. 'census@PERMANENT'
  51. >>> cens.proj_name
  52. 'Lambert Conformal Conic'
  53. >>> cens.maptype
  54. 'native'
  55. And some basic methods: ::
  56. >>> cens.is_3D()
  57. False
  58. >>> cens.exist()
  59. True
  60. >>> cens.is_open()
  61. True
  62. >>> cens.close()
  63. """
  64. def __init__(self, name, mapset='', layer=None, mode='r', with_z=False):
  65. self._name = ''
  66. self._mapset = ''
  67. # Set map name and mapset
  68. self.name = name
  69. self.mapset = mapset
  70. self.c_mapinfo = ctypes.pointer(libvect.Map_info())
  71. self._topo_level = 1
  72. self._class_name = 'Vector'
  73. self.overwrite = False
  74. self.date_fmt = '%a %b %d %H:%M:%S %Y'
  75. self.layer = layer
  76. self.mode = mode
  77. self.with_z = with_z
  78. def __enter__(self, *args, **kwargs):
  79. self.open(*args, **kwargs)
  80. return self
  81. def __exit__(self, exc_type, exc_value, traceback):
  82. self.close()
  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 functions.is_clean_name(newname):
  89. str_err = _("Map name {0} not valid")
  90. raise ValueError(str_err.format(newname))
  91. if self.exist():
  92. self.rename(newname)
  93. self._name = newname
  94. name = property(fget=_get_name, fset=_set_name,
  95. doc="Set or obtain the Vector name")
  96. def _get_mapset(self):
  97. """Private method to obtain the Vector mapset"""
  98. return self._mapset
  99. def _set_mapset(self, mapset):
  100. """Private method to change the Vector mapset"""
  101. if mapset:
  102. self._mapset = mapset
  103. mapset = property(fget=_get_mapset, fset=_set_mapset,
  104. doc="Set or obtain the Vector mapset")
  105. def _get_organization(self):
  106. """Private method to obtain the Vector organization"""
  107. return libvect.Vect_get_organization(self.c_mapinfo)
  108. def _set_organization(self, org):
  109. """Private method to change the Vector organization"""
  110. libvect.Vect_get_organization(self.c_mapinfo, ctypes.c_char_p(org))
  111. organization = property(fget=_get_organization, fset=_set_organization,
  112. doc="Set or obtain the Vector organization")
  113. def _get_date(self):
  114. """Private method to obtain the Vector date"""
  115. return libvect.Vect_get_date(self.c_mapinfo)
  116. def _set_date(self, date):
  117. """Private method to change the Vector date"""
  118. return libvect.Vect_set_date(self.c_mapinfo, ctypes.c_char_p(date))
  119. date = property(fget=_get_date, fset=_set_date,
  120. doc="Set or obtain the Vector date")
  121. def _get_person(self):
  122. """Private method to obtain the Vector person"""
  123. return 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, ctypes.c_char_p(person))
  127. person = property(fget=_get_person, fset=_set_person,
  128. doc="Set or obtain the Vector author")
  129. def _get_title(self):
  130. """Private method to obtain the Vector title"""
  131. return libvect.Vect_get_map_name(self.c_mapinfo)
  132. def _set_title(self, title):
  133. """Private method to change the Vector title"""
  134. libvect.Vect_set_map_name(self.c_mapinfo, ctypes.c_char_p(title))
  135. title = property(fget=_get_title, fset=_set_title,
  136. doc="Set or obtain the Vector title")
  137. def _get_map_date(self):
  138. """Private method to obtain the Vector map date"""
  139. date_str = libvect.Vect_get_map_date(self.c_mapinfo)
  140. return datetime.datetime.strptime(date_str, self.date_fmt)
  141. def _set_map_date(self, datetimeobj):
  142. """Private method to change the Vector map date"""
  143. date_str = datetimeobj.strftime(self.date_fmt)
  144. libvect.Vect_set_map_date(self.c_mapinfo, ctypes.c_char_p(date_str))
  145. map_date = property(fget=_get_map_date, fset=_set_map_date,
  146. doc="Set or obtain the Vector map date")
  147. def _get_scale(self):
  148. """Private method to obtain the Vector scale"""
  149. return libvect.Vect_get_scale(self.c_mapinfo)
  150. def _set_scale(self, scale):
  151. """Private method to set the Vector scale"""
  152. return libvect.Vect_set_scale(self.c_mapinfo, ctypes.c_int(scale))
  153. scale = property(fget=_get_scale, fset=_set_scale,
  154. doc="Set or obtain the Vector scale")
  155. def _get_comment(self):
  156. """Private method to obtain the Vector comment"""
  157. return libvect.Vect_get_comment(self.c_mapinfo)
  158. def _set_comment(self, comm):
  159. """Private method to set the Vector comment"""
  160. return libvect.Vect_set_comment(self.c_mapinfo, ctypes.c_char_p(comm))
  161. comment = property(fget=_get_comment, fset=_set_comment,
  162. doc="Set or obtain the Vector comment")
  163. def _get_zone(self):
  164. """Private method to obtain the Vector projection zone"""
  165. return libvect.Vect_get_zone(self.c_mapinfo)
  166. def _set_zone(self, zone):
  167. """Private method to set the Vector projection zone"""
  168. return libvect.Vect_set_zone(self.c_mapinfo, ctypes.c_int(zone))
  169. zone = property(fget=_get_zone, fset=_set_zone,
  170. doc="Set or obtain the Vector projection zone")
  171. def _get_proj(self):
  172. """Private method to obtain the Vector projection code"""
  173. return libvect.Vect_get_proj(self.c_mapinfo)
  174. def _set_proj(self, proj):
  175. """Private method to set the Vector projection code"""
  176. libvect.Vect_set_proj(self.c_mapinfo, ctypes.c_int(proj))
  177. proj = property(fget=_get_proj, fset=_set_proj,
  178. doc="Set or obtain the Vector projection code")
  179. def _get_thresh(self):
  180. """Private method to obtain the Vector threshold"""
  181. return libvect.Vect_get_thresh(self.c_mapinfo)
  182. def _set_thresh(self, thresh):
  183. """Private method to set the Vector threshold"""
  184. return libvect.Vect_set_thresh(self.c_mapinfo, ctypes.c_double(thresh))
  185. thresh = property(fget=_get_thresh, fset=_set_thresh,
  186. doc="Set or obtain the Vector threshold")
  187. @property
  188. @must_be_open
  189. def full_name(self):
  190. """Return the full name of Vector"""
  191. return libvect.Vect_get_full_name(self.c_mapinfo)
  192. @property
  193. @must_be_open
  194. def maptype(self):
  195. """Return the map type of Vector"""
  196. return MAPTYPE[libvect.Vect_maptype(self.c_mapinfo)]
  197. @property
  198. @must_be_open
  199. def proj_name(self):
  200. """Return the project name of Vector"""
  201. return libvect.Vect_get_proj_name(self.c_mapinfo)
  202. def _write_header(self):
  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. functions.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 = functions.get_mapset_vector(self.name, self.mapset)
  223. self.mapset = mapset if mapset else ''
  224. return True if mapset else False
  225. return bool(functions.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. self.with_z = self.with_z if with_z is None else with_z
  269. with_z = libvect.WITH_Z if self.with_z else libvect.WITHOUT_Z
  270. # check if map exists or not
  271. if not self.exist() and self.mode != 'w':
  272. raise OpenError("Map <%s> not found." % self._name)
  273. if libvect.Vect_set_open_level(self._topo_level) != 0:
  274. raise OpenError("Invalid access level.")
  275. # update the overwrite attribute
  276. self.overwrite = overwrite if overwrite is not None else self.overwrite
  277. # check if the mode is valid
  278. if self.mode not in ('r', 'rw', 'w'):
  279. raise ValueError("Mode not supported. Use one of: 'r', 'rw', 'w'.")
  280. # check if the map exist
  281. if self.exist() and self.mode in ('r', 'rw'):
  282. # open in READ mode
  283. if self.mode == 'r':
  284. openvect = libvect.Vect_open_old2(self.c_mapinfo, self.name,
  285. self.mapset, str(layer))
  286. # open in READ and WRITE mode
  287. elif self.mode == 'rw':
  288. openvect = libvect.Vect_open_update2(self.c_mapinfo, self.name,
  289. self.mapset, str(layer))
  290. # instantiate class attributes
  291. self.dblinks = DBlinks(self.c_mapinfo)
  292. # If it is opened in write mode
  293. if self.mode == 'w':
  294. openvect = libvect.Vect_open_new(self.c_mapinfo, self.name, with_z)
  295. self.dblinks = DBlinks(self.c_mapinfo)
  296. if tab_cols:
  297. # create a link
  298. link = Link(layer,
  299. link_name if link_name else self.name,
  300. tab_name if tab_name else self.name,
  301. link_key, link_db, link_driver)
  302. # add the new link
  303. self.dblinks.add(link)
  304. # create the table
  305. table = link.table()
  306. table.create(tab_cols)
  307. table.conn.commit()
  308. # check the C function result.
  309. if openvect == -1:
  310. str_err = "Not able to open the map, C function return %d."
  311. raise OpenError(str_err % openvect)
  312. if len(self.dblinks) == 0:
  313. self.layer = layer
  314. self.table = None
  315. self.n_lines = 0
  316. else:
  317. self.layer = self.dblinks.by_layer(layer).layer
  318. self.table = self.dblinks.by_layer(layer).table()
  319. self.n_lines = self.table.n_rows()
  320. self.writable = self.mapset == functions.getenv("MAPSET")
  321. self.find = {'by_point': PointFinder(self.c_mapinfo, self.table,
  322. self.writable),
  323. 'by_box': BboxFinder(self.c_mapinfo, self.table,
  324. self.writable),
  325. 'by_polygon': PolygonFinder(self.c_mapinfo, self.table,
  326. self.writable), }
  327. def close(self, build=False):
  328. """Method to close the Vector
  329. :param build: True if the vector map should be build before close it
  330. :type build: bool
  331. """
  332. if hasattr(self, 'table') and self.table is not None:
  333. self.table.conn.close()
  334. if self.is_open():
  335. if libvect.Vect_close(self.c_mapinfo) != 0:
  336. str_err = 'Error when trying to close the map with Vect_close'
  337. raise GrassError(str_err)
  338. if ((self.c_mapinfo.contents.mode == libvect.GV_MODE_RW or
  339. self.c_mapinfo.contents.mode == libvect.GV_MODE_WRITE) and
  340. build):
  341. self.build()
  342. def remove(self):
  343. """Remove vector map"""
  344. if self.is_open():
  345. self.close()
  346. functions.remove(self.name, 'vect')
  347. def build(self):
  348. """Close the vector map and build vector Topology"""
  349. self.close()
  350. libvect.Vect_set_open_level(1)
  351. if libvect.Vect_open_old2(self.c_mapinfo, self.name,
  352. self.mapset, '0') != 1:
  353. str_err = 'Error when trying to open the vector map.'
  354. raise GrassError(str_err)
  355. # Vect_build returns 1 on success and 0 on error (bool approach)
  356. if libvect.Vect_build(self.c_mapinfo) != 1:
  357. str_err = 'Error when trying build topology with Vect_build'
  358. raise GrassError(str_err)
  359. libvect.Vect_close(self.c_mapinfo)