__init__.py 32 KB

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