abstract.py 12 KB

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