__init__.py 14 KB

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