__init__.py 13 KB

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