abstract.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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 vector_type import MAPTYPE
  10. from grass.pygrass import functions
  11. from grass.pygrass.errors import GrassError, OpenError, must_be_open
  12. from table import DBlinks, Link
  13. from 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'):
  65. self._name = None
  66. self._mapset = None
  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. def __enter__(self, *args, **kwargs):
  78. self.open(*args, **kwargs)
  79. return self
  80. def __exit__(self, exc_type, exc_value, traceback):
  81. self.close()
  82. def _get_name(self):
  83. """Private method to obtain the Vector name"""
  84. return self._name
  85. def _set_name(self, newname):
  86. """Private method to change the Vector name"""
  87. if not functions.is_clean_name(newname):
  88. str_err = _("Map name {0} not valid")
  89. raise ValueError(str_err.format(newname))
  90. if self.exist():
  91. self.rename(newname)
  92. self._name = newname
  93. name = property(fget=_get_name, fset=_set_name)
  94. def _get_mapset(self):
  95. """Private method to obtain the Vector name"""
  96. return self._mapset
  97. def _set_mapset(self, mapset):
  98. """Private method to change the Vector name"""
  99. if mapset:
  100. self._mapset = mapset
  101. else:
  102. self._mapset = ''
  103. mapset = property(fget=_get_mapset, fset=_set_mapset)
  104. def _get_organization(self):
  105. """Private method to obtain the Vector organization"""
  106. return libvect.Vect_get_organization(self.c_mapinfo)
  107. def _set_organization(self, org):
  108. """Private method to change the Vector organization"""
  109. libvect.Vect_get_organization(self.c_mapinfo, ctypes.c_char_p(org))
  110. organization = property(fget=_get_organization, fset=_set_organization)
  111. def _get_date(self):
  112. """Private method to obtain the Vector date"""
  113. return libvect.Vect_get_date(self.c_mapinfo)
  114. def _set_date(self, date):
  115. """Private method to change the Vector date"""
  116. return libvect.Vect_set_date(self.c_mapinfo, ctypes.c_char_p(date))
  117. date = property(fget=_get_date, fset=_set_date)
  118. def _get_person(self):
  119. """Private method to obtain the Vector person"""
  120. return libvect.Vect_get_person(self.c_mapinfo)
  121. def _set_person(self, person):
  122. """Private method to change the Vector person"""
  123. libvect.Vect_set_person(self.c_mapinfo, ctypes.c_char_p(person))
  124. person = property(fget=_get_person, fset=_set_person)
  125. def _get_title(self):
  126. """Private method to obtain the Vector title"""
  127. return 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, ctypes.c_char_p(title))
  131. title = property(fget=_get_title, fset=_set_title)
  132. def _get_map_date(self):
  133. """Private method to obtain the Vector map date"""
  134. date_str = libvect.Vect_get_map_date(self.c_mapinfo)
  135. return datetime.datetime.strptime(date_str, self.date_fmt)
  136. def _set_map_date(self, datetimeobj):
  137. """Private method to change the Vector map date"""
  138. date_str = datetimeobj.strftime(self.date_fmt)
  139. libvect.Vect_set_map_date(self.c_mapinfo, ctypes.c_char_p(date_str))
  140. map_date = property(fget=_get_map_date, fset=_set_map_date)
  141. def _get_scale(self):
  142. """Private method to obtain the Vector scale"""
  143. return libvect.Vect_get_scale(self.c_mapinfo)
  144. def _set_scale(self, scale):
  145. """Private method to set the Vector scale"""
  146. return libvect.Vect_set_scale(self.c_mapinfo, ctypes.c_int(scale))
  147. scale = property(fget=_get_scale, fset=_set_scale)
  148. def _get_comment(self):
  149. """Private method to obtain the Vector comment"""
  150. return libvect.Vect_get_comment(self.c_mapinfo)
  151. def _set_comment(self, comm):
  152. """Private method to set the Vector comment"""
  153. return libvect.Vect_set_comment(self.c_mapinfo, ctypes.c_char_p(comm))
  154. comment = property(fget=_get_comment, fset=_set_comment)
  155. def _get_zone(self):
  156. """Private method to obtain the Vector projection zone"""
  157. return libvect.Vect_get_zone(self.c_mapinfo)
  158. def _set_zone(self, zone):
  159. """Private method to set the Vector projection zone"""
  160. return libvect.Vect_set_zone(self.c_mapinfo, ctypes.c_int(zone))
  161. zone = property(fget=_get_zone, fset=_set_zone)
  162. def _get_proj(self):
  163. """Private method to obtain the Vector projection code"""
  164. return libvect.Vect_get_proj(self.c_mapinfo)
  165. def _set_proj(self, proj):
  166. """Private method to set the Vector projection code"""
  167. libvect.Vect_set_proj(self.c_mapinfo, ctypes.c_int(proj))
  168. proj = property(fget=_get_proj, fset=_set_proj)
  169. def _get_thresh(self):
  170. """Private method to obtain the Vector threshold"""
  171. return libvect.Vect_get_thresh(self.c_mapinfo)
  172. def _set_thresh(self, thresh):
  173. """Private method to set the Vector threshold"""
  174. return libvect.Vect_set_thresh(self.c_mapinfo, ctypes.c_double(thresh))
  175. thresh = property(fget=_get_thresh, fset=_set_thresh)
  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. libvect.Vect_write_header(self.c_mapinfo)
  193. def rename(self, newname):
  194. """Method to rename the Vector map"""
  195. if self.exist():
  196. if not self.is_open():
  197. functions.rename(self.name, newname, 'vect')
  198. else:
  199. raise GrassError("The map is open, not able to renamed it.")
  200. self._name = newname
  201. def is_3D(self):
  202. """Return if the Vector is 3D"""
  203. return bool(libvect.Vect_is_3d(self.c_mapinfo))
  204. def exist(self):
  205. """Return if the Vector exists or not"""
  206. if self.name:
  207. if self.mapset == '':
  208. mapset = functions.get_mapset_vector(self.name, self.mapset)
  209. self.mapset = mapset if mapset else ''
  210. return True if mapset else False
  211. return bool(functions.get_mapset_vector(self.name, self.mapset))
  212. else:
  213. return False
  214. def is_open(self):
  215. """Return if the Vector is open"""
  216. return is_open(self.c_mapinfo)
  217. def open(self, mode=None, layer=1, overwrite=None,
  218. # parameters valid only if mode == 'w'
  219. tab_name='', tab_cols=None, link_name=None, link_key='cat',
  220. link_db='$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db',
  221. link_driver='sqlite'):
  222. """Open a Vector map.
  223. Parameters
  224. ----------
  225. mode : string
  226. Open a vector map in ``r`` in reading, ``w`` in writing and
  227. in ``rw`` read and write mode
  228. layer: int, optional
  229. Specify the layer that you want to use
  230. Some parameters are valid only if we open use the writing mode (``w``)
  231. overwrite: bool, optional
  232. valid only for ``w`` mode
  233. tab_name: string, optional
  234. Define the name of the table that will be generate
  235. tab_cols: list of pairs, optional
  236. Define the name and type of the columns of the attribute table
  237. of the vecto map
  238. link_name: string, optional
  239. Define the name of the link connecttion with the database
  240. link_key: string, optional
  241. Define the nema of the column that will be use as vector category
  242. link_db: string, optional
  243. Define the database connection parameters
  244. link_driver: string, optional
  245. Define witch database driver will be used
  246. See more examples in the documentation of the ``read`` and ``write``
  247. methods.
  248. """
  249. self.mode = mode if mode else self.mode
  250. # check if map exists or not
  251. if not self.exist() and self.mode != 'w':
  252. raise OpenError("Map <%s> not found." % self._name)
  253. if libvect.Vect_set_open_level(self._topo_level) != 0:
  254. raise OpenError("Invalid access level.")
  255. # update the overwrite attribute
  256. self.overwrite = overwrite if overwrite is not None else self.overwrite
  257. # check if the mode is valid
  258. if self.mode not in ('r', 'rw', 'w'):
  259. raise ValueError("Mode not supported. Use one of: 'r', 'rw', 'w'.")
  260. # check if the map exist
  261. if self.exist() and self.mode in ('r', 'rw'):
  262. # open in READ mode
  263. if self.mode == 'r':
  264. openvect = libvect.Vect_open_old2(self.c_mapinfo, self.name,
  265. self.mapset, str(layer))
  266. # open in READ and WRITE mode
  267. elif self.mode == 'rw':
  268. openvect = libvect.Vect_open_update2(self.c_mapinfo, self.name,
  269. self.mapset, str(layer))
  270. # instantiate class attributes
  271. self.dblinks = DBlinks(self.c_mapinfo)
  272. # If it is opened in write mode
  273. if self.mode == 'w':
  274. openvect = libvect.Vect_open_new(self.c_mapinfo, self.name,
  275. libvect.WITHOUT_Z)
  276. self.dblinks = DBlinks(self.c_mapinfo)
  277. if tab_cols:
  278. # create a link
  279. link = Link(layer,
  280. link_name if link_name else self.name,
  281. tab_name if tab_name else self.name,
  282. link_key, link_db, link_driver)
  283. # add the new link
  284. self.dblinks.add(link)
  285. # create the table
  286. table = link.table()
  287. table.create(tab_cols)
  288. table.conn.commit()
  289. # check the C function result.
  290. if openvect == -1:
  291. str_err = "Not able to open the map, C function return %d."
  292. raise OpenError(str_err % openvect)
  293. if len(self.dblinks) == 0:
  294. self.layer = layer
  295. self.table = None
  296. self.n_lines = 0
  297. else:
  298. self.layer = self.dblinks.by_layer(layer).layer
  299. self.table = self.dblinks.by_layer(layer).table()
  300. self.n_lines = self.table.n_rows()
  301. self.writable = self.mapset == functions.getenv("MAPSET")
  302. self.find = {'by_point': PointFinder(self.c_mapinfo, self.table,
  303. self.writable),
  304. 'by_box': BboxFinder(self.c_mapinfo, self.table,
  305. self.writable),
  306. 'by_polygon': PolygonFinder(self.c_mapinfo, self.table,
  307. self.writable), }
  308. def close(self, build=False):
  309. """Method to close the Vector"""
  310. if hasattr(self, 'table') and self.table is not None:
  311. self.table.conn.close()
  312. if self.is_open():
  313. if libvect.Vect_close(self.c_mapinfo) != 0:
  314. str_err = 'Error when trying to close the map with Vect_close'
  315. raise GrassError(str_err)
  316. if ((self.c_mapinfo.contents.mode == libvect.GV_MODE_RW or
  317. self.c_mapinfo.contents.mode == libvect.GV_MODE_WRITE) and
  318. build):
  319. self.build()
  320. def remove(self):
  321. """Remove vector map"""
  322. if self.is_open():
  323. self.close()
  324. functions.remove(self.name, 'vect')
  325. def build(self):
  326. """Close the vector map and build vector Topology"""
  327. self.close()
  328. libvect.Vect_set_open_level(1)
  329. if libvect.Vect_open_old2(self.c_mapinfo, self.name,
  330. self.mapset, '0') != 1:
  331. str_err = 'Error when trying to open the vector map.'
  332. raise GrassError(str_err)
  333. # Vect_build returns 1 on success and 0 on error (bool approach)
  334. if libvect.Vect_build(self.c_mapinfo) != 1:
  335. str_err = 'Error when trying build topology with Vect_build'
  336. raise GrassError(str_err)
  337. libvect.Vect_close(self.c_mapinfo)