abstract.py 12 KB

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