__init__.py 15 KB

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