__init__.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  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. loc = Location()
  187. path = join(loc.path(), self.mapset, 'vector', self.name, 'colr')
  188. return True if exists(path) else 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='', *args, **kwargs):
  206. super(VectorTopo, self).__init__(name, mapset, *args, **kwargs)
  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 range(*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, idonly=False):
  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. ids = (indx for indx in range(1, self.number_of(vtype) + 1))
  322. if idonly:
  323. return ids
  324. return (_GEOOBJ[vtype](v_id=indx, c_mapinfo=self.c_mapinfo,
  325. table=self.table,
  326. writable=self.writable)
  327. for indx in ids)
  328. else:
  329. keys = "', '".join(sorted(_GEOOBJ.keys()))
  330. raise ValueError("vtype not supported, use one of: '%s'" % keys)
  331. @must_be_open
  332. def rewind(self):
  333. """Rewind vector map to cause reads to start at beginning. ::
  334. >>> mun = VectorTopo('boundary_municp_sqlite')
  335. >>> mun.open()
  336. >>> mun.next()
  337. Boundary(v_id=1)
  338. >>> mun.next()
  339. Boundary(v_id=2)
  340. >>> mun.next()
  341. Boundary(v_id=3)
  342. >>> mun.rewind()
  343. >>> mun.next()
  344. Boundary(v_id=1)
  345. >>> mun.close()
  346. ..
  347. """
  348. libvect.Vect_rewind(self.c_mapinfo)
  349. @must_be_open
  350. def cat(self, cat_id, vtype, layer=None, generator=False, geo=None):
  351. """Return the geometry features with category == cat_id.
  352. Parameters
  353. ----------
  354. cat_id : integer
  355. Integer with the category number.
  356. vtype : string
  357. String of the type of geometry feature that we are looking for.
  358. layer : integer, optional
  359. Integer of the layer that will be used.
  360. generator : bool, optional
  361. If True return a generator otherwise it return a list of features.
  362. """
  363. if geo is None and vtype not in _GEOOBJ:
  364. keys = "', '".join(sorted(_GEOOBJ.keys()))
  365. raise ValueError("vtype not supported, use one of: '%s'" % keys)
  366. Obj = _GEOOBJ[vtype] if geo is None else geo
  367. ilist = Ilist()
  368. libvect.Vect_cidx_find_all(self.c_mapinfo,
  369. layer if layer else self.layer,
  370. Obj.gtype, cat_id, ilist.c_ilist)
  371. if generator:
  372. return (read_line(feature_id=v_id, c_mapinfo=self.c_mapinfo,
  373. table=self.table, writable=self.writable)
  374. for v_id in ilist)
  375. else:
  376. return [read_line(feature_id=v_id, c_mapinfo=self.c_mapinfo,
  377. table=self.table, writable=self.writable)
  378. for v_id in ilist]
  379. @must_be_open
  380. def read(self, feature_id):
  381. """Return a geometry object given the feature id. ::
  382. >>> mun = VectorTopo('boundary_municp_sqlite')
  383. >>> mun.open()
  384. >>> feature1 = mun.read(0) #doctest: +ELLIPSIS
  385. Traceback (most recent call last):
  386. ...
  387. ValueError: The index must be >0, 0 given.
  388. >>> feature1 = mun.read(1)
  389. >>> feature1
  390. Boundary(v_id=1)
  391. >>> feature1.length()
  392. 1415.3348048582038
  393. >>> mun.read(-1)
  394. Centoid(649102.382010, 15945.714502)
  395. >>> len(mun)
  396. 8707
  397. >>> mun.read(8707)
  398. Centoid(649102.382010, 15945.714502)
  399. >>> mun.read(8708) #doctest: +ELLIPSIS
  400. Traceback (most recent call last):
  401. ...
  402. IndexError: Index out of range
  403. >>> mun.close()
  404. ..
  405. """
  406. return read_line(feature_id, self.c_mapinfo, self.table, self.writable)
  407. @must_be_open
  408. def is_empty(self):
  409. """Return if a vector map is empty or not
  410. """
  411. primitives = self.num_primitives()
  412. output = True
  413. for v in primitives.values():
  414. if v != 0:
  415. output = False
  416. break
  417. return output
  418. @must_be_open
  419. def rewrite(self, line, geo_obj, attrs=None, **kargs):
  420. """Rewrite a geometry features
  421. """
  422. if self.table is not None and attrs:
  423. attr = [line, ]
  424. attr.extend(attrs)
  425. self.table.update(key=line, values=attr)
  426. libvect.Vect_cat_set(geo_obj.c_cats, self.layer, line)
  427. result = libvect.Vect_rewrite_line(self.c_mapinfo,
  428. line, geo_obj.gtype,
  429. geo_obj.c_points,
  430. geo_obj.c_cats)
  431. if result == -1:
  432. raise GrassError("Not able to write the vector feature.")
  433. # return offset into file where the feature starts
  434. geo_obj.offset = result
  435. @must_be_open
  436. def delete(self, feature_id):
  437. if libvect.Vect_rewrite_line(self.c_mapinfo, feature_id) == -1:
  438. raise GrassError("C funtion: Vect_rewrite_line.")
  439. @must_be_open
  440. def restore(self, geo_obj):
  441. if hasattr(geo_obj, 'offset'):
  442. if libvect.Vect_restore_line(self.c_mapinfo, geo_obj.id,
  443. geo_obj.offset) == -1:
  444. raise GrassError("C funtion: Vect_restore_line.")
  445. else:
  446. raise ValueError("The value have not an offset attribute.")
  447. @must_be_open
  448. def bbox(self):
  449. """Return the BBox of the vecor map
  450. """
  451. bbox = Bbox()
  452. if libvect.Vect_get_map_box(self.c_mapinfo, bbox.c_bbox) == 0:
  453. raise GrassError("I can not find the Bbox.")
  454. return bbox
  455. @must_be_open
  456. def select_by_bbox(self, bbox):
  457. """Return the BBox of the vecor map
  458. """
  459. bbox = Bbox()
  460. if libvect.Vect_get_map_box(self.c_mapinfo, bbox.c_bbox) == 0:
  461. raise GrassError("I can not find the Bbox.")
  462. return bbox
  463. def close(self, build=True, release=True):
  464. """Close the VectorTopo map, if release is True, the memory
  465. occupied by spatial index is released"""
  466. if release:
  467. libvect.Vect_set_release_support(self.c_mapinfo)
  468. super(VectorTopo, self).close(build=build)