abstract.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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='0', overwrite=None,
  168. # parameters valid only if mode == 'w'
  169. tab_name='', tab_cols=[('cat', 'INTEGER PRIMARY KEY'), ],
  170. link_layer=1, link_name=None, link_key='cat',
  171. link_db='$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite.db',
  172. link_driver='sqlite'):
  173. """::
  174. >>> mun = Info('boundary_municp_sqlite')
  175. >>> mun.open()
  176. >>> mun.is_open()
  177. True
  178. >>> mun.close()
  179. ..
  180. """
  181. # check if map exists or not
  182. if not self.exist() and mode != 'w':
  183. raise OpenError("Map <%s> not found." % self._name)
  184. if libvect.Vect_set_open_level(self._topo_level) != 0:
  185. raise OpenError("Invalid access level.")
  186. # update the overwrite attribute
  187. self.overwrite = overwrite if overwrite is not None else self.overwrite
  188. # check if the mode is valid
  189. if mode not in ('r', 'rw', 'w'):
  190. raise ValueError("Mode not supported. Use one of: 'r', 'rw', 'w'.")
  191. # check if the map exist
  192. if self.exist() and mode == 'r':
  193. openvect = libvect.Vect_open_old2(self.c_mapinfo, self.name,
  194. self.mapset, layer)
  195. # If it is opened in write mode
  196. if mode == 'w':
  197. #TODO: build topo if new
  198. openvect = libvect.Vect_open_new(self.c_mapinfo, self.name,
  199. libvect.WITHOUT_Z)
  200. # create a link
  201. link = Link(link_layer,
  202. link_name if link_name else self.name,
  203. tab_name if tab_name else self.name,
  204. link_key, link_db, link_driver)
  205. self.dblinks = DBlinks(self.c_mapinfo)
  206. # add the new link
  207. self.dblinks.add(link)
  208. # get the table
  209. table = link.table()
  210. # create the new columns
  211. table.columns.create(tab_cols)
  212. self.n_lines = 0
  213. elif mode == 'rw':
  214. openvect = libvect.Vect_open_update2(self.c_mapinfo, self.name,
  215. self.mapset, layer)
  216. # initialize the dblinks object
  217. self.dblinks = DBlinks(self.c_mapinfo)
  218. # check the C function result.
  219. if openvect == -1:
  220. str_err = "Not able to open the map, C function return %d."
  221. raise OpenError(str_err % openvect)
  222. # istantiate the table
  223. self.layer = self.dblinks[0].layer
  224. self.table = self.get_table(layer=self.layer)
  225. self.writable = self.mapset == functions.getenv("MAPSET")
  226. if mode != 'w':
  227. self.n_lines = self.table.num_rows()
  228. def get_table(self, layer=None, name=None,):
  229. if layer is None and name is None and len(self.dblinks) == 0:
  230. return None
  231. if layer is not None:
  232. return self.dblinks.by_layer(layer).table()
  233. elif name is not None:
  234. return self.dblinks.by_name(name).table()
  235. else:
  236. return self.dblinks.by_layer(1).table()
  237. def close(self):
  238. self.table.conn.close()
  239. if self.is_open():
  240. if libvect.Vect_close(self.c_mapinfo) != 0:
  241. str_err = 'Error when trying to close the map with Vect_close'
  242. raise GrassError(str_err)
  243. if (self.c_mapinfo.contents.mode == libvect.GV_MODE_RW or
  244. self.c_mapinfo.contents.mode == libvect.GV_MODE_WRITE):
  245. self.build()
  246. def remove(self):
  247. """Remove vector map"""
  248. if self.is_open():
  249. self.close()
  250. functions.remove(vect=self.name)
  251. def build(self):
  252. """Close the vector map and build vector Topology"""
  253. self.close()
  254. libvect.Vect_set_open_level(1)
  255. if libvect.Vect_open_old2(self.c_mapinfo, self.name,
  256. self.mapset, '0') != 1:
  257. str_err = 'Error when trying to open the vector map.'
  258. raise GrassError(str_err)
  259. # Vect_build returns 1 on success and 0 on error (bool approach)
  260. if libvect.Vect_build(self.c_mapinfo) != 1:
  261. str_err = 'Error when trying build topology with Vect_build'
  262. raise GrassError(str_err)
  263. libvect.Vect_close(self.c_mapinfo)