__init__.py 32 KB

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