__init__.py 15 KB

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