__init__.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  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 grass.pygrass.vector.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 grass.pygrass.vector.geometry import GEOOBJ as _GEOOBJ
  15. from grass.pygrass.vector.geometry import read_line, read_next_line
  16. from grass.pygrass.vector.geometry import Area as _Area
  17. from grass.pygrass.vector.abstract import Info
  18. from grass.pygrass.vector.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_lines,
  26. "points": libvect.Vect_get_num_line_points,
  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. """Vector class is the grass vector format without topology
  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. def __init__(self, name, mapset='', *args, **kwargs):
  50. # Set map name and mapset
  51. super(Vector, self).__init__(name, mapset, *args, **kwargs)
  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. >>> cens = Vector('census')
  63. >>> cens.open(mode='r')
  64. >>> features = [feature for feature in cens]
  65. >>> features[:3]
  66. [Boundary(v_id=None), Boundary(v_id=None), Boundary(v_id=None)]
  67. >>> cens.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. >>> cens = Vector('census')
  76. >>> cens.open(mode='r')
  77. >>> cens.next()
  78. Boundary(v_id=None)
  79. >>> cens.next()
  80. Boundary(v_id=None)
  81. >>> cens.close()
  82. ..
  83. """
  84. return read_next_line(self.c_mapinfo, self.table, self.writable,
  85. is2D=not self.is_3D())
  86. @must_be_open
  87. def rewind(self):
  88. """Rewind vector map to cause reads to start at beginning."""
  89. if libvect.Vect_rewind(self.c_mapinfo) == -1:
  90. raise GrassError("Vect_rewind raise an error.")
  91. @must_be_open
  92. def write(self, geo_obj, attrs=None, set_cats=True):
  93. """Write geometry features and attributes.
  94. :param geo_obj: a geometry grass object define in
  95. grass.pygrass.vector.geometry
  96. :type geo_obj: geometry GRASS object
  97. :param attrs: a list with the values that will be insert in the
  98. attribute table.
  99. :type attrs: list
  100. :param set_cats: if True, the category of the geometry feature is set
  101. using the default layer of the vector map and a
  102. progressive category value (default), otherwise the
  103. c_cats attribute of the geometry object will be used.
  104. :type set_cats: bool
  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. commit the db changes ::
  123. >>> new.table.conn.commit()
  124. >>> new.table.execute().fetchall()
  125. [(1, u'pub'), (2, u'resturnat')]
  126. close the vector map ::
  127. >>> new.close()
  128. >>> new.exist()
  129. True
  130. then play with the map ::
  131. >>> new.open(mode='r')
  132. >>> new.read(1)
  133. Point(636981.336043, 256517.602235)
  134. >>> new.read(2)
  135. Point(637209.083058, 257970.129540)
  136. >>> new.read(1).attrs['name']
  137. u'pub'
  138. >>> new.read(2).attrs['name']
  139. u'resturnat'
  140. >>> new.close()
  141. >>> new.remove()
  142. """
  143. self.n_lines += 1
  144. if self.table is not None and attrs:
  145. attr = [self.n_lines, ]
  146. attr.extend(attrs)
  147. cur = self.table.conn.cursor()
  148. cur.execute(self.table.columns.insert_str, attr)
  149. cur.close()
  150. if set_cats:
  151. cats = Cats(geo_obj.c_cats)
  152. cats.reset()
  153. cats.set(self.n_lines, self.layer)
  154. if geo_obj.gtype == _Area.gtype:
  155. result = self._write_area(geo_obj)
  156. result = libvect.Vect_write_line(self.c_mapinfo, geo_obj.gtype,
  157. geo_obj.c_points, geo_obj.c_cats)
  158. if result == -1:
  159. raise GrassError("Not able to write the vector feature.")
  160. if self._topo_level == 2:
  161. # return new feature id (on level 2)
  162. geo_obj.id = result
  163. else:
  164. # return offset into file where the feature starts (on level 1)
  165. geo_obj.offset = result
  166. @must_be_open
  167. def has_color_table(self):
  168. """Return if vector has color table associated in file system;
  169. Color table stored in the vector's attribute table well be not checked
  170. >>> cens = Vector('census')
  171. >>> cens.open(mode='r')
  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. Module('v.colors')
  180. >>> mycens = Vector('mycensus')
  181. >>> mycens.open(mode='r')
  182. >>> mycens.has_color_table()
  183. True
  184. >>> mycens.close()
  185. >>> remove('mycensus', 'vect')
  186. """
  187. loc = Location()
  188. path = join(loc.path(), self.mapset, 'vector', self.name, 'colr')
  189. return True if exists(path) else False
  190. #=============================================
  191. # VECTOR WITH TOPOLOGY
  192. #=============================================
  193. class VectorTopo(Vector):
  194. """Vector class with the support of the GRASS topology.
  195. Open a vector map using the *with statement*: ::
  196. >>> with VectorTopo('schools', mode='r') as schools:
  197. ... for school in schools[:3]:
  198. ... print school.attrs['NAMESHORT']
  199. ...
  200. SWIFT CREEK
  201. BRIARCLIFF
  202. FARMINGTON WOODS
  203. >>> schools.is_open()
  204. False
  205. ..
  206. """
  207. def __init__(self, name, mapset='', *args, **kwargs):
  208. super(VectorTopo, self).__init__(name, mapset, *args, **kwargs)
  209. self._topo_level = 2
  210. self._class_name = 'VectorTopo'
  211. def __len__(self):
  212. return libvect.Vect_get_num_lines(self.c_mapinfo)
  213. def __getitem__(self, key):
  214. """::
  215. >>> cens = VectorTopo('census')
  216. >>> cens.open(mode='r')
  217. >>> cens[:3]
  218. [Boundary(v_id=1), Boundary(v_id=2), Boundary(v_id=3)]
  219. >>> cens.close()
  220. ..
  221. """
  222. if isinstance(key, slice):
  223. #import pdb; pdb.set_trace()
  224. #Get the start, stop, and step from the slice
  225. return [self.read(indx + 1)
  226. for indx in range(*key.indices(len(self)))]
  227. elif isinstance(key, int):
  228. return self.read(key)
  229. else:
  230. raise ValueError("Invalid argument type: %r." % key)
  231. @must_be_open
  232. def num_primitive_of(self, primitive):
  233. """Return the number of primitive
  234. :param primitive: the name of primitive to query; the supported values are:
  235. * *boundary*,
  236. * *centroid*,
  237. * *face*,
  238. * *kernel*,
  239. * *line*,
  240. * *point*
  241. * *area*
  242. * *volume*
  243. :type primitive: str
  244. ::
  245. >>> cens = VectorTopo('census')
  246. >>> cens.open(mode='r')
  247. >>> cens.num_primitive_of('point')
  248. 0
  249. >>> cens.num_primitive_of('line')
  250. 0
  251. >>> cens.num_primitive_of('centroid')
  252. 2537
  253. >>> cens.num_primitive_of('boundary')
  254. 6383
  255. >>> cens.close()
  256. ..
  257. """
  258. return libvect.Vect_get_num_primitives(self.c_mapinfo,
  259. VTYPE[primitive])
  260. @must_be_open
  261. def number_of(self, vtype):
  262. """Return the number of the choosen element type
  263. :param vtype: the name of type to query; the supported values are:
  264. *areas*, *dblinks*, *faces*, *holes*, *islands*,
  265. *kernels*, *line_points*, *lines*, *nodes*,
  266. *update_lines*, *update_nodes*, *volumes*
  267. :type vtype: str
  268. >>> cens = VectorTopo('census')
  269. >>> cens.open(mode='r')
  270. >>> cens.number_of("areas")
  271. 2547
  272. >>> cens.number_of("islands")
  273. 49
  274. >>> cens.number_of("holes")
  275. 0
  276. >>> cens.number_of("lines")
  277. 8920
  278. >>> cens.number_of("nodes")
  279. 3885
  280. >>> cens.number_of("pizza")
  281. ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
  282. Traceback (most recent call last):
  283. ...
  284. ValueError: vtype not supported, use one of: 'areas', ...
  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. :param vtype: the name of type to query; the supported values are:
  305. *areas*, *dblinks*, *faces*, *holes*, *islands*,
  306. *kernels*, *line_points*, *lines*, *nodes*,
  307. *update_lines*, *update_nodes*, *volumes*
  308. :type vtype: str
  309. :param idonly: variable to return only the id of features instead of
  310. full features
  311. :type idonly: bool
  312. >>> cens = VectorTopo('census', mode='r')
  313. >>> cens.open(mode='r')
  314. >>> big = [area for area in cens.viter('areas')
  315. ... if area.alive() and area.area() >= 10000]
  316. >>> big[:3]
  317. [Area(5), Area(6), Area(13)]
  318. to sort the result in a efficient way, use: ::
  319. >>> from operator import methodcaller as method
  320. >>> big.sort(key=method('area'), reverse=True) # sort the list
  321. >>> for area in big[:3]:
  322. ... print area, area.area()
  323. Area(2099) 5392751.5304
  324. Area(2171) 4799921.30863
  325. Area(495) 4055812.49695
  326. >>> cens.close()
  327. """
  328. if vtype in _GEOOBJ.keys():
  329. if _GEOOBJ[vtype] is not None:
  330. ids = (indx for indx in range(1, self.number_of(vtype) + 1))
  331. if idonly:
  332. return ids
  333. return (_GEOOBJ[vtype](v_id=indx, c_mapinfo=self.c_mapinfo,
  334. table=self.table,
  335. writable=self.writable)
  336. for indx in ids)
  337. else:
  338. keys = "', '".join(sorted(_GEOOBJ.keys()))
  339. raise ValueError("vtype not supported, use one of: '%s'" % keys)
  340. @must_be_open
  341. def rewind(self):
  342. """Rewind vector map to cause reads to start at beginning. ::
  343. >>> cens = VectorTopo('census')
  344. >>> cens.open(mode='r')
  345. >>> cens.next()
  346. Boundary(v_id=1)
  347. >>> cens.next()
  348. Boundary(v_id=2)
  349. >>> cens.next()
  350. Boundary(v_id=3)
  351. >>> cens.rewind()
  352. >>> cens.next()
  353. Boundary(v_id=1)
  354. >>> cens.close()
  355. ..
  356. """
  357. libvect.Vect_rewind(self.c_mapinfo)
  358. @must_be_open
  359. def cat(self, cat_id, vtype, layer=None, generator=False, geo=None):
  360. """Return the geometry features with category == cat_id.
  361. :param cat_id: the category number
  362. :type cat_id: int
  363. :param vtype: the type of geometry feature that we are looking for
  364. :type vtype: str
  365. :param layer: the layer number that will be used
  366. :type layer: int
  367. :param generator: if True return a generator otherwise it return a
  368. list of features
  369. :type generator: bool
  370. """
  371. if geo is None and vtype not in _GEOOBJ:
  372. keys = "', '".join(sorted(_GEOOBJ.keys()))
  373. raise ValueError("vtype not supported, use one of: '%s'" % keys)
  374. Obj = _GEOOBJ[vtype] if geo is None else geo
  375. ilist = Ilist()
  376. libvect.Vect_cidx_find_all(self.c_mapinfo,
  377. layer if layer else self.layer,
  378. Obj.gtype, cat_id, ilist.c_ilist)
  379. is2D = not self.is_3D()
  380. if generator:
  381. return (read_line(feature_id=v_id, c_mapinfo=self.c_mapinfo,
  382. table=self.table, writable=self.writable,
  383. is2D=is2D)
  384. for v_id in ilist)
  385. else:
  386. return [read_line(feature_id=v_id, c_mapinfo=self.c_mapinfo,
  387. table=self.table, writable=self.writable,
  388. is2D=is2D)
  389. for v_id in ilist]
  390. @must_be_open
  391. def read(self, feature_id):
  392. """Return a geometry object given the feature id.
  393. :param int feature_id: the id of feature to obtain
  394. >>> cens = VectorTopo('census')
  395. >>> cens.open(mode='r')
  396. >>> feature1 = cens.read(0) #doctest: +ELLIPSIS
  397. Traceback (most recent call last):
  398. ...
  399. ValueError: The index must be >0, 0 given.
  400. >>> feature1 = cens.read(1)
  401. >>> feature1
  402. Boundary(v_id=1)
  403. >>> feature1.length()
  404. 444.54490917696944
  405. >>> cens.read(-1)
  406. Centoid(642963.159711, 214994.016279)
  407. >>> len(cens)
  408. 8920
  409. >>> cens.read(8920)
  410. Centoid(642963.159711, 214994.016279)
  411. >>> cens.read(8921) #doctest: +ELLIPSIS
  412. Traceback (most recent call last):
  413. ...
  414. IndexError: Index out of range
  415. >>> cens.close()
  416. """
  417. return read_line(feature_id, self.c_mapinfo, self.table, self.writable,
  418. is2D=not self.is_3D())
  419. @must_be_open
  420. def is_empty(self):
  421. """Return if a vector map is empty or not
  422. """
  423. primitives = self.num_primitives()
  424. output = True
  425. for v in primitives.values():
  426. if v != 0:
  427. output = False
  428. break
  429. return output
  430. @must_be_open
  431. def rewrite(self, line, geo_obj, attrs=None, **kargs):
  432. """Rewrite a geometry features
  433. """
  434. if self.table is not None and attrs:
  435. attr = [line, ]
  436. attr.extend(attrs)
  437. self.table.update(key=line, values=attr)
  438. elif self.table is None and attrs:
  439. print "Table for vector {name} does not exist, attributes not" \
  440. " loaded".format(name=self.name)
  441. libvect.Vect_cat_set(geo_obj.c_cats, self.layer, line)
  442. result = libvect.Vect_rewrite_line(self.c_mapinfo,
  443. line, geo_obj.gtype,
  444. geo_obj.c_points,
  445. geo_obj.c_cats)
  446. if result == -1:
  447. raise GrassError("Not able to write the vector feature.")
  448. # return offset into file where the feature starts
  449. geo_obj.offset = result
  450. @must_be_open
  451. def delete(self, feature_id):
  452. """Remove a feature by its id
  453. :param feature_id: the id of the feature
  454. :type feature_id: int
  455. """
  456. if libvect.Vect_rewrite_line(self.c_mapinfo, feature_id) == -1:
  457. raise GrassError("C funtion: Vect_rewrite_line.")
  458. @must_be_open
  459. def restore(self, geo_obj):
  460. if hasattr(geo_obj, 'offset'):
  461. if libvect.Vect_restore_line(self.c_mapinfo, geo_obj.id,
  462. geo_obj.offset) == -1:
  463. raise GrassError("C funtion: Vect_restore_line.")
  464. else:
  465. raise ValueError("The value have not an offset attribute.")
  466. @must_be_open
  467. def bbox(self):
  468. """Return the BBox of the vecor map
  469. """
  470. bbox = Bbox()
  471. if libvect.Vect_get_map_box(self.c_mapinfo, bbox.c_bbox) == 0:
  472. raise GrassError("I can not find the Bbox.")
  473. return bbox
  474. @must_be_open
  475. def select_by_bbox(self, bbox):
  476. """Return the BBox of the vector map
  477. """
  478. # TODO replace with bbox if bbox else Bbox() ??
  479. bbox = Bbox()
  480. if libvect.Vect_get_map_box(self.c_mapinfo, bbox.c_bbox) == 0:
  481. raise GrassError("I can not find the Bbox.")
  482. return bbox
  483. def close(self, build=True, release=True):
  484. """Close the VectorTopo map, if release is True, the memory
  485. occupied by spatial index is released"""
  486. if release:
  487. libvect.Vect_set_release_support(self.c_mapinfo)
  488. super(VectorTopo, self).close(build=build)