__init__.py 13 KB

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