__init__.py 30 KB

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