__init__.py 17 KB

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