__init__.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936
  1. # -*- coding: utf-8 -*-
  2. from __future__ import print_function
  3. from os.path import join, exists
  4. import grass.lib.gis as libgis
  5. libgis.G_gisinit('')
  6. import grass.lib.vector as libvect
  7. import ctypes
  8. #
  9. # import pygrass modules
  10. #
  11. from grass.pygrass.vector.vector_type import VTYPE
  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. "points": (libvect.Vect_get_num_primitives, libvect.GV_POINT),
  26. "lines": (libvect.Vect_get_num_primitives, libvect.GV_LINE),
  27. "centroids": (libvect.Vect_get_num_primitives, libvect.GV_CENTROID),
  28. "boundaries": (libvect.Vect_get_num_primitives, libvect.GV_BOUNDARY),
  29. "nodes": libvect.Vect_get_num_nodes,
  30. "updated_lines": libvect.Vect_get_num_updated_lines,
  31. "updated_nodes": libvect.Vect_get_num_updated_nodes,
  32. "volumes": libvect.Vect_get_num_volumes}
  33. # For test purposes
  34. test_vector_name = "vector_doctest_map"
  35. #=============================================
  36. # VECTOR
  37. #=============================================
  38. class Vector(Info):
  39. """Vector class is the grass vector format without topology
  40. >>> from grass.pygrass.vector import Vector
  41. >>> test_vect = Vector(test_vector_name)
  42. >>> test_vect.is_open()
  43. False
  44. >>> test_vect.mapset
  45. ''
  46. >>> test_vect.exist()
  47. True
  48. >>> test_vect.overwrite
  49. False
  50. """
  51. def __init__(self, name, mapset='', *args, **kwargs):
  52. # Set map name and mapset
  53. super(Vector, self).__init__(name, mapset, *args, **kwargs)
  54. self._topo_level = 1
  55. self._class_name = 'Vector'
  56. self.overwrite = False
  57. self._cats = []
  58. def __repr__(self):
  59. if self.exist():
  60. return "%s(%r, %r)" % (self._class_name, self.name, self.mapset)
  61. else:
  62. return "%s(%r)" % (self._class_name, self.name)
  63. def __iter__(self):
  64. """::
  65. >>> test_vect = Vector(test_vector_name)
  66. >>> test_vect.open(mode='r')
  67. >>> features = [feature for feature in test_vect]
  68. >>> features[:3]
  69. [Point(10.000000, 6.000000), Point(12.000000, 6.000000), Point(14.000000, 6.000000)]
  70. >>> test_vect.close()
  71. ..
  72. """
  73. #return (self.read(f_id) for f_id in xrange(self.num_of_features()))
  74. return self
  75. @must_be_open
  76. def __next__(self):
  77. """::
  78. >>> test_vect = Vector(test_vector_name)
  79. >>> test_vect.open(mode='r')
  80. >>> test_vect.next()
  81. Point(10.000000, 6.000000)
  82. >>> test_vect.next()
  83. Point(12.000000, 6.000000)
  84. >>> test_vect.close()
  85. ..
  86. """
  87. return read_next_line(self.c_mapinfo, self.table, self.writeable,
  88. is2D=not self.is_3D())
  89. @must_be_open
  90. def next(self):
  91. return self.__next__()
  92. @must_be_open
  93. def rewind(self):
  94. """Rewind vector map to cause reads to start at beginning."""
  95. if libvect.Vect_rewind(self.c_mapinfo) == -1:
  96. raise GrassError("Vect_rewind raise an error.")
  97. @must_be_open
  98. def write(self, geo_obj, cat=None, attrs=None):
  99. """Write geometry features and attributes.
  100. :param geo_obj: a geometry grass object define in
  101. grass.pygrass.vector.geometry
  102. :type geo_obj: geometry GRASS object
  103. :param attrs: a list with the values that will be insert in the
  104. attribute table.
  105. :type attrs: list
  106. :param cat: The category of the geometry feature, otherwise the
  107. c_cats attribute of the geometry object will be used.
  108. :type cat: integer
  109. Open a new vector map ::
  110. >>> new = VectorTopo('newvect')
  111. >>> new.exist()
  112. False
  113. define the new columns of the attribute table ::
  114. >>> cols = [(u'cat', 'INTEGER PRIMARY KEY'),
  115. ... (u'name', 'TEXT')]
  116. open the vector map in write mode
  117. >>> new.open('w', tab_name='newvect', tab_cols=cols)
  118. import a geometry feature ::
  119. >>> from grass.pygrass.vector.geometry import Point
  120. create two points ::
  121. >>> point0 = Point(0, 0)
  122. >>> point1 = Point(1, 1)
  123. then write the two points on the map, with ::
  124. >>> new.write(point0, cat=1, attrs=('pub',))
  125. >>> new.write(point1, cat=2, attrs=('resturant',))
  126. commit the db changes ::
  127. >>> new.table.conn.commit()
  128. >>> new.table.execute().fetchall()
  129. [(1, u'pub'), (2, u'resturant')]
  130. close the vector map ::
  131. >>> new.close()
  132. >>> new.exist()
  133. True
  134. then play with the map ::
  135. >>> new.open(mode='r')
  136. >>> new.read(1)
  137. Point(0.000000, 0.000000)
  138. >>> new.read(2)
  139. Point(1.000000, 1.000000)
  140. >>> new.read(1).attrs['name']
  141. u'pub'
  142. >>> new.read(2).attrs['name']
  143. u'resturant'
  144. >>> new.close()
  145. >>> new.remove()
  146. """
  147. self.n_lines += 1
  148. if not isinstance(cat, int) and not isinstance(cat, str):
  149. # likely the case of using 7.0 API
  150. import warnings
  151. warnings.warn("Vector.write(geo_obj, attrs=(...)) is"
  152. " depreciated, specify cat explicitly",
  153. DeprecationWarning)
  154. # try to accommodate
  155. attrs = cat
  156. cat = None
  157. if attrs and cat is None:
  158. # TODO: this does not work as expected when there are
  159. # already features in the map when we opened it
  160. cat = (self._cats[-1] if self._cats else 0) + 1
  161. if cat is not None and cat not in self._cats:
  162. self._cats.append(cat)
  163. if self.table is not None and attrs is not None:
  164. attr = [cat, ]
  165. attr.extend(attrs)
  166. cur = self.table.conn.cursor()
  167. cur.execute(self.table.columns.insert_str, attr)
  168. cur.close()
  169. if cat is not None:
  170. cats = Cats(geo_obj.c_cats)
  171. cats.reset()
  172. cats.set(cat, self.layer)
  173. if geo_obj.gtype == _Area.gtype:
  174. result = self._write_area(geo_obj)
  175. result = libvect.Vect_write_line(self.c_mapinfo, geo_obj.gtype,
  176. geo_obj.c_points, geo_obj.c_cats)
  177. if result == -1:
  178. raise GrassError("Not able to write the vector feature.")
  179. if self._topo_level == 2:
  180. # return new feature id (on level 2)
  181. geo_obj.id = result
  182. else:
  183. # return offset into file where the feature starts (on level 1)
  184. geo_obj.offset = result
  185. @must_be_open
  186. def has_color_table(self):
  187. """Return if vector has color table associated in file system;
  188. Color table stored in the vector's attribute table well be not checked
  189. >>> test_vect = Vector(test_vector_name)
  190. >>> test_vect.open(mode='r')
  191. >>> test_vect.has_color_table()
  192. False
  193. >>> test_vect.close()
  194. >>> from grass.pygrass.utils import copy, remove
  195. >>> copy(test_vector_name,'mytest_vect','vect')
  196. >>> from grass.pygrass.modules.shortcuts import vector as v
  197. >>> v.colors(map='mytest_vect', color='population', column='value')
  198. Module('v.colors')
  199. >>> mytest_vect = Vector('mytest_vect')
  200. >>> mytest_vect.open(mode='r')
  201. >>> mytest_vect.has_color_table()
  202. True
  203. >>> mytest_vect.close()
  204. >>> remove('mytest_vect', 'vect')
  205. """
  206. loc = Location()
  207. path = join(loc.path(), self.mapset, 'vector', self.name, 'colr')
  208. return True if exists(path) else False
  209. #=============================================
  210. # VECTOR WITH TOPOLOGY
  211. #=============================================
  212. class VectorTopo(Vector):
  213. """Vector class with the support of the GRASS topology.
  214. Open a vector map using the *with statement*: ::
  215. >>> with VectorTopo(test_vector_name, mode='r') as test_vect:
  216. ... for feature in test_vect[:7]:
  217. ... print(feature.attrs['name'])
  218. ...
  219. point
  220. point
  221. point
  222. line
  223. line
  224. line
  225. >>> test_vect.is_open()
  226. False
  227. ..
  228. """
  229. def __init__(self, name, mapset='', *args, **kwargs):
  230. super(VectorTopo, self).__init__(name, mapset, *args, **kwargs)
  231. self._topo_level = 2
  232. self._class_name = 'VectorTopo'
  233. def __len__(self):
  234. return libvect.Vect_get_num_lines(self.c_mapinfo)
  235. def __getitem__(self, key):
  236. """::
  237. >>> test_vect = VectorTopo(test_vector_name)
  238. >>> test_vect.open(mode='r')
  239. >>> test_vect[:4]
  240. [Point(10.000000, 6.000000), Point(12.000000, 6.000000), Point(14.000000, 6.000000)]
  241. >>> test_vect.close()
  242. ..
  243. """
  244. if isinstance(key, slice):
  245. return [self.read(indx)
  246. for indx in range(key.start if key.start else 1,
  247. key.stop if key.stop else len(self),
  248. key.step if key.step else 1)]
  249. elif isinstance(key, int):
  250. return self.read(key)
  251. else:
  252. raise ValueError("Invalid argument type: %r." % key)
  253. @must_be_open
  254. def num_primitive_of(self, primitive):
  255. """Return the number of primitive
  256. :param primitive: the name of primitive to query; the supported values are:
  257. * *boundary*,
  258. * *centroid*,
  259. * *face*,
  260. * *kernel*,
  261. * *line*,
  262. * *point*
  263. * *area*
  264. * *volume*
  265. :type primitive: str
  266. ::
  267. >>> test_vect = VectorTopo(test_vector_name)
  268. >>> test_vect.open(mode='r')
  269. >>> test_vect.num_primitive_of('point')
  270. 3
  271. >>> test_vect.num_primitive_of('line')
  272. 3
  273. >>> test_vect.num_primitive_of('centroid')
  274. 4
  275. >>> test_vect.num_primitive_of('boundary')
  276. 11
  277. >>> test_vect.close()
  278. ..
  279. """
  280. return libvect.Vect_get_num_primitives(self.c_mapinfo,
  281. VTYPE[primitive])
  282. @must_be_open
  283. def number_of(self, vtype):
  284. """Return the number of the chosen element type
  285. :param vtype: the name of type to query; the supported values are:
  286. *areas*, *dblinks*, *faces*, *holes*, *islands*,
  287. *kernels*, *points*, *lines*, *centroids*, *boundaries*,
  288. *nodes*, *line_points*, *update_lines*, *update_nodes*,
  289. *volumes*
  290. :type vtype: str
  291. >>> test_vect = VectorTopo(test_vector_name)
  292. >>> test_vect.open(mode='r')
  293. >>> test_vect.number_of("areas")
  294. 4
  295. >>> test_vect.number_of("islands")
  296. 2
  297. >>> test_vect.number_of("holes")
  298. 0
  299. >>> test_vect.number_of("lines")
  300. 21
  301. >>> test_vect.number_of("nodes")
  302. 15
  303. >>> test_vect.number_of("pizza")
  304. ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
  305. Traceback (most recent call last):
  306. ...
  307. ValueError: vtype not supported, use one of: 'areas', ...
  308. >>> test_vect.close()
  309. ..
  310. """
  311. if vtype in _NUMOF.keys():
  312. if isinstance(_NUMOF[vtype], tuple):
  313. fn, ptype = _NUMOF[vtype]
  314. return fn(self.c_mapinfo, ptype)
  315. else:
  316. return _NUMOF[vtype](self.c_mapinfo)
  317. else:
  318. keys = "', '".join(sorted(_NUMOF.keys()))
  319. raise ValueError("vtype not supported, use one of: '%s'" % keys)
  320. @must_be_open
  321. def num_primitives(self):
  322. """Return dictionary with the number of all primitives
  323. """
  324. output = {}
  325. for prim in VTYPE.keys():
  326. output[prim] = self.num_primitive_of(prim)
  327. return output
  328. @must_be_open
  329. def viter(self, vtype, idonly=False):
  330. """Return an iterator of vector features
  331. :param vtype: the name of type to query; the supported values are:
  332. *areas*, *dblinks*, *faces*, *holes*, *islands*,
  333. *kernels*, *line_points*, *lines*, *nodes*, *points*,
  334. *update_lines*, *update_nodes*, *volumes*
  335. :type vtype: str
  336. :param idonly: variable to return only the id of features instead of
  337. full features
  338. :type idonly: bool
  339. >>> test_vect = VectorTopo(test_vector_name, mode='r')
  340. >>> test_vect.open(mode='r')
  341. >>> areas = [area for area in test_vect.viter('areas')]
  342. >>> areas[:3]
  343. [Area(1), Area(2), Area(3)]
  344. to sort the result in a efficient way, use: ::
  345. >>> from operator import methodcaller as method
  346. >>> areas.sort(key=method('area'), reverse=True) # sort the list
  347. >>> for area in areas[:3]:
  348. ... print(area, area.area())
  349. Area(1) 12.0
  350. Area(2) 8.0
  351. Area(4) 8.0
  352. >>> areas = [area for area in test_vect.viter('areas')]
  353. >>> for area in areas:
  354. ... print(area.centroid().cat)
  355. 3
  356. 3
  357. 3
  358. 3
  359. >>> test_vect.close()
  360. """
  361. if vtype in _GEOOBJ.keys():
  362. if _GEOOBJ[vtype] is not None:
  363. ids = (indx for indx in range(1, self.number_of(vtype) + 1))
  364. if idonly:
  365. return ids
  366. return (_GEOOBJ[vtype](v_id=indx, c_mapinfo=self.c_mapinfo,
  367. table=self.table,
  368. writeable=self.writeable)
  369. for indx in ids)
  370. else:
  371. keys = "', '".join(sorted(_GEOOBJ.keys()))
  372. raise ValueError("vtype not supported, use one of: '%s'" % keys)
  373. @must_be_open
  374. def rewind(self):
  375. """Rewind vector map to cause reads to start at beginning. ::
  376. >>> test_vect = VectorTopo(test_vector_name)
  377. >>> test_vect.open(mode='r')
  378. >>> test_vect.next()
  379. Point(10.000000, 6.000000)
  380. >>> test_vect.next()
  381. Point(12.000000, 6.000000)
  382. >>> test_vect.next()
  383. Point(14.000000, 6.000000)
  384. >>> test_vect.rewind()
  385. >>> test_vect.next()
  386. Point(10.000000, 6.000000)
  387. >>> test_vect.close()
  388. ..
  389. """
  390. libvect.Vect_rewind(self.c_mapinfo)
  391. @must_be_open
  392. def cat(self, cat_id, vtype, layer=None, generator=False, geo=None):
  393. """Return the geometry features with category == cat_id.
  394. :param cat_id: the category number
  395. :type cat_id: int
  396. :param vtype: the type of geometry feature that we are looking for
  397. :type vtype: str
  398. :param layer: the layer number that will be used
  399. :type layer: int
  400. :param generator: if True return a generator otherwise it return a
  401. list of features
  402. :type generator: bool
  403. """
  404. if geo is None and vtype not in _GEOOBJ:
  405. keys = "', '".join(sorted(_GEOOBJ.keys()))
  406. raise ValueError("vtype not supported, use one of: '%s'" % keys)
  407. Obj = _GEOOBJ[vtype] if geo is None else geo
  408. ilist = Ilist()
  409. libvect.Vect_cidx_find_all(self.c_mapinfo,
  410. layer if layer else self.layer,
  411. Obj.gtype, cat_id, ilist.c_ilist)
  412. is2D = not self.is_3D()
  413. if generator:
  414. return (read_line(feature_id=v_id, c_mapinfo=self.c_mapinfo,
  415. table=self.table, writeable=self.writeable,
  416. is2D=is2D)
  417. for v_id in ilist)
  418. else:
  419. return [read_line(feature_id=v_id, c_mapinfo=self.c_mapinfo,
  420. table=self.table, writeable=self.writeable,
  421. is2D=is2D)
  422. for v_id in ilist]
  423. @must_be_open
  424. def read(self, feature_id):
  425. """Return a geometry object given the feature id.
  426. :param int feature_id: the id of feature to obtain
  427. >>> test_vect = VectorTopo(test_vector_name)
  428. >>> test_vect.open(mode='r')
  429. >>> feature1 = test_vect.read(0) #doctest: +ELLIPSIS
  430. Traceback (most recent call last):
  431. ...
  432. ValueError: The index must be >0, 0 given.
  433. >>> feature1 = test_vect.read(5)
  434. >>> feature1
  435. Line([Point(12.000000, 4.000000), Point(12.000000, 2.000000), Point(12.000000, 0.000000)])
  436. >>> feature1.length()
  437. 4.0
  438. >>> test_vect.read(-1)
  439. Centroid(7.500000, 3.500000)
  440. >>> len(test_vect)
  441. 21
  442. >>> test_vect.read(21)
  443. Centroid(7.500000, 3.500000)
  444. >>> test_vect.read(22) #doctest: +ELLIPSIS
  445. Traceback (most recent call last):
  446. ...
  447. IndexError: Index out of range
  448. >>> test_vect.close()
  449. """
  450. return read_line(feature_id, self.c_mapinfo, self.table, self.writeable,
  451. is2D=not self.is_3D())
  452. @must_be_open
  453. def is_empty(self):
  454. """Return if a vector map is empty or not
  455. """
  456. primitives = self.num_primitives()
  457. output = True
  458. for v in primitives.values():
  459. if v != 0:
  460. output = False
  461. break
  462. return output
  463. @must_be_open
  464. def rewrite(self, geo_obj, cat, attrs=None, **kargs):
  465. """Rewrite a geometry features
  466. >>> cols = [(u'cat', 'INTEGER PRIMARY KEY'),
  467. ... (u'name', 'TEXT')]
  468. Generate a new vector map
  469. >>> test_vect = VectorTopo('newvect_2')
  470. >>> test_vect.open('w', tab_name='newvect_2', tab_cols=cols,
  471. ... overwrite=True)
  472. import a geometry feature ::
  473. >>> from grass.pygrass.vector.geometry import Point
  474. create two points ::
  475. >>> point0 = Point(0, 0)
  476. >>> point1 = Point(1, 1)
  477. >>> point2 = Point(2, 2)
  478. then write the two points on the map, with ::
  479. >>> test_vect.write(point0, cat=1, attrs=('pub',))
  480. >>> test_vect.write(point1, cat=2, attrs=('resturant',))
  481. >>> test_vect.table.conn.commit() # save changes in the DB
  482. >>> test_vect.table_to_dict()
  483. {1: [1, u'pub'], 2: [2, u'resturant']}
  484. >>> test_vect.close()
  485. Now rewrite one point of the vector map: ::
  486. >>> test_vect.open('rw')
  487. >>> test_vect.rewrite(point2, cat=1, attrs=('Irish Pub',))
  488. >>> test_vect.table.conn.commit() # save changes in the DB
  489. >>> test_vect.close()
  490. Check the output:
  491. >>> test_vect.open('r')
  492. >>> test_vect[1] == point2
  493. True
  494. >>> test_vect[1].attrs['name'] == 'Irish Pub'
  495. True
  496. >>> test_vect.close()
  497. >>> test_vect.remove()
  498. """
  499. if self.table is not None and attrs:
  500. self.table.update(key=cat, values=attrs)
  501. elif self.table is None and attrs:
  502. print("Table for vector {name} does not exist, attributes not"
  503. " loaded".format(name=self.name))
  504. libvect.Vect_cat_set(geo_obj.c_cats, self.layer, cat)
  505. result = libvect.Vect_rewrite_line(self.c_mapinfo,
  506. cat, geo_obj.gtype,
  507. geo_obj.c_points,
  508. geo_obj.c_cats)
  509. if result == -1:
  510. raise GrassError("Not able to write the vector feature.")
  511. # return offset into file where the feature starts
  512. geo_obj.offset = result
  513. @must_be_open
  514. def delete(self, feature_id):
  515. """Remove a feature by its id
  516. :param feature_id: the id of the feature
  517. :type feature_id: int
  518. """
  519. if libvect.Vect_rewrite_line(self.c_mapinfo, feature_id) == -1:
  520. raise GrassError("C function: Vect_rewrite_line.")
  521. @must_be_open
  522. def restore(self, geo_obj):
  523. if hasattr(geo_obj, 'offset'):
  524. if libvect.Vect_restore_line(self.c_mapinfo, geo_obj.offset,
  525. geo_obj.id) == -1:
  526. raise GrassError("C function: Vect_restore_line.")
  527. else:
  528. raise ValueError("The value have not an offset attribute.")
  529. @must_be_open
  530. def bbox(self):
  531. """Return the BBox of the vecor map
  532. """
  533. bbox = Bbox()
  534. if libvect.Vect_get_map_box(self.c_mapinfo, bbox.c_bbox) == 0:
  535. raise GrassError("I can not find the Bbox.")
  536. return bbox
  537. def close(self, build=True, release=True):
  538. """Close the VectorTopo map, if release is True, the memory
  539. occupied by spatial index is released"""
  540. if release:
  541. libvect.Vect_set_release_support(self.c_mapinfo)
  542. super(VectorTopo, self).close(build=build)
  543. @must_be_open
  544. def table_to_dict(self, where=None):
  545. """Return the attribute table as a dictionary with the category as keys
  546. The columns have the order of the self.table.columns.names() list.
  547. Examples
  548. >>> from grass.pygrass.vector import VectorTopo
  549. >>> from grass.pygrass.vector.basic import Bbox
  550. >>> test_vect = VectorTopo(test_vector_name)
  551. >>> test_vect.open('r')
  552. >>> test_vect.table_to_dict()
  553. {1: [1, u'point', 1.0], 2: [2, u'line', 2.0], 3: [3, u'centroid', 3.0]}
  554. >>> test_vect.table_to_dict(where="value > 2")
  555. {3: [3, u'centroid', 3.0]}
  556. >>> test_vect.table_to_dict(where="value > 0")
  557. {1: [1, u'point', 1.0], 2: [2, u'line', 2.0], 3: [3, u'centroid', 3.0]}
  558. >>> test_vect.table.filters.get_sql()
  559. u'SELECT cat,name,value FROM vector_doctest_map WHERE value > 0 ORDER BY cat;'
  560. """
  561. if self.table is not None:
  562. table_dict = {}
  563. # Get the category index
  564. cat_index = self.table.columns.names().index("cat")
  565. # Prepare a filter
  566. if where is not None:
  567. self.table.filters.where(where)
  568. self.table.filters.order_by("cat")
  569. self.table.filters.select(",".join(self.table.columns.names()))
  570. # Execute the query and fetch the result
  571. cur = self.table.execute()
  572. l = cur.fetchall()
  573. # Generate the dictionary
  574. for entry in l:
  575. table_dict[entry[cat_index]] = list(entry)
  576. return(table_dict)
  577. return None
  578. @must_be_open
  579. def features_to_wkb_list(self, bbox=None, feature_type="point", field=1):
  580. """Return all features of type point, line, boundary or centroid
  581. as a list of Well Known Binary representations (WKB)
  582. (id, cat, wkb) triplets located in a specific
  583. bounding box.
  584. :param bbox: The boundingbox to search for features,
  585. if bbox=None the boundingbox of the whole
  586. vector map layer is used
  587. :type bbox: grass.pygrass.vector.basic.Bbox
  588. :param feature_type: The type of feature that should be converted to
  589. the Well Known Binary (WKB) format. Supported are:
  590. 'point' -> libvect.GV_POINT 1
  591. 'line' -> libvect.GV_LINE 2
  592. 'boundary' -> libvect.GV_BOUNDARY 3
  593. 'centroid' -> libvect.GV_CENTROID 4
  594. :type type: string
  595. :param field: The category field
  596. :type field: integer
  597. :return: A list of triplets, or None if nothing was found
  598. The well known binary are stored in byte arrays.
  599. Examples:
  600. >>> from grass.pygrass.vector import VectorTopo
  601. >>> from grass.pygrass.vector.basic import Bbox
  602. >>> test_vect = VectorTopo(test_vector_name)
  603. >>> test_vect.open('r')
  604. >>> bbox = Bbox(north=20, south=-1, east=20, west=-1)
  605. >>> result = test_vect.features_to_wkb_list(bbox=bbox,
  606. ... feature_type="point")
  607. >>> len(result)
  608. 3
  609. >>> for entry in result:
  610. ... f_id, cat, wkb = entry
  611. ... print((f_id, cat, len(wkb)))
  612. (1, 1, 21)
  613. (2, 1, 21)
  614. (3, 1, 21)
  615. >>> result = test_vect.features_to_wkb_list(bbox=None,
  616. ... feature_type="line")
  617. >>> len(result)
  618. 3
  619. >>> for entry in result:
  620. ... f_id, cat, wkb = entry
  621. ... print((f_id, cat, len(wkb)))
  622. (4, 2, 57)
  623. (5, 2, 57)
  624. (6, 2, 57)
  625. >>> result = test_vect.features_to_wkb_list(bbox=bbox,
  626. ... feature_type="boundary")
  627. >>> len(result)
  628. 11
  629. >>> result = test_vect.features_to_wkb_list(bbox=None,
  630. ... feature_type="centroid")
  631. >>> len(result)
  632. 4
  633. >>> for entry in result:
  634. ... f_id, cat, wkb = entry
  635. ... print((f_id, cat, len(wkb)))
  636. (19, 3, 21)
  637. (18, 3, 21)
  638. (20, 3, 21)
  639. (21, 3, 21)
  640. >>> result = test_vect.features_to_wkb_list(bbox=bbox,
  641. ... feature_type="blub")
  642. Traceback (most recent call last):
  643. ...
  644. GrassError: Unsupported feature type <blub>, supported are <point,line,boundary,centroid>
  645. >>> test_vect.close()
  646. """
  647. supported = ['point', 'line', 'boundary', 'centroid']
  648. if feature_type.lower() not in supported:
  649. raise GrassError("Unsupported feature type <%s>, "\
  650. "supported are <%s>"%(feature_type,
  651. ",".join(supported)))
  652. if bbox is None:
  653. bbox = self.bbox()
  654. bboxlist = self.find_by_bbox.geos(bbox, type=feature_type.lower(),
  655. bboxlist_only = True)
  656. if bboxlist is not None and len(bboxlist) > 0:
  657. l = []
  658. line_p = libvect.line_pnts()
  659. line_c = libvect.line_cats()
  660. size = ctypes.c_size_t()
  661. cat = ctypes.c_int()
  662. error = ctypes.c_int()
  663. for f_id in bboxlist.ids:
  664. barray = libvect.Vect_read_line_to_wkb(self.c_mapinfo,
  665. ctypes.byref(line_p),
  666. ctypes.byref(line_c),
  667. f_id,
  668. ctypes.byref(size),
  669. ctypes.byref(error))
  670. if not barray:
  671. if error == -1:
  672. raise GrassError(_("Unable to read line of feature %i"%(f_id)))
  673. if error == -2:
  674. print("Empty feature %i"%(f_id))
  675. continue
  676. ok = libvect.Vect_cat_get(ctypes.byref(line_c), field,
  677. ctypes.byref(cat))
  678. if ok < 1:
  679. pcat = None
  680. else:
  681. pcat = cat.value
  682. l.append((f_id, pcat, ctypes.string_at(barray, size.value)))
  683. libgis.G_free(barray)
  684. return l
  685. return None
  686. @must_be_open
  687. def areas_to_wkb_list(self, bbox=None, field=1):
  688. """Return all features of type point, line, boundary or centroid
  689. as a list of Well Known Binary representations (WKB)
  690. (id, cat, wkb) triplets located in a specific
  691. bounding box.
  692. :param bbox: The boundingbox to search for features,
  693. if bbox=None the boundingbox of the whole
  694. vector map layer is used
  695. :type bbox: grass.pygrass.vector.basic.Bbox
  696. :param field: The centroid category field
  697. :type field: integer
  698. :return: A list of triplets, or None if nothing was found
  699. The well known binary are stored in byte arrays.
  700. Examples:
  701. >>> from grass.pygrass.vector import VectorTopo
  702. >>> from grass.pygrass.vector.basic import Bbox
  703. >>> test_vect = VectorTopo(test_vector_name)
  704. >>> test_vect.open('r')
  705. >>> bbox = Bbox(north=20, south=-1, east=20, west=-1)
  706. >>> result = test_vect.areas_to_wkb_list(bbox=bbox)
  707. >>> len(result)
  708. 4
  709. >>> for entry in result:
  710. ... a_id, cat, wkb = entry
  711. ... print((a_id, cat, len(wkb)))
  712. (1, 3, 225)
  713. (2, 3, 141)
  714. (3, 3, 93)
  715. (4, 3, 141)
  716. >>> result = test_vect.areas_to_wkb_list()
  717. >>> len(result)
  718. 4
  719. >>> for entry in result:
  720. ... a_id, cat, wkb = entry
  721. ... print((a_id, cat, len(wkb)))
  722. (1, 3, 225)
  723. (2, 3, 141)
  724. (3, 3, 93)
  725. (4, 3, 141)
  726. >>> test_vect.close()
  727. """
  728. if bbox is None:
  729. bbox = self.bbox()
  730. bboxlist = self.find_by_bbox.areas(bbox, bboxlist_only = True)
  731. if bboxlist is not None and len(bboxlist) > 0:
  732. l = []
  733. line_c = libvect.line_cats()
  734. size = ctypes.c_size_t()
  735. cat = ctypes.c_int()
  736. for a_id in bboxlist.ids:
  737. barray = libvect.Vect_read_area_to_wkb(self.c_mapinfo,
  738. a_id,
  739. ctypes.byref(size))
  740. if not barray:
  741. raise GrassError(_("Unable to read area with id %i"%(a_id)))
  742. pcat = None
  743. c_ok = libvect.Vect_get_area_cats(self.c_mapinfo, a_id,
  744. ctypes.byref(line_c))
  745. if c_ok == 0: # Centroid found
  746. ok = libvect.Vect_cat_get(ctypes.byref(line_c), field,
  747. ctypes.byref(cat))
  748. if ok > 0:
  749. pcat = cat.value
  750. l.append((a_id, pcat, ctypes.string_at(barray, size.value)))
  751. libgis.G_free(barray)
  752. return l
  753. return None
  754. if __name__ == "__main__":
  755. import doctest
  756. from grass.pygrass import utils
  757. utils.create_test_vector_map(test_vector_name)
  758. doctest.testmod()
  759. """Remove the generated vector map, if exist"""
  760. from grass.pygrass.utils import get_mapset_vector
  761. from grass.script.core import run_command
  762. mset = get_mapset_vector(test_vector_name, mapset='')
  763. if mset:
  764. run_command("g.remove", flags='f', type='vector', name=test_vector_name)