__init__.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929
  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. "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. if isinstance(_NUMOF[vtype], tuple):
  307. fn, ptype = _NUMOF[vtype]
  308. return fn(self.c_mapinfo, ptype)
  309. else:
  310. return _NUMOF[vtype](self.c_mapinfo)
  311. else:
  312. keys = "', '".join(sorted(_NUMOF.keys()))
  313. raise ValueError("vtype not supported, use one of: '%s'" % keys)
  314. @must_be_open
  315. def num_primitives(self):
  316. """Return dictionary with the number of all primitives
  317. """
  318. output = {}
  319. for prim in VTYPE.keys():
  320. output[prim] = self.num_primitive_of(prim)
  321. return output
  322. @must_be_open
  323. def viter(self, vtype, idonly=False):
  324. """Return an iterator of vector features
  325. :param vtype: the name of type to query; the supported values are:
  326. *areas*, *dblinks*, *faces*, *holes*, *islands*,
  327. *kernels*, *line_points*, *lines*, *nodes*, *points*,
  328. *update_lines*, *update_nodes*, *volumes*
  329. :type vtype: str
  330. :param idonly: variable to return only the id of features instead of
  331. full features
  332. :type idonly: bool
  333. >>> test_vect = VectorTopo(test_vector_name, mode='r')
  334. >>> test_vect.open(mode='r')
  335. >>> areas = [area for area in test_vect.viter('areas')]
  336. >>> areas[:3]
  337. [Area(1), Area(2), Area(3)]
  338. to sort the result in a efficient way, use: ::
  339. >>> from operator import methodcaller as method
  340. >>> areas.sort(key=method('area'), reverse=True) # sort the list
  341. >>> for area in areas[:3]:
  342. ... print(area, area.area())
  343. Area(1) 12.0
  344. Area(2) 8.0
  345. Area(4) 8.0
  346. >>> areas = [area for area in test_vect.viter('areas')]
  347. >>> for area in areas:
  348. ... print(area.centroid().cat)
  349. 3
  350. 3
  351. 3
  352. 3
  353. >>> test_vect.close()
  354. """
  355. if vtype in _GEOOBJ.keys():
  356. if _GEOOBJ[vtype] is not None:
  357. ids = (indx for indx in range(1, self.number_of(vtype) + 1))
  358. if idonly:
  359. return ids
  360. return (_GEOOBJ[vtype](v_id=indx, c_mapinfo=self.c_mapinfo,
  361. table=self.table,
  362. writeable=self.writeable)
  363. for indx in ids)
  364. else:
  365. keys = "', '".join(sorted(_GEOOBJ.keys()))
  366. raise ValueError("vtype not supported, use one of: '%s'" % keys)
  367. @must_be_open
  368. def rewind(self):
  369. """Rewind vector map to cause reads to start at beginning. ::
  370. >>> test_vect = VectorTopo(test_vector_name)
  371. >>> test_vect.open(mode='r')
  372. >>> test_vect.next()
  373. Point(10.000000, 6.000000)
  374. >>> test_vect.next()
  375. Point(12.000000, 6.000000)
  376. >>> test_vect.next()
  377. Point(14.000000, 6.000000)
  378. >>> test_vect.rewind()
  379. >>> test_vect.next()
  380. Point(10.000000, 6.000000)
  381. >>> test_vect.close()
  382. ..
  383. """
  384. libvect.Vect_rewind(self.c_mapinfo)
  385. @must_be_open
  386. def cat(self, cat_id, vtype, layer=None, generator=False, geo=None):
  387. """Return the geometry features with category == cat_id.
  388. :param cat_id: the category number
  389. :type cat_id: int
  390. :param vtype: the type of geometry feature that we are looking for
  391. :type vtype: str
  392. :param layer: the layer number that will be used
  393. :type layer: int
  394. :param generator: if True return a generator otherwise it return a
  395. list of features
  396. :type generator: bool
  397. """
  398. if geo is None and vtype not in _GEOOBJ:
  399. keys = "', '".join(sorted(_GEOOBJ.keys()))
  400. raise ValueError("vtype not supported, use one of: '%s'" % keys)
  401. Obj = _GEOOBJ[vtype] if geo is None else geo
  402. ilist = Ilist()
  403. libvect.Vect_cidx_find_all(self.c_mapinfo,
  404. layer if layer else self.layer,
  405. Obj.gtype, cat_id, ilist.c_ilist)
  406. is2D = not self.is_3D()
  407. if generator:
  408. return (read_line(feature_id=v_id, c_mapinfo=self.c_mapinfo,
  409. table=self.table, writeable=self.writeable,
  410. is2D=is2D)
  411. for v_id in ilist)
  412. else:
  413. return [read_line(feature_id=v_id, c_mapinfo=self.c_mapinfo,
  414. table=self.table, writeable=self.writeable,
  415. is2D=is2D)
  416. for v_id in ilist]
  417. @must_be_open
  418. def read(self, feature_id):
  419. """Return a geometry object given the feature id.
  420. :param int feature_id: the id of feature to obtain
  421. >>> test_vect = VectorTopo(test_vector_name)
  422. >>> test_vect.open(mode='r')
  423. >>> feature1 = test_vect.read(0) #doctest: +ELLIPSIS
  424. Traceback (most recent call last):
  425. ...
  426. ValueError: The index must be >0, 0 given.
  427. >>> feature1 = test_vect.read(5)
  428. >>> feature1
  429. Line([Point(12.000000, 4.000000), Point(12.000000, 2.000000), Point(12.000000, 0.000000)])
  430. >>> feature1.length()
  431. 4.0
  432. >>> test_vect.read(-1)
  433. Centroid(7.500000, 3.500000)
  434. >>> len(test_vect)
  435. 21
  436. >>> test_vect.read(21)
  437. Centroid(7.500000, 3.500000)
  438. >>> test_vect.read(22) #doctest: +ELLIPSIS
  439. Traceback (most recent call last):
  440. ...
  441. IndexError: Index out of range
  442. >>> test_vect.close()
  443. """
  444. return read_line(feature_id, self.c_mapinfo, self.table, self.writeable,
  445. is2D=not self.is_3D())
  446. @must_be_open
  447. def is_empty(self):
  448. """Return if a vector map is empty or not
  449. """
  450. primitives = self.num_primitives()
  451. output = True
  452. for v in primitives.values():
  453. if v != 0:
  454. output = False
  455. break
  456. return output
  457. @must_be_open
  458. def rewrite(self, geo_obj, cat, attrs=None, **kargs):
  459. """Rewrite a geometry features
  460. >>> cols = [(u'cat', 'INTEGER PRIMARY KEY'),
  461. ... (u'name', 'TEXT')]
  462. Generate a new vector map
  463. >>> test_vect = VectorTopo('newvect_2')
  464. >>> test_vect.open('w', tab_name='newvect_2', tab_cols=cols,
  465. ... overwrite=True)
  466. import a geometry feature ::
  467. >>> from grass.pygrass.vector.geometry import Point
  468. create two points ::
  469. >>> point0 = Point(0, 0)
  470. >>> point1 = Point(1, 1)
  471. >>> point2 = Point(2, 2)
  472. then write the two points on the map, with ::
  473. >>> test_vect.write(point0, cat=1, attrs=('pub',))
  474. >>> test_vect.write(point1, cat=2, attrs=('resturant',))
  475. >>> test_vect.table.conn.commit() # save changes in the DB
  476. >>> test_vect.table_to_dict()
  477. {1: [1, u'pub'], 2: [2, u'resturant']}
  478. >>> test_vect.close()
  479. Now rewrite one point of the vector map: ::
  480. >>> test_vect.open('rw')
  481. >>> test_vect.rewrite(point2, cat=1, attrs=('Irish Pub',))
  482. >>> test_vect.table.conn.commit() # save changes in the DB
  483. >>> test_vect.close()
  484. Check the output:
  485. >>> test_vect.open('r')
  486. >>> test_vect[1] == point2
  487. True
  488. >>> test_vect[1].attrs['name'] == 'Irish Pub'
  489. True
  490. >>> test_vect.close()
  491. >>> test_vect.remove()
  492. """
  493. if self.table is not None and attrs:
  494. self.table.update(key=cat, values=attrs)
  495. elif self.table is None and attrs:
  496. print("Table for vector {name} does not exist, attributes not"
  497. " loaded".format(name=self.name))
  498. libvect.Vect_cat_set(geo_obj.c_cats, self.layer, cat)
  499. result = libvect.Vect_rewrite_line(self.c_mapinfo,
  500. cat, geo_obj.gtype,
  501. geo_obj.c_points,
  502. geo_obj.c_cats)
  503. if result == -1:
  504. raise GrassError("Not able to write the vector feature.")
  505. # return offset into file where the feature starts
  506. geo_obj.offset = result
  507. @must_be_open
  508. def delete(self, feature_id):
  509. """Remove a feature by its id
  510. :param feature_id: the id of the feature
  511. :type feature_id: int
  512. """
  513. if libvect.Vect_rewrite_line(self.c_mapinfo, feature_id) == -1:
  514. raise GrassError("C function: Vect_rewrite_line.")
  515. @must_be_open
  516. def restore(self, geo_obj):
  517. if hasattr(geo_obj, 'offset'):
  518. if libvect.Vect_restore_line(self.c_mapinfo, geo_obj.offset,
  519. geo_obj.id) == -1:
  520. raise GrassError("C function: Vect_restore_line.")
  521. else:
  522. raise ValueError("The value have not an offset attribute.")
  523. @must_be_open
  524. def bbox(self):
  525. """Return the BBox of the vecor map
  526. """
  527. bbox = Bbox()
  528. if libvect.Vect_get_map_box(self.c_mapinfo, bbox.c_bbox) == 0:
  529. raise GrassError("I can not find the Bbox.")
  530. return bbox
  531. def close(self, build=True, release=True):
  532. """Close the VectorTopo map, if release is True, the memory
  533. occupied by spatial index is released"""
  534. if release:
  535. libvect.Vect_set_release_support(self.c_mapinfo)
  536. super(VectorTopo, self).close(build=build)
  537. @must_be_open
  538. def table_to_dict(self, where=None):
  539. """Return the attribute table as a dictionary with the category as keys
  540. The columns have the order of the self.table.columns.names() list.
  541. Examples
  542. >>> from grass.pygrass.vector import VectorTopo
  543. >>> from grass.pygrass.vector.basic import Bbox
  544. >>> test_vect = VectorTopo(test_vector_name)
  545. >>> test_vect.open('r')
  546. >>> test_vect.table_to_dict()
  547. {1: [1, u'point', 1.0], 2: [2, u'line', 2.0], 3: [3, u'centroid', 3.0]}
  548. >>> test_vect.table_to_dict(where="value > 2")
  549. {3: [3, u'centroid', 3.0]}
  550. >>> test_vect.table_to_dict(where="value > 0")
  551. {1: [1, u'point', 1.0], 2: [2, u'line', 2.0], 3: [3, u'centroid', 3.0]}
  552. >>> test_vect.table.filters.get_sql()
  553. u'SELECT cat,name,value FROM vector_doctest_map WHERE value > 0 ORDER BY cat;'
  554. """
  555. if self.table is not None:
  556. table_dict = {}
  557. # Get the category index
  558. cat_index = self.table.columns.names().index("cat")
  559. # Prepare a filter
  560. if where is not None:
  561. self.table.filters.where(where)
  562. self.table.filters.order_by("cat")
  563. self.table.filters.select(",".join(self.table.columns.names()))
  564. # Execute the query and fetch the result
  565. cur = self.table.execute()
  566. l = cur.fetchall()
  567. # Generate the dictionary
  568. for entry in l:
  569. table_dict[entry[cat_index]] = list(entry)
  570. return(table_dict)
  571. return None
  572. @must_be_open
  573. def features_to_wkb_list(self, bbox=None, feature_type="point", field=1):
  574. """Return all features of type point, line, boundary or centroid
  575. as a list of Well Known Binary representations (WKB)
  576. (id, cat, wkb) triplets located in a specific
  577. bounding box.
  578. :param bbox: The boundingbox to search for features,
  579. if bbox=None the boundingbox of the whole
  580. vector map layer is used
  581. :type bbox: grass.pygrass.vector.basic.Bbox
  582. :param feature_type: The type of feature that should be converted to
  583. the Well Known Binary (WKB) format. Supported are:
  584. 'point' -> libvect.GV_POINT 1
  585. 'line' -> libvect.GV_LINE 2
  586. 'boundary' -> libvect.GV_BOUNDARY 3
  587. 'centroid' -> libvect.GV_CENTROID 4
  588. :type type: string
  589. :param field: The category field
  590. :type field: integer
  591. :return: A list of triplets, or None if nothing was found
  592. The well known binary are stored in byte arrays.
  593. Examples:
  594. >>> from grass.pygrass.vector import VectorTopo
  595. >>> from grass.pygrass.vector.basic import Bbox
  596. >>> test_vect = VectorTopo(test_vector_name)
  597. >>> test_vect.open('r')
  598. >>> bbox = Bbox(north=20, south=-1, east=20, west=-1)
  599. >>> result = test_vect.features_to_wkb_list(bbox=bbox,
  600. ... feature_type="point")
  601. >>> len(result)
  602. 3
  603. >>> for entry in result:
  604. ... f_id, cat, wkb = entry
  605. ... print((f_id, cat, len(wkb)))
  606. (1, 1, 21)
  607. (2, 1, 21)
  608. (3, 1, 21)
  609. >>> result = test_vect.features_to_wkb_list(bbox=None,
  610. ... feature_type="line")
  611. >>> len(result)
  612. 3
  613. >>> for entry in result:
  614. ... f_id, cat, wkb = entry
  615. ... print((f_id, cat, len(wkb)))
  616. (4, 2, 57)
  617. (5, 2, 57)
  618. (6, 2, 57)
  619. >>> result = test_vect.features_to_wkb_list(bbox=bbox,
  620. ... feature_type="boundary")
  621. >>> len(result)
  622. 11
  623. >>> result = test_vect.features_to_wkb_list(bbox=None,
  624. ... feature_type="centroid")
  625. >>> len(result)
  626. 4
  627. >>> for entry in result:
  628. ... f_id, cat, wkb = entry
  629. ... print((f_id, cat, len(wkb)))
  630. (19, 3, 21)
  631. (18, 3, 21)
  632. (20, 3, 21)
  633. (21, 3, 21)
  634. >>> result = test_vect.features_to_wkb_list(bbox=bbox,
  635. ... feature_type="blub")
  636. Traceback (most recent call last):
  637. ...
  638. GrassError: Unsupported feature type <blub>, supported are <point,line,boundary,centroid>
  639. >>> test_vect.close()
  640. """
  641. supported = ['point', 'line', 'boundary', 'centroid']
  642. if feature_type.lower() not in supported:
  643. raise GrassError("Unsupported feature type <%s>, "\
  644. "supported are <%s>"%(feature_type,
  645. ",".join(supported)))
  646. if bbox is None:
  647. bbox = self.bbox()
  648. bboxlist = self.find_by_bbox.geos(bbox, type=feature_type.lower(),
  649. bboxlist_only = True)
  650. if bboxlist is not None and len(bboxlist) > 0:
  651. l = []
  652. line_p = libvect.line_pnts()
  653. line_c = libvect.line_cats()
  654. size = ctypes.c_size_t()
  655. cat = ctypes.c_int()
  656. error = ctypes.c_int()
  657. for f_id in bboxlist.ids:
  658. barray = libvect.Vect_read_line_to_wkb(self.c_mapinfo,
  659. ctypes.byref(line_p),
  660. ctypes.byref(line_c),
  661. f_id,
  662. ctypes.byref(size),
  663. ctypes.byref(error))
  664. if not barray:
  665. if error == -1:
  666. raise GrassError(_("Unable to read line of feature %i"%(f_id)))
  667. if error == -2:
  668. print("Empty feature %i"%(f_id))
  669. continue
  670. ok = libvect.Vect_cat_get(ctypes.byref(line_c), field,
  671. ctypes.byref(cat))
  672. if ok < 1:
  673. pcat = None
  674. else:
  675. pcat = cat.value
  676. l.append((f_id, pcat, ctypes.string_at(barray, size.value)))
  677. libgis.G_free(barray)
  678. return l
  679. return None
  680. @must_be_open
  681. def areas_to_wkb_list(self, bbox=None, field=1):
  682. """Return all features of type point, line, boundary or centroid
  683. as a list of Well Known Binary representations (WKB)
  684. (id, cat, wkb) triplets located in a specific
  685. bounding box.
  686. :param bbox: The boundingbox to search for features,
  687. if bbox=None the boundingbox of the whole
  688. vector map layer is used
  689. :type bbox: grass.pygrass.vector.basic.Bbox
  690. :param field: The centroid category field
  691. :type field: integer
  692. :return: A list of triplets, or None if nothing was found
  693. The well known binary are stored in byte arrays.
  694. Examples:
  695. >>> from grass.pygrass.vector import VectorTopo
  696. >>> from grass.pygrass.vector.basic import Bbox
  697. >>> test_vect = VectorTopo(test_vector_name)
  698. >>> test_vect.open('r')
  699. >>> bbox = Bbox(north=20, south=-1, east=20, west=-1)
  700. >>> result = test_vect.areas_to_wkb_list(bbox=bbox)
  701. >>> len(result)
  702. 4
  703. >>> for entry in result:
  704. ... a_id, cat, wkb = entry
  705. ... print((a_id, cat, len(wkb)))
  706. (1, 3, 225)
  707. (2, 3, 141)
  708. (3, 3, 93)
  709. (4, 3, 141)
  710. >>> result = test_vect.areas_to_wkb_list()
  711. >>> len(result)
  712. 4
  713. >>> for entry in result:
  714. ... a_id, cat, wkb = entry
  715. ... print((a_id, cat, len(wkb)))
  716. (1, 3, 225)
  717. (2, 3, 141)
  718. (3, 3, 93)
  719. (4, 3, 141)
  720. >>> test_vect.close()
  721. """
  722. if bbox is None:
  723. bbox = self.bbox()
  724. bboxlist = self.find_by_bbox.areas(bbox, bboxlist_only = True)
  725. if bboxlist is not None and len(bboxlist) > 0:
  726. l = []
  727. line_c = libvect.line_cats()
  728. size = ctypes.c_size_t()
  729. cat = ctypes.c_int()
  730. for a_id in bboxlist.ids:
  731. barray = libvect.Vect_read_area_to_wkb(self.c_mapinfo,
  732. a_id,
  733. ctypes.byref(size))
  734. if not barray:
  735. raise GrassError(_("Unable to read area with id %i"%(a_id)))
  736. pcat = None
  737. c_ok = libvect.Vect_get_area_cats(self.c_mapinfo, a_id,
  738. ctypes.byref(line_c))
  739. if c_ok == 0: # Centroid found
  740. ok = libvect.Vect_cat_get(ctypes.byref(line_c), field,
  741. ctypes.byref(cat))
  742. if ok > 0:
  743. pcat = cat.value
  744. l.append((a_id, pcat, ctypes.string_at(barray, size.value)))
  745. libgis.G_free(barray)
  746. return l
  747. return None
  748. if __name__ == "__main__":
  749. import doctest
  750. from grass.pygrass import utils
  751. utils.create_test_vector_map(test_vector_name)
  752. doctest.testmod()
  753. """Remove the generated vector map, if exist"""
  754. from grass.pygrass.utils import get_mapset_vector
  755. from grass.script.core import run_command
  756. mset = get_mapset_vector(test_vector_name, mapset='')
  757. if mset:
  758. run_command("g.remove", flags='f', type='vector', name=test_vector_name)