abstract.py 13 KB

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