__init__.py 14 KB

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