__init__.py 15 KB

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