__init__.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Tue Jul 17 08:51:53 2012
  4. @author: pietro
  5. """
  6. import ctypes
  7. import grass.lib.vector as libvect
  8. from vector_type import VTYPE, GV_TYPE
  9. #
  10. # import pygrass modules
  11. #
  12. from pygrass.errors import GrassError
  13. import geometry
  14. from abstract import Info
  15. from basic import Bbox
  16. import grass.script.core as core
  17. _GRASSENV = core.gisenv()
  18. _NUMOF = {"areas": libvect.Vect_get_num_areas,
  19. "dblinks": libvect.Vect_get_num_dblinks,
  20. "faces": libvect.Vect_get_num_faces,
  21. "holes": libvect.Vect_get_num_holes,
  22. "islands": libvect.Vect_get_num_islands,
  23. "kernels": libvect.Vect_get_num_kernels,
  24. "lines": libvect.Vect_get_num_line_points,
  25. "points": libvect.Vect_get_num_lines,
  26. "nodes": libvect.Vect_get_num_nodes,
  27. "updated_lines": libvect.Vect_get_num_updated_lines,
  28. "updated_nodes": libvect.Vect_get_num_updated_nodes,
  29. "volumes": libvect.Vect_get_num_volumes}
  30. _GEOOBJ = {"areas": geometry.Area,
  31. "dblinks": None,
  32. "faces": None,
  33. "holes": None,
  34. "islands": geometry.Isle,
  35. "kernels": None,
  36. "line_points": None,
  37. "points": geometry.Point,
  38. "lines": geometry.Line,
  39. "nodes": geometry.Node,
  40. "volumes": None}
  41. #=============================================
  42. # VECTOR
  43. #=============================================
  44. class Vector(Info):
  45. """ ::
  46. >>> from pygrass.vector import Vector
  47. >>> municip = Vector('boundary_municp_sqlite')
  48. >>> municip.is_open()
  49. False
  50. >>> municip.mapset
  51. ''
  52. >>> municip.exist()
  53. True
  54. >>> municip.mapset
  55. '%s'
  56. >>> municip.overwrite
  57. False
  58. ..
  59. """ % _GRASSENV['MAPSET']
  60. def __init__(self, name, mapset=''):
  61. # Set map name and mapset
  62. super(Vector, self).__init__(name, mapset)
  63. self._topo_level = 1
  64. self._class_name = 'Vector'
  65. self.overwrite = False
  66. def __repr__(self):
  67. if self.exist():
  68. return "%s(%r, %r)" % (self._class_name, self.name, self.mapset)
  69. else:
  70. return "%s(%r)" % (self._class_name, self.name)
  71. def __iter__(self):
  72. """::
  73. >>> mun = Vector('boundary_municp_sqlite')
  74. >>> mun.open()
  75. >>> features = [feature for feature in mun]
  76. >>> features[:3]
  77. [Boundary(v_id=None), Boundary(v_id=None), Boundary(v_id=None)]
  78. >>> mun.close()
  79. ..
  80. """
  81. #return (self.read(f_id) for f_id in xrange(self.num_of_features()))
  82. return self
  83. def next(self):
  84. """::
  85. >>> mun = Vector('boundary_municp_sqlite')
  86. >>> mun.open()
  87. >>> mun.next()
  88. Boundary(v_id=None)
  89. >>> mun.next()
  90. Boundary(v_id=None)
  91. >>> mun.close()
  92. ..
  93. """
  94. v_id = self.c_mapinfo.contents.next_line
  95. v_id = v_id if v_id != 0 else None
  96. c_points = ctypes.pointer(libvect.line_pnts())
  97. c_cats = ctypes.pointer(libvect.line_cats())
  98. ftype = libvect.Vect_read_next_line(self.c_mapinfo, c_points, c_cats)
  99. if ftype == -2:
  100. raise StopIteration()
  101. if ftype == -1:
  102. raise
  103. #if GV_TYPE[ftype]['obj'] is not None:
  104. return GV_TYPE[ftype]['obj'](v_id=v_id,
  105. c_mapinfo=self.c_mapinfo,
  106. c_points=c_points,
  107. c_cats=c_cats)
  108. def rewind(self):
  109. if libvect.Vect_rewind(self.c_mapinfo) == -1:
  110. raise GrassError("Vect_rewind raise an error.")
  111. def write(self, geo_obj):
  112. """::
  113. >>> mun = Vector('boundary_municp_sqlite') #doctest: +SKIP
  114. >>> mun.open(mode='rw') #doctest: +SKIP
  115. >>> feature1 = mun.read(1) #doctest: +SKIP
  116. >>> feature1 #doctest: +SKIP
  117. Boundary(v_id=1)
  118. >>> feature1[:3] #doctest: +SKIP +NORMALIZE_WHITESPACE
  119. [Point(463718.874987, 310970.844494),
  120. Point(463707.405987, 310989.499494),
  121. Point(463714.593986, 311084.281494)]
  122. >>> from geometry import Point #doctest: +SKIP
  123. >>> feature1.insert(1, Point(463713.000000, 310980.000000))
  124. ... #doctest: +SKIP
  125. >>> feature1[:4] #doctest: +SKIP +NORMALIZE_WHITESPACE
  126. [Point(463718.874987, 310970.844494),
  127. Point(463713.000000, 310980.000000),
  128. Point(463707.405987, 310989.499494),
  129. Point(463714.593986, 311084.281494)]
  130. >>> mun.write(feature1) #doctest: +SKIP
  131. >>> feature1 #doctest: +SKIP
  132. Boundary(v_id=8708)
  133. >>> mun.close() #doctest: +SKIP
  134. ..
  135. """
  136. result = libvect.Vect_write_line(self.c_mapinfo, geo_obj.gtype,
  137. geo_obj.c_points, geo_obj.c_cats)
  138. if result == -1:
  139. raise GrassError("Not able to write the vector feature.")
  140. if self._topo_level == 2:
  141. # return new feature id (on level 2)
  142. geo_obj.id = result
  143. else:
  144. # return offset into file where the feature starts (on level 1)
  145. geo_obj.offset = result
  146. #=============================================
  147. # VECTOR WITH TOPOLOGY
  148. #=============================================
  149. class VectorTopo(Vector):
  150. def __init__(self, name, mapset=''):
  151. super(VectorTopo, self).__init__(name, mapset)
  152. self._topo_level = 2
  153. self._class_name = 'VectorTopo'
  154. def __len__(self):
  155. return libvect.Vect_get_num_lines(self.c_mapinfo)
  156. def __getitem__(self, key):
  157. """::
  158. >>> mun = VectorTopo('boundary_municp_sqlite')
  159. >>> mun.open()
  160. >>> mun[:3]
  161. [Boundary(v_id=1), Boundary(v_id=2), Boundary(v_id=3)]
  162. >>> mun.close()
  163. ..
  164. """
  165. if isinstance(key, slice):
  166. #import pdb; pdb.set_trace()
  167. #Get the start, stop, and step from the slice
  168. return [self.read(indx + 1)
  169. for indx in xrange(*key.indices(len(self)))]
  170. elif isinstance(key, int):
  171. self.read(key)
  172. else:
  173. raise ValueError("Invalid argument type: %r." % key)
  174. def num_primitive_of(self, primitive):
  175. """Primitive are:
  176. * "boundary",
  177. * "centroid",
  178. * "face",
  179. * "kernel",
  180. * "line",
  181. * "point"
  182. ::
  183. >>> municip = VectorTopo('boundary_municp_sqlite')
  184. >>> municip.open()
  185. >>> municip.num_primitive_of('point')
  186. 0
  187. >>> municip.num_primitive_of('line')
  188. 0
  189. >>> municip.num_primitive_of('centroid')
  190. 3579
  191. >>> municip.num_primitive_of('boundary')
  192. 5128
  193. >>> municip.close()
  194. ..
  195. """
  196. return libvect.Vect_get_num_primitives(self.c_mapinfo,
  197. VTYPE[primitive])
  198. def number_of(self, vtype):
  199. """
  200. vtype in ["areas", "dblinks", "faces", "holes", "islands", "kernels",
  201. "line_points", "lines", "nodes", "update_lines",
  202. "update_nodes", "volumes"]
  203. >>> municip = VectorTopo('boundary_municp_sqlite')
  204. >>> municip.open()
  205. >>> municip.number_of("areas")
  206. 3579
  207. >>> municip.number_of("islands")
  208. 2629
  209. >>> municip.number_of("holes")
  210. 0
  211. >>> municip.number_of("lines")
  212. 8707
  213. >>> municip.number_of("nodes")
  214. 4178
  215. >>> municip.number_of("pizza")
  216. ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
  217. Traceback (most recent call last):
  218. ...
  219. ValueError: vtype not supported, use one of:
  220. 'areas', 'dblinks', 'faces', 'holes', 'islands', 'kernels',
  221. 'line_points', 'lines', 'nodes', 'updated_lines', 'updated_nodes',
  222. 'volumes'
  223. >>> municip.close()
  224. ..
  225. """
  226. if vtype in _NUMOF.keys():
  227. return _NUMOF[vtype](self.c_mapinfo)
  228. else:
  229. keys = "', '".join(sorted(_NUMOF.keys()))
  230. raise ValueError("vtype not supported, use one of: '%s'" % keys)
  231. def viter(self, vtype):
  232. """Return an iterator of vector features
  233. ::
  234. >>> municip = VectorTopo('boundary_municp_sqlite')
  235. >>> municip.open()
  236. >>> big = [area for area in municip.viter('areas')
  237. ... if area.alive() and area.area >= 10000]
  238. >>> big[:3]
  239. [Area(1), Area(2), Area(3)]
  240. to sort the result in a efficient way, use: ::
  241. >>> from operator import methodcaller as method
  242. >>> big.sort(key = method('area'), reverse = True) # sort the list
  243. >>> for area in big[:3]:
  244. ... print area, area.area()
  245. Area(3102) 697521857.848
  246. Area(2682) 320224369.66
  247. Area(2552) 298356117.948
  248. >>> municip.close()
  249. ..
  250. """
  251. if vtype in _GEOOBJ.keys():
  252. if _GEOOBJ[vtype] is not None:
  253. return (_GEOOBJ[vtype](v_id=indx, c_mapinfo=self.c_mapinfo)
  254. for indx in xrange(1, self.number_of(vtype) + 1))
  255. else:
  256. keys = "', '".join(sorted(_GEOOBJ.keys()))
  257. raise ValueError("vtype not supported, use one of: '%s'" % keys)
  258. def rewind(self):
  259. """Rewind vector map to cause reads to start at beginning. ::
  260. >>> mun = VectorTopo('boundary_municp_sqlite')
  261. >>> mun.open()
  262. >>> mun.next()
  263. Boundary(v_id=1)
  264. >>> mun.next()
  265. Boundary(v_id=2)
  266. >>> mun.next()
  267. Boundary(v_id=3)
  268. >>> mun.rewind()
  269. >>> mun.next()
  270. Boundary(v_id=1)
  271. >>> mun.close()
  272. ..
  273. """
  274. libvect.Vect_rewind(self.c_mapinfo)
  275. def read(self, feature_id):
  276. """Return a geometry object given the feature id. ::
  277. >>> mun = VectorTopo('boundary_municp_sqlite')
  278. >>> mun.open()
  279. >>> feature1 = mun.read(0) #doctest: +ELLIPSIS
  280. Traceback (most recent call last):
  281. ...
  282. ValueError: The index must be >0, 0 given.
  283. >>> feature1 = mun.read(1)
  284. >>> feature1
  285. Boundary(v_id=1)
  286. >>> feature1.length()
  287. 1415.3348048582038
  288. >>> mun.read(-1)
  289. Centoid(649102.382010, 15945.714502)
  290. >>> len(mun)
  291. 8707
  292. >>> mun.read(8707)
  293. Centoid(649102.382010, 15945.714502)
  294. >>> mun.read(8708) #doctest: +ELLIPSIS
  295. Traceback (most recent call last):
  296. ...
  297. IndexError: Index out of range
  298. >>> mun.close()
  299. ..
  300. """
  301. if feature_id < 0: # Handle negative indices
  302. feature_id += self.__len__() + 1
  303. if feature_id >= (self.__len__() + 1):
  304. raise IndexError('Index out of range')
  305. if feature_id > 0:
  306. c_points = ctypes.pointer(libvect.line_pnts())
  307. c_cats = ctypes.pointer(libvect.line_cats())
  308. ftype = libvect.Vect_read_line(self.c_mapinfo, c_points,
  309. c_cats, feature_id)
  310. if GV_TYPE[ftype]['obj'] is not None:
  311. return GV_TYPE[ftype]['obj'](v_id=feature_id,
  312. c_mapinfo=self.c_mapinfo,
  313. c_points=c_points,
  314. c_cats=c_cats)
  315. else:
  316. raise ValueError('The index must be >0, %r given.' % feature_id)
  317. def rewrite(self, geo_obj):
  318. result = libvect.Vect_rewrite_line(self.c_mapinfo,
  319. geo_obj.id, geo_obj.gtype,
  320. geo_obj.c_points,
  321. geo_obj.c_cats)
  322. # return offset into file where the feature starts
  323. geo_obj.offset = result
  324. def delete(self, feature_id):
  325. if libvect.Vect_rewrite_line(self.c_mapinfo, feature_id) == -1:
  326. raise GrassError("C funtion: Vect_rewrite_line.")
  327. def restore(self, geo_obj):
  328. if hasattr(geo_obj, 'offset'):
  329. if libvect.Vect_restore_line(self.c_mapinfo, geo_obj.id,
  330. geo_obj.offset) == -1:
  331. raise GrassError("C funtion: Vect_restore_line.")
  332. else:
  333. raise ValueError("The value have not an offset attribute.")
  334. def bbox(self):
  335. """Return the BBox of the vecor map
  336. """
  337. bbox = Bbox()
  338. if libvect.Vect_get_map_box(self.c_mapinfo, bbox.c_bbox) == 0:
  339. raise GrassError("I can not find the Bbox.")
  340. return bbox