__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 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, Cats
  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, set_cats=True):
  89. """Write geometry features and attributes.
  90. Parameters
  91. ----------
  92. geo_obj : geometry GRASS object
  93. A geometry grass object define in grass.pygrass.vector.geometry.
  94. attrs: list, optional
  95. A list with the values that will be insert in the attribute table.
  96. set_cats, bool, optional
  97. If True, the category of the geometry feature is set using the
  98. default layer of the vector map and a progressive category value
  99. (default), otherwise the c_cats attribute of the geometry object
  100. will be used.
  101. Examples
  102. --------
  103. Open a new vector map ::
  104. >>> new = VectorTopo('newvect')
  105. >>> new.exist()
  106. False
  107. define the new columns of the attribute table ::
  108. >>> cols = [(u'cat', 'INTEGER PRIMARY KEY'),
  109. ... (u'name', 'TEXT')]
  110. open the vector map in write mode
  111. >>> new.open('w', tab_name='newvect', tab_cols=cols)
  112. import a geometry feature ::
  113. >>> from grass.pygrass.vector.geometry import Point
  114. create two points ::
  115. >>> point0 = Point(636981.336043, 256517.602235)
  116. >>> point1 = Point(637209.083058, 257970.129540)
  117. then write the two points on the map, with ::
  118. >>> new.write(point0, ('pub', ))
  119. >>> new.write(point1, ('resturnat', ))
  120. close the vector map ::
  121. >>> new.close()
  122. >>> new.exist()
  123. True
  124. then play with the map ::
  125. >>> new.open()
  126. >>> new.read(1)
  127. Point(636981.336043, 256517.602235)
  128. >>> new.read(2)
  129. Point(637209.083058, 257970.129540)
  130. >>> new.read(1).attrs['name']
  131. u'pub'
  132. >>> new.read(2).attrs['cat', 'name']
  133. (2, u'resturnat')
  134. >>> new.close()
  135. >>> new.remove()
  136. ..
  137. """
  138. self.n_lines += 1
  139. if self.table is not None and attrs:
  140. attr = [self.n_lines, ]
  141. attr.extend(attrs)
  142. cur = self.table.conn.cursor()
  143. cur.execute(self.table.columns.insert_str, attr)
  144. cur.close()
  145. if set_cats:
  146. cats = Cats(geo_obj.c_cats)
  147. cats.reset()
  148. cats.set(self.n_lines, self.layer)
  149. result = libvect.Vect_write_line(self.c_mapinfo, geo_obj.gtype,
  150. geo_obj.c_points, geo_obj.c_cats)
  151. if result == -1:
  152. raise GrassError("Not able to write the vector feature.")
  153. if self._topo_level == 2:
  154. # return new feature id (on level 2)
  155. geo_obj.id = result
  156. else:
  157. # return offset into file where the feature starts (on level 1)
  158. geo_obj.offset = result
  159. #=============================================
  160. # VECTOR WITH TOPOLOGY
  161. #=============================================
  162. class VectorTopo(Vector):
  163. """Vector class with the support of the GRASS topology.
  164. Open a vector map using the *with statement*: ::
  165. >>> with VectorTopo('schools') as schools:
  166. ... for school in schools[:3]:
  167. ... print school.attrs['NAMESHORT']
  168. ...
  169. SWIFT CREEK
  170. BRIARCLIFF
  171. FARMINGTON WOODS
  172. >>> schools.is_open()
  173. False
  174. """
  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('census')
  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. >>> cens = VectorTopo('boundary_municp_sqlite')
  212. >>> cens.open()
  213. >>> cens.num_primitive_of('point')
  214. 0
  215. >>> cens.num_primitive_of('line')
  216. 0
  217. >>> cens.num_primitive_of('centroid')
  218. 3579
  219. >>> cens.num_primitive_of('boundary')
  220. 5128
  221. >>> cens.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. >>> cens = VectorTopo('boundary_municp_sqlite')
  233. >>> cens.open()
  234. >>> cens.number_of("areas")
  235. 3579
  236. >>> cens.number_of("islands")
  237. 2629
  238. >>> cens.number_of("holes")
  239. 0
  240. >>> cens.number_of("lines")
  241. 8707
  242. >>> cens.number_of("nodes")
  243. 4178
  244. >>> cens.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. >>> cens.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. >>> cens = VectorTopo('census')
  273. >>> cens.open()
  274. >>> big = [area for area in cens.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. >>> cens.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 cat(self, cat_id):
  318. """Return the geometry features with category == cat_id.
  319. """
  320. return self.read(libvect.Vect_get_line_cat(self.c_mapinfo,
  321. cat_id, self.layer))
  322. @must_be_open
  323. def read(self, feature_id):
  324. """Return a geometry object given the feature id. ::
  325. >>> mun = VectorTopo('boundary_municp_sqlite')
  326. >>> mun.open()
  327. >>> feature1 = mun.read(0) #doctest: +ELLIPSIS
  328. Traceback (most recent call last):
  329. ...
  330. ValueError: The index must be >0, 0 given.
  331. >>> feature1 = mun.read(1)
  332. >>> feature1
  333. Boundary(v_id=1)
  334. >>> feature1.length()
  335. 1415.3348048582038
  336. >>> mun.read(-1)
  337. Centoid(649102.382010, 15945.714502)
  338. >>> len(mun)
  339. 8707
  340. >>> mun.read(8707)
  341. Centoid(649102.382010, 15945.714502)
  342. >>> mun.read(8708) #doctest: +ELLIPSIS
  343. Traceback (most recent call last):
  344. ...
  345. IndexError: Index out of range
  346. >>> mun.close()
  347. ..
  348. """
  349. return read_line(feature_id, self.c_mapinfo, self.table, self.writable)
  350. @must_be_open
  351. def is_empty(self):
  352. """Return if a vector map is empty or not
  353. """
  354. primitives = self.num_primitives()
  355. output = True
  356. for v in primitives.values():
  357. if v != 0:
  358. output = False
  359. break
  360. return output
  361. @must_be_open
  362. def rewrite(self, line, geo_obj, attrs=None, **kargs):
  363. """Rewrite a geometry features
  364. """
  365. if self.table is not None and attrs:
  366. attr = [line, ]
  367. attr.extend(attrs)
  368. self.table.update(key=line, values=attr)
  369. libvect.Vect_cat_set(geo_obj.c_cats, self.layer, line)
  370. result = libvect.Vect_rewrite_line(self.c_mapinfo,
  371. line, geo_obj.gtype,
  372. geo_obj.c_points,
  373. geo_obj.c_cats)
  374. if result == -1:
  375. raise GrassError("Not able to write the vector feature.")
  376. # return offset into file where the feature starts
  377. geo_obj.offset = result
  378. @must_be_open
  379. def delete(self, feature_id):
  380. if libvect.Vect_rewrite_line(self.c_mapinfo, feature_id) == -1:
  381. raise GrassError("C funtion: Vect_rewrite_line.")
  382. @must_be_open
  383. def restore(self, geo_obj):
  384. if hasattr(geo_obj, 'offset'):
  385. if libvect.Vect_restore_line(self.c_mapinfo, geo_obj.id,
  386. geo_obj.offset) == -1:
  387. raise GrassError("C funtion: Vect_restore_line.")
  388. else:
  389. raise ValueError("The value have not an offset attribute.")
  390. @must_be_open
  391. def bbox(self):
  392. """Return the BBox of the vecor map
  393. """
  394. bbox = Bbox()
  395. if libvect.Vect_get_map_box(self.c_mapinfo, bbox.c_bbox) == 0:
  396. raise GrassError("I can not find the Bbox.")
  397. return bbox
  398. def close(self, release=True):
  399. """Close the VectorTopo map, if release is True, the memory
  400. occupied by spatial index is released"""
  401. if release:
  402. libvect.Vect_set_release_support(self.c_mapinfo)
  403. super(VectorTopo, self).close()