__init__.py 31 KB

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