__init__.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  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, geo_obj, cat, attrs=None, **kargs):
  444. """Rewrite a geometry features
  445. >>> cols = [(u'cat', 'INTEGER PRIMARY KEY'),
  446. ... (u'name', 'TEXT')]
  447. Generate a new vector map
  448. >>> test_vect = VectorTopo(test_vector_name)
  449. >>> test_vect.open('w', tab_name='newvect', tab_cols=cols,
  450. ... overwrite=True)
  451. import a geometry feature ::
  452. >>> from grass.pygrass.vector.geometry import Point
  453. create two points ::
  454. >>> point0 = Point(0, 0)
  455. >>> point1 = Point(1, 1)
  456. >>> point2 = Point(2, 2)
  457. then write the two points on the map, with ::
  458. >>> test_vect.write(point0, cat=1, attrs=('pub',))
  459. >>> test_vect.write(point1, cat=2, attrs=('resturant',))
  460. >>> test_vect.table.conn.commit() # save changes in the DB
  461. >>> test_vect.close()
  462. Now rewrite on point of the vector map: ::
  463. >>> test_vect.open('rw')
  464. >>> test_vect.rewrite(point2, cat=1, attrs('Irish Pub'))
  465. >>> test_vect.table.conn.commit() # save changes in the DB
  466. >>> test_vect.close()
  467. Check the output:
  468. >>> test_vect.open('r')
  469. >>> test_vect[1] == point2
  470. True
  471. >>> test_vect[1].attrs['name'] == 'Irish Pub'
  472. True
  473. >>> test_vect.close()
  474. """
  475. if self.table is not None and attrs:
  476. self.table.update(key=cat, values=attrs)
  477. elif self.table is None and attrs:
  478. print("Table for vector {name} does not exist, attributes not"
  479. " loaded".format(name=self.name))
  480. libvect.Vect_cat_set(geo_obj.c_cats, self.layer, cat)
  481. result = libvect.Vect_rewrite_line(self.c_mapinfo,
  482. cat, geo_obj.gtype,
  483. geo_obj.c_points,
  484. geo_obj.c_cats)
  485. if result == -1:
  486. raise GrassError("Not able to write the vector feature.")
  487. # return offset into file where the feature starts
  488. geo_obj.offset = result
  489. @must_be_open
  490. def delete(self, feature_id):
  491. """Remove a feature by its id
  492. :param feature_id: the id of the feature
  493. :type feature_id: int
  494. """
  495. if libvect.Vect_rewrite_line(self.c_mapinfo, feature_id) == -1:
  496. raise GrassError("C funtion: Vect_rewrite_line.")
  497. @must_be_open
  498. def restore(self, geo_obj):
  499. if hasattr(geo_obj, 'offset'):
  500. if libvect.Vect_restore_line(self.c_mapinfo, geo_obj.offset,
  501. geo_obj.id) == -1:
  502. raise GrassError("C funtion: Vect_restore_line.")
  503. else:
  504. raise ValueError("The value have not an offset attribute.")
  505. @must_be_open
  506. def bbox(self):
  507. """Return the BBox of the vecor map
  508. """
  509. bbox = Bbox()
  510. if libvect.Vect_get_map_box(self.c_mapinfo, bbox.c_bbox) == 0:
  511. raise GrassError("I can not find the Bbox.")
  512. return bbox
  513. def close(self, build=True, release=True):
  514. """Close the VectorTopo map, if release is True, the memory
  515. occupied by spatial index is released"""
  516. if release:
  517. libvect.Vect_set_release_support(self.c_mapinfo)
  518. super(VectorTopo, self).close(build=build)
  519. @must_be_open
  520. def table_to_dict(self, where=None):
  521. """Return the attribute table as a dictionary with the category as keys
  522. The columns have the order of the self.table.columns.names() list.
  523. Examples
  524. >>> from grass.pygrass.vector import VectorTopo
  525. >>> from grass.pygrass.vector.basic import Bbox
  526. >>> test_vect = VectorTopo(test_vector_name)
  527. >>> test_vect.open('r')
  528. >>> test_vect.table_to_dict()
  529. {1: [1, u'point', 1.0], 2: [2, u'line', 2.0], 3: [3, u'centroid', 3.0]}
  530. >>> test_vect.table_to_dict(where="value > 2")
  531. {3: [3, u'centroid', 3.0]}
  532. >>> test_vect.table_to_dict(where="value > 0")
  533. {1: [1, u'point', 1.0], 2: [2, u'line', 2.0], 3: [3, u'centroid', 3.0]}
  534. >>> test_vect.table.filters.get_sql()
  535. u'SELECT cat,name,value FROM vector_doctest_map WHERE value > 0 ORDER BY cat;'
  536. """
  537. if self.table is not None:
  538. table_dict = {}
  539. # Get the category index
  540. cat_index = self.table.columns.names().index("cat")
  541. # Prepare a filter
  542. if where is not None:
  543. self.table.filters.where(where)
  544. self.table.filters.order_by("cat")
  545. self.table.filters.select(",".join(self.table.columns.names()))
  546. # Execute the query and fetch the result
  547. cur = self.table.execute()
  548. l = cur.fetchall()
  549. # Generate the dictionary
  550. for entry in l:
  551. table_dict[entry[cat_index]] = list(entry)
  552. return(table_dict)
  553. return None
  554. @must_be_open
  555. def features_to_wkb_list(self, bbox=None, feature_type="point", field=1):
  556. """Return all features of type point, line, boundary or centroid
  557. as a list of Well Known Binary representations (WKB)
  558. (id, cat, wkb) triplets located in a specific
  559. bounding box.
  560. :param bbox: The boundingbox to search for features,
  561. if bbox=None the boundingbox of the whole
  562. vector map layer is used
  563. :type bbox: grass.pygrass.vector.basic.Bbox
  564. :param feature_type: The type of feature that should be converted to
  565. the Well Known Binary (WKB) format. Supported are:
  566. 'point' -> libvect.GV_POINT 1
  567. 'line' -> libvect.GV_LINE 2
  568. 'boundary' -> libvect.GV_BOUNDARY 3
  569. 'centroid' -> libvect.GV_CENTROID 4
  570. :type type: string
  571. :param field: The category field
  572. :type field: integer
  573. :return: A list of triplets, or None if nothing was found
  574. The well known binary are stored in byte arrays.
  575. Examples:
  576. >>> from grass.pygrass.vector import VectorTopo
  577. >>> from grass.pygrass.vector.basic import Bbox
  578. >>> test_vect = VectorTopo(test_vector_name)
  579. >>> test_vect.open('r')
  580. >>> bbox = Bbox(north=20, south=-1, east=20, west=-1)
  581. >>> result = test_vect.features_to_wkb_list(bbox=bbox,
  582. ... feature_type="point")
  583. >>> len(result)
  584. 3
  585. >>> for entry in result:
  586. ... f_id, cat, wkb = entry
  587. ... print((f_id, cat, len(wkb)))
  588. (1, 1, 21)
  589. (2, 1, 21)
  590. (3, 1, 21)
  591. >>> result = test_vect.features_to_wkb_list(bbox=None,
  592. ... feature_type="line")
  593. >>> len(result)
  594. 3
  595. >>> for entry in result:
  596. ... f_id, cat, wkb = entry
  597. ... print((f_id, cat, len(wkb)))
  598. (4, 2, 57)
  599. (5, 2, 57)
  600. (6, 2, 57)
  601. >>> result = test_vect.features_to_wkb_list(bbox=bbox,
  602. ... feature_type="boundary")
  603. >>> len(result)
  604. 11
  605. >>> result = test_vect.features_to_wkb_list(bbox=None,
  606. ... feature_type="centroid")
  607. >>> len(result)
  608. 4
  609. >>> for entry in result:
  610. ... f_id, cat, wkb = entry
  611. ... print((f_id, cat, len(wkb)))
  612. (19, 3, 21)
  613. (18, 3, 21)
  614. (20, 3, 21)
  615. (21, 3, 21)
  616. >>> result = test_vect.features_to_wkb_list(bbox=bbox,
  617. ... feature_type="blub")
  618. Traceback (most recent call last):
  619. ...
  620. GrassError: Unsupported feature type <blub>, supported are <point,line,boundary,centroid>
  621. >>> test_vect.close()
  622. """
  623. supported = ['point', 'line', 'boundary', 'centroid']
  624. if feature_type.lower() not in supported:
  625. raise GrassError("Unsupported feature type <%s>, "\
  626. "supported are <%s>"%(feature_type,
  627. ",".join(supported)))
  628. if bbox is None:
  629. bbox = self.bbox()
  630. bboxlist = self.find_by_bbox.geos(bbox, type=feature_type.lower(),
  631. bboxlist_only = True)
  632. if bboxlist is not None and len(bboxlist) > 0:
  633. l = []
  634. line_p = libvect.line_pnts()
  635. line_c = libvect.line_cats()
  636. size = ctypes.c_size_t()
  637. cat = ctypes.c_int()
  638. error = ctypes.c_int()
  639. for f_id in bboxlist.ids:
  640. barray = libvect.Vect_read_line_to_wkb(self.c_mapinfo,
  641. ctypes.byref(line_p),
  642. ctypes.byref(line_c),
  643. f_id,
  644. ctypes.byref(size),
  645. ctypes.byref(error))
  646. if not barray:
  647. if error == -1:
  648. raise GrassError(_("Unable to read line of feature %i"%(f_id)))
  649. if error == -2:
  650. print("Empty feature %i"%(f_id))
  651. continue
  652. ok = libvect.Vect_cat_get(ctypes.byref(line_c), field,
  653. ctypes.byref(cat))
  654. if ok < 1:
  655. pcat = None
  656. else:
  657. pcat = cat.value
  658. l.append((f_id, pcat, ctypes.string_at(barray, size.value)))
  659. libgis.G_free(barray)
  660. return l
  661. return None
  662. @must_be_open
  663. def areas_to_wkb_list(self, bbox=None, field=1):
  664. """Return all features of type point, line, boundary or centroid
  665. as a list of Well Known Binary representations (WKB)
  666. (id, cat, wkb) triplets located in a specific
  667. bounding box.
  668. :param bbox: The boundingbox to search for features,
  669. if bbox=None the boundingbox of the whole
  670. vector map layer is used
  671. :type bbox: grass.pygrass.vector.basic.Bbox
  672. :param field: The centroid category field
  673. :type field: integer
  674. :return: A list of triplets, or None if nothing was found
  675. The well known binary are stored in byte arrays.
  676. Examples:
  677. >>> from grass.pygrass.vector import VectorTopo
  678. >>> from grass.pygrass.vector.basic import Bbox
  679. >>> test_vect = VectorTopo(test_vector_name)
  680. >>> test_vect.open('r')
  681. >>> bbox = Bbox(north=20, south=-1, east=20, west=-1)
  682. >>> result = test_vect.areas_to_wkb_list(bbox=bbox)
  683. >>> len(result)
  684. 4
  685. >>> for entry in result:
  686. ... a_id, cat, wkb = entry
  687. ... print((a_id, cat, len(wkb)))
  688. (1, 3, 225)
  689. (2, 3, 141)
  690. (3, 3, 93)
  691. (4, 3, 141)
  692. >>> result = test_vect.areas_to_wkb_list()
  693. >>> len(result)
  694. 4
  695. >>> for entry in result:
  696. ... a_id, cat, wkb = entry
  697. ... print((a_id, cat, len(wkb)))
  698. (1, 3, 225)
  699. (2, 3, 141)
  700. (3, 3, 93)
  701. (4, 3, 141)
  702. >>> test_vect.close()
  703. """
  704. if bbox is None:
  705. bbox = self.bbox()
  706. bboxlist = self.find_by_bbox.areas(bbox, bboxlist_only = True)
  707. if bboxlist is not None and len(bboxlist) > 0:
  708. l = []
  709. line_c = libvect.line_cats()
  710. size = ctypes.c_size_t()
  711. cat = ctypes.c_int()
  712. for a_id in bboxlist.ids:
  713. barray = libvect.Vect_read_area_to_wkb(self.c_mapinfo,
  714. a_id,
  715. ctypes.byref(size))
  716. if not barray:
  717. raise GrassError(_("Unable to read area with id %i"%(a_id)))
  718. pcat = None
  719. c_ok = libvect.Vect_get_area_cats(self.c_mapinfo, a_id,
  720. ctypes.byref(line_c))
  721. if c_ok == 0: # Centroid found
  722. ok = libvect.Vect_cat_get(ctypes.byref(line_c), field,
  723. ctypes.byref(cat))
  724. if ok > 0:
  725. pcat = cat.value
  726. l.append((a_id, pcat, ctypes.string_at(barray, size.value)))
  727. libgis.G_free(barray)
  728. return l
  729. return None
  730. if __name__ == "__main__":
  731. import doctest
  732. from grass.pygrass import utils
  733. utils.create_test_vector_map(test_vector_name)
  734. doctest.testmod()
  735. """Remove the generated vector map, if exist"""
  736. from grass.pygrass.utils import get_mapset_vector
  737. from grass.script.core import run_command
  738. mset = get_mapset_vector(test_vector_name, mapset='')
  739. if mset:
  740. run_command("g.remove", flags='f', type='vector', name=test_vector_name)