__init__.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. # -*- coding: utf-8 -*-
  2. from os.path import join, exists
  3. import grass.lib.gis as libgis
  4. libgis.G_gisinit('')
  5. import grass.lib.vector as libvect
  6. #
  7. # import pygrass modules
  8. #
  9. from grass.pygrass.vector.vector_type import VTYPE
  10. from grass.pygrass.errors import GrassError, must_be_open
  11. from grass.pygrass.gis import Location
  12. from grass.pygrass.vector.geometry import GEOOBJ as _GEOOBJ
  13. from grass.pygrass.vector.geometry import read_line, read_next_line
  14. from grass.pygrass.vector.geometry import Area as _Area
  15. from grass.pygrass.vector.abstract import Info
  16. from grass.pygrass.vector.basic import Bbox, Cats, Ilist
  17. _NUMOF = {"areas": libvect.Vect_get_num_areas,
  18. "dblinks": libvect.Vect_get_num_dblinks,
  19. "faces": libvect.Vect_get_num_faces,
  20. "holes": libvect.Vect_get_num_holes,
  21. "islands": libvect.Vect_get_num_islands,
  22. "kernels": libvect.Vect_get_num_kernels,
  23. "points": libvect.Vect_get_num_lines,
  24. "lines": libvect.Vect_get_num_lines,
  25. "nodes": libvect.Vect_get_num_nodes,
  26. "updated_lines": libvect.Vect_get_num_updated_lines,
  27. "updated_nodes": libvect.Vect_get_num_updated_nodes,
  28. "volumes": libvect.Vect_get_num_volumes}
  29. #=============================================
  30. # VECTOR
  31. #=============================================
  32. class Vector(Info):
  33. """Vector class is the grass vector format without topology
  34. >>> from grass.pygrass.vector import Vector
  35. >>> cens = Vector('census')
  36. >>> cens.is_open()
  37. False
  38. >>> cens.mapset
  39. ''
  40. >>> cens.exist()
  41. True
  42. >>> cens.mapset
  43. 'PERMANENT'
  44. >>> cens.overwrite
  45. False
  46. """
  47. def __init__(self, name, mapset='', *args, **kwargs):
  48. # Set map name and mapset
  49. super(Vector, self).__init__(name, mapset, *args, **kwargs)
  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. >>> cens = Vector('census')
  61. >>> cens.open(mode='r')
  62. >>> features = [feature for feature in cens]
  63. >>> features[:3]
  64. [Boundary(v_id=None), Boundary(v_id=None), Boundary(v_id=None)]
  65. >>> cens.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. >>> cens = Vector('census')
  74. >>> cens.open(mode='r')
  75. >>> cens.next()
  76. Boundary(v_id=None)
  77. >>> cens.next()
  78. Boundary(v_id=None)
  79. >>> cens.close()
  80. ..
  81. """
  82. return read_next_line(self.c_mapinfo, self.table, self.writable,
  83. is2D=not self.is_3D())
  84. @must_be_open
  85. def rewind(self):
  86. """Rewind vector map to cause reads to start at beginning."""
  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. :param geo_obj: a geometry grass object define in
  93. grass.pygrass.vector.geometry
  94. :type geo_obj: geometry GRASS object
  95. :param attrs: a list with the values that will be insert in the
  96. attribute table.
  97. :type attrs: list
  98. :param set_cats: if True, the category of the geometry feature is set
  99. using the default layer of the vector map and a
  100. progressive category value (default), otherwise the
  101. c_cats attribute of the geometry object will be used.
  102. :type set_cats: bool
  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. commit the db changes ::
  121. >>> new.table.conn.commit()
  122. >>> new.table.execute().fetchall()
  123. [(1, u'pub'), (2, u'resturnat')]
  124. close the vector map ::
  125. >>> new.close()
  126. >>> new.exist()
  127. True
  128. then play with the map ::
  129. >>> new.open(mode='r')
  130. >>> new.read(1)
  131. Point(636981.336043, 256517.602235)
  132. >>> new.read(2)
  133. Point(637209.083058, 257970.129540)
  134. >>> new.read(1).attrs['name']
  135. u'pub'
  136. >>> new.read(2).attrs['name']
  137. u'resturnat'
  138. >>> new.close()
  139. >>> new.remove()
  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. >>> cens = Vector('census')
  169. >>> cens.open(mode='r')
  170. >>> cens.has_color_table()
  171. False
  172. >>> cens.close()
  173. >>> from grass.pygrass.utils import copy, remove
  174. >>> copy('census','mycensus','vect')
  175. >>> from grass.pygrass.modules.shortcuts import vector as v
  176. >>> v.colors(map='mycensus', color='population', column='TOTAL_POP')
  177. Module('v.colors')
  178. >>> mycens = Vector('mycensus')
  179. >>> mycens.open(mode='r')
  180. >>> mycens.has_color_table()
  181. True
  182. >>> mycens.close()
  183. >>> remove('mycensus', 'vect')
  184. """
  185. loc = Location()
  186. path = join(loc.path(), self.mapset, 'vector', self.name, 'colr')
  187. return True if exists(path) else False
  188. #=============================================
  189. # VECTOR WITH TOPOLOGY
  190. #=============================================
  191. class VectorTopo(Vector):
  192. """Vector class with the support of the GRASS topology.
  193. Open a vector map using the *with statement*: ::
  194. >>> with VectorTopo('schools', mode='r') as schools:
  195. ... for school in schools[:4]:
  196. ... print school.attrs['NAMESHORT']
  197. ...
  198. SWIFT CREEK
  199. BRIARCLIFF
  200. FARMINGTON WOODS
  201. >>> schools.is_open()
  202. False
  203. ..
  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. >>> cens = VectorTopo('census')
  214. >>> cens.open(mode='r')
  215. >>> cens[:4]
  216. [Boundary(v_id=1), Boundary(v_id=2), Boundary(v_id=3)]
  217. >>> cens.close()
  218. ..
  219. """
  220. if isinstance(key, slice):
  221. return [self.read(indx)
  222. for indx in range(key.start if key.start else 1,
  223. key.stop if key.stop else len(self),
  224. key.step if key.step else 1)]
  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. """Return the number of primitive
  232. :param primitive: the name of primitive to query; the supported values are:
  233. * *boundary*,
  234. * *centroid*,
  235. * *face*,
  236. * *kernel*,
  237. * *line*,
  238. * *point*
  239. * *area*
  240. * *volume*
  241. :type primitive: str
  242. ::
  243. >>> cens = VectorTopo('census')
  244. >>> cens.open(mode='r')
  245. >>> cens.num_primitive_of('point')
  246. 0
  247. >>> cens.num_primitive_of('line')
  248. 0
  249. >>> cens.num_primitive_of('centroid')
  250. 2537
  251. >>> cens.num_primitive_of('boundary')
  252. 6383
  253. >>> cens.close()
  254. ..
  255. """
  256. return libvect.Vect_get_num_primitives(self.c_mapinfo,
  257. VTYPE[primitive])
  258. @must_be_open
  259. def number_of(self, vtype):
  260. """Return the number of the choosen element type
  261. :param vtype: the name of type to query; the supported values are:
  262. *areas*, *dblinks*, *faces*, *holes*, *islands*,
  263. *kernels*, *line_points*, *lines*, *nodes*,
  264. *update_lines*, *update_nodes*, *volumes*
  265. :type vtype: str
  266. >>> cens = VectorTopo('census')
  267. >>> cens.open(mode='r')
  268. >>> cens.number_of("areas")
  269. 2547
  270. >>> cens.number_of("islands")
  271. 49
  272. >>> cens.number_of("holes")
  273. 0
  274. >>> cens.number_of("lines")
  275. 8920
  276. >>> cens.number_of("nodes")
  277. 3885
  278. >>> cens.number_of("pizza")
  279. ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
  280. Traceback (most recent call last):
  281. ...
  282. ValueError: vtype not supported, use one of: 'areas', ...
  283. >>> cens.close()
  284. ..
  285. """
  286. if vtype in _NUMOF.keys():
  287. return _NUMOF[vtype](self.c_mapinfo)
  288. else:
  289. keys = "', '".join(sorted(_NUMOF.keys()))
  290. raise ValueError("vtype not supported, use one of: '%s'" % keys)
  291. @must_be_open
  292. def num_primitives(self):
  293. """Return dictionary with the number of all primitives
  294. """
  295. output = {}
  296. for prim in VTYPE.keys():
  297. output[prim] = self.num_primitive_of(prim)
  298. return output
  299. @must_be_open
  300. def viter(self, vtype, idonly=False):
  301. """Return an iterator of vector features
  302. :param vtype: the name of type to query; the supported values are:
  303. *areas*, *dblinks*, *faces*, *holes*, *islands*,
  304. *kernels*, *line_points*, *lines*, *nodes*,
  305. *update_lines*, *update_nodes*, *volumes*
  306. :type vtype: str
  307. :param idonly: variable to return only the id of features instead of
  308. full features
  309. :type idonly: bool
  310. >>> cens = VectorTopo('census', mode='r')
  311. >>> cens.open(mode='r')
  312. >>> big = [area for area in cens.viter('areas')
  313. ... if area.alive() and area.area() >= 10000]
  314. >>> big[:3]
  315. [Area(5), Area(6), Area(13)]
  316. to sort the result in a efficient way, use: ::
  317. >>> from operator import methodcaller as method
  318. >>> big.sort(key=method('area'), reverse=True) # sort the list
  319. >>> for area in big[:3]:
  320. ... print area, area.area()
  321. Area(2099) 5392751.5304
  322. Area(2171) 4799921.30863
  323. Area(495) 4055812.49695
  324. >>> cens.close()
  325. """
  326. if vtype in _GEOOBJ.keys():
  327. if _GEOOBJ[vtype] is not None:
  328. ids = (indx for indx in range(1, self.number_of(vtype) + 1))
  329. if idonly:
  330. return ids
  331. return (_GEOOBJ[vtype](v_id=indx, c_mapinfo=self.c_mapinfo,
  332. table=self.table,
  333. writable=self.writable)
  334. for indx in ids)
  335. else:
  336. keys = "', '".join(sorted(_GEOOBJ.keys()))
  337. raise ValueError("vtype not supported, use one of: '%s'" % keys)
  338. @must_be_open
  339. def rewind(self):
  340. """Rewind vector map to cause reads to start at beginning. ::
  341. >>> cens = VectorTopo('census')
  342. >>> cens.open(mode='r')
  343. >>> cens.next()
  344. Boundary(v_id=1)
  345. >>> cens.next()
  346. Boundary(v_id=2)
  347. >>> cens.next()
  348. Boundary(v_id=3)
  349. >>> cens.rewind()
  350. >>> cens.next()
  351. Boundary(v_id=1)
  352. >>> cens.close()
  353. ..
  354. """
  355. libvect.Vect_rewind(self.c_mapinfo)
  356. @must_be_open
  357. def cat(self, cat_id, vtype, layer=None, generator=False, geo=None):
  358. """Return the geometry features with category == cat_id.
  359. :param cat_id: the category number
  360. :type cat_id: int
  361. :param vtype: the type of geometry feature that we are looking for
  362. :type vtype: str
  363. :param layer: the layer number that will be used
  364. :type layer: int
  365. :param generator: if True return a generator otherwise it return a
  366. list of features
  367. :type generator: bool
  368. """
  369. if geo is None and vtype not in _GEOOBJ:
  370. keys = "', '".join(sorted(_GEOOBJ.keys()))
  371. raise ValueError("vtype not supported, use one of: '%s'" % keys)
  372. Obj = _GEOOBJ[vtype] if geo is None else geo
  373. ilist = Ilist()
  374. libvect.Vect_cidx_find_all(self.c_mapinfo,
  375. layer if layer else self.layer,
  376. Obj.gtype, cat_id, ilist.c_ilist)
  377. is2D = not self.is_3D()
  378. if generator:
  379. return (read_line(feature_id=v_id, c_mapinfo=self.c_mapinfo,
  380. table=self.table, writable=self.writable,
  381. is2D=is2D)
  382. for v_id in ilist)
  383. else:
  384. return [read_line(feature_id=v_id, c_mapinfo=self.c_mapinfo,
  385. table=self.table, writable=self.writable,
  386. is2D=is2D)
  387. for v_id in ilist]
  388. @must_be_open
  389. def read(self, feature_id):
  390. """Return a geometry object given the feature id.
  391. :param int feature_id: the id of feature to obtain
  392. >>> cens = VectorTopo('census')
  393. >>> cens.open(mode='r')
  394. >>> feature1 = cens.read(0) #doctest: +ELLIPSIS
  395. Traceback (most recent call last):
  396. ...
  397. ValueError: The index must be >0, 0 given.
  398. >>> feature1 = cens.read(1)
  399. >>> feature1
  400. Boundary(v_id=1)
  401. >>> feature1.length()
  402. 444.54490917696944
  403. >>> cens.read(-1)
  404. Centoid(642963.159711, 214994.016279)
  405. >>> len(cens)
  406. 8920
  407. >>> cens.read(8920)
  408. Centoid(642963.159711, 214994.016279)
  409. >>> cens.read(8921) #doctest: +ELLIPSIS
  410. Traceback (most recent call last):
  411. ...
  412. IndexError: Index out of range
  413. >>> cens.close()
  414. """
  415. return read_line(feature_id, self.c_mapinfo, self.table, self.writable,
  416. is2D=not self.is_3D())
  417. @must_be_open
  418. def is_empty(self):
  419. """Return if a vector map is empty or not
  420. """
  421. primitives = self.num_primitives()
  422. output = True
  423. for v in primitives.values():
  424. if v != 0:
  425. output = False
  426. break
  427. return output
  428. @must_be_open
  429. def rewrite(self, line, geo_obj, attrs=None, **kargs):
  430. """Rewrite a geometry features
  431. """
  432. if self.table is not None and attrs:
  433. attr = [line, ]
  434. attr.extend(attrs)
  435. self.table.update(key=line, values=attr)
  436. elif self.table is None and attrs:
  437. print "Table for vector {name} does not exist, attributes not" \
  438. " loaded".format(name=self.name)
  439. libvect.Vect_cat_set(geo_obj.c_cats, self.layer, line)
  440. result = libvect.Vect_rewrite_line(self.c_mapinfo,
  441. line, geo_obj.gtype,
  442. geo_obj.c_points,
  443. geo_obj.c_cats)
  444. if result == -1:
  445. raise GrassError("Not able to write the vector feature.")
  446. # return offset into file where the feature starts
  447. geo_obj.offset = result
  448. @must_be_open
  449. def delete(self, feature_id):
  450. """Remove a feature by its id
  451. :param feature_id: the id of the feature
  452. :type feature_id: int
  453. """
  454. if libvect.Vect_rewrite_line(self.c_mapinfo, feature_id) == -1:
  455. raise GrassError("C funtion: Vect_rewrite_line.")
  456. @must_be_open
  457. def restore(self, geo_obj):
  458. if hasattr(geo_obj, 'offset'):
  459. if libvect.Vect_restore_line(self.c_mapinfo, geo_obj.id,
  460. geo_obj.offset) == -1:
  461. raise GrassError("C funtion: Vect_restore_line.")
  462. else:
  463. raise ValueError("The value have not an offset attribute.")
  464. @must_be_open
  465. def bbox(self):
  466. """Return the BBox of the vecor map
  467. """
  468. bbox = Bbox()
  469. if libvect.Vect_get_map_box(self.c_mapinfo, bbox.c_bbox) == 0:
  470. raise GrassError("I can not find the Bbox.")
  471. return bbox
  472. @must_be_open
  473. def select_by_bbox(self, bbox):
  474. """Return the BBox of the vector map
  475. """
  476. # TODO replace with bbox if bbox else Bbox() ??
  477. bbox = Bbox()
  478. if libvect.Vect_get_map_box(self.c_mapinfo, bbox.c_bbox) == 0:
  479. raise GrassError("I can not find the Bbox.")
  480. return bbox
  481. def close(self, build=True, release=True):
  482. """Close the VectorTopo map, if release is True, the memory
  483. occupied by spatial index is released"""
  484. if release:
  485. libvect.Vect_set_release_support(self.c_mapinfo)
  486. super(VectorTopo, self).close(build=build)