__init__.py 13 KB

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