__init__.py 16 KB

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