__init__.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. # -*- coding: utf-8 -*-
  2. from os.path import join, exists
  3. import grass.lib.gis as libgis
  4. libgis.G_gisinit('')
  5. import grass.lib.vector as libvect
  6. #
  7. # import pygrass modules
  8. #
  9. from grass.pygrass.vector.vector_type import VTYPE
  10. from grass.pygrass.errors import GrassError, must_be_open
  11. from grass.pygrass.gis import Location
  12. from grass.pygrass.vector.geometry import GEOOBJ as _GEOOBJ
  13. from grass.pygrass.vector.geometry import read_line, read_next_line
  14. from grass.pygrass.vector.geometry import Area as _Area
  15. from grass.pygrass.vector.abstract import Info
  16. from grass.pygrass.vector.basic import Bbox, Cats, Ilist
  17. _NUMOF = {"areas": libvect.Vect_get_num_areas,
  18. "dblinks": libvect.Vect_get_num_dblinks,
  19. "faces": libvect.Vect_get_num_faces,
  20. "holes": libvect.Vect_get_num_holes,
  21. "islands": libvect.Vect_get_num_islands,
  22. "kernels": libvect.Vect_get_num_kernels,
  23. "lines": libvect.Vect_get_num_lines,
  24. "nodes": libvect.Vect_get_num_nodes,
  25. "updated_lines": libvect.Vect_get_num_updated_lines,
  26. "updated_nodes": libvect.Vect_get_num_updated_nodes,
  27. "volumes": libvect.Vect_get_num_volumes}
  28. #=============================================
  29. # VECTOR
  30. #=============================================
  31. class Vector(Info):
  32. """Vector class is the grass vector format without topology
  33. >>> from grass.pygrass.vector import Vector
  34. >>> cens = Vector('census')
  35. >>> cens.is_open()
  36. False
  37. >>> cens.mapset
  38. ''
  39. >>> cens.exist()
  40. True
  41. >>> cens.mapset
  42. 'PERMANENT'
  43. >>> cens.overwrite
  44. False
  45. """
  46. def __init__(self, name, mapset='', *args, **kwargs):
  47. # Set map name and mapset
  48. super(Vector, self).__init__(name, mapset, *args, **kwargs)
  49. self._topo_level = 1
  50. self._class_name = 'Vector'
  51. self.overwrite = False
  52. def __repr__(self):
  53. if self.exist():
  54. return "%s(%r, %r)" % (self._class_name, self.name, self.mapset)
  55. else:
  56. return "%s(%r)" % (self._class_name, self.name)
  57. def __iter__(self):
  58. """::
  59. >>> cens = Vector('census')
  60. >>> cens.open(mode='r')
  61. >>> features = [feature for feature in cens]
  62. >>> features[:3]
  63. [Boundary(v_id=None), Boundary(v_id=None), Boundary(v_id=None)]
  64. >>> cens.close()
  65. ..
  66. """
  67. #return (self.read(f_id) for f_id in xrange(self.num_of_features()))
  68. return self
  69. @must_be_open
  70. def next(self):
  71. """::
  72. >>> cens = Vector('census')
  73. >>> cens.open(mode='r')
  74. >>> cens.next()
  75. Boundary(v_id=None)
  76. >>> cens.next()
  77. Boundary(v_id=None)
  78. >>> cens.close()
  79. ..
  80. """
  81. return read_next_line(self.c_mapinfo, self.table, self.writable,
  82. is2D=not self.is_3D())
  83. @must_be_open
  84. def rewind(self):
  85. """Rewind vector map to cause reads to start at beginning."""
  86. if libvect.Vect_rewind(self.c_mapinfo) == -1:
  87. raise GrassError("Vect_rewind raise an error.")
  88. @must_be_open
  89. def write(self, geo_obj, attrs=None, set_cats=True):
  90. """Write geometry features and attributes.
  91. :param geo_obj: a geometry grass object define in
  92. grass.pygrass.vector.geometry
  93. :type geo_obj: geometry GRASS object
  94. :param attrs: a list with the values that will be insert in the
  95. attribute table.
  96. :type attrs: list
  97. :param set_cats: if True, the category of the geometry feature is set
  98. using the default layer of the vector map and a
  99. progressive category value (default), otherwise the
  100. c_cats attribute of the geometry object will be used.
  101. :type set_cats: bool
  102. Open a new vector map ::
  103. >>> new = VectorTopo('newvect')
  104. >>> new.exist()
  105. False
  106. define the new columns of the attribute table ::
  107. >>> cols = [(u'cat', 'INTEGER PRIMARY KEY'),
  108. ... (u'name', 'TEXT')]
  109. open the vector map in write mode
  110. >>> new.open('w', tab_name='newvect', tab_cols=cols)
  111. import a geometry feature ::
  112. >>> from grass.pygrass.vector.geometry import Point
  113. create two points ::
  114. >>> point0 = Point(636981.336043, 256517.602235)
  115. >>> point1 = Point(637209.083058, 257970.129540)
  116. then write the two points on the map, with ::
  117. >>> new.write(point0, ('pub', ))
  118. >>> new.write(point1, ('resturnat', ))
  119. commit the db changes ::
  120. >>> new.table.conn.commit()
  121. >>> new.table.execute().fetchall()
  122. [(1, u'pub'), (2, u'resturnat')]
  123. close the vector map ::
  124. >>> new.close()
  125. >>> new.exist()
  126. True
  127. then play with the map ::
  128. >>> new.open(mode='r')
  129. >>> new.read(1)
  130. Point(636981.336043, 256517.602235)
  131. >>> new.read(2)
  132. Point(637209.083058, 257970.129540)
  133. >>> new.read(1).attrs['name']
  134. u'pub'
  135. >>> new.read(2).attrs['name']
  136. u'resturnat'
  137. >>> new.close()
  138. >>> new.remove()
  139. """
  140. self.n_lines += 1
  141. if self.table is not None and attrs:
  142. attr = [self.n_lines, ]
  143. attr.extend(attrs)
  144. cur = self.table.conn.cursor()
  145. cur.execute(self.table.columns.insert_str, attr)
  146. cur.close()
  147. if set_cats:
  148. cats = Cats(geo_obj.c_cats)
  149. cats.reset()
  150. cats.set(self.n_lines, self.layer)
  151. if geo_obj.gtype == _Area.gtype:
  152. result = self._write_area(geo_obj)
  153. result = libvect.Vect_write_line(self.c_mapinfo, geo_obj.gtype,
  154. geo_obj.c_points, geo_obj.c_cats)
  155. if result == -1:
  156. raise GrassError("Not able to write the vector feature.")
  157. if self._topo_level == 2:
  158. # return new feature id (on level 2)
  159. geo_obj.id = result
  160. else:
  161. # return offset into file where the feature starts (on level 1)
  162. geo_obj.offset = result
  163. @must_be_open
  164. def has_color_table(self):
  165. """Return if vector has color table associated in file system;
  166. Color table stored in the vector's attribute table well be not checked
  167. >>> cens = Vector('census')
  168. >>> cens.open(mode='r')
  169. >>> cens.has_color_table()
  170. False
  171. >>> cens.close()
  172. >>> from grass.pygrass.functions import copy, remove
  173. >>> copy('census','mycensus','vect')
  174. >>> from grass.pygrass.modules.shortcuts import vector as v
  175. >>> v.colors(map='mycensus', color='population', column='TOTAL_POP')
  176. Module('v.colors')
  177. >>> mycens = Vector('mycensus')
  178. >>> mycens.open(mode='r')
  179. >>> mycens.has_color_table()
  180. True
  181. >>> mycens.close()
  182. >>> remove('mycensus', 'vect')
  183. """
  184. loc = Location()
  185. path = join(loc.path(), self.mapset, 'vector', self.name, 'colr')
  186. return True if exists(path) else False
  187. #=============================================
  188. # VECTOR WITH TOPOLOGY
  189. #=============================================
  190. class VectorTopo(Vector):
  191. """Vector class with the support of the GRASS topology.
  192. Open a vector map using the *with statement*: ::
  193. >>> with VectorTopo('schools', mode='r') as schools:
  194. ... for school in schools[:3]:
  195. ... print school.attrs['NAMESHORT']
  196. ...
  197. SWIFT CREEK
  198. BRIARCLIFF
  199. FARMINGTON WOODS
  200. >>> schools.is_open()
  201. False
  202. ..
  203. """
  204. def __init__(self, name, mapset='', *args, **kwargs):
  205. super(VectorTopo, self).__init__(name, mapset, *args, **kwargs)
  206. self._topo_level = 2
  207. self._class_name = 'VectorTopo'
  208. def __len__(self):
  209. return libvect.Vect_get_num_lines(self.c_mapinfo)
  210. def __getitem__(self, key):
  211. """::
  212. >>> cens = VectorTopo('census')
  213. >>> cens.open(mode='r')
  214. >>> cens[:3]
  215. [Boundary(v_id=1), Boundary(v_id=2), Boundary(v_id=3)]
  216. >>> cens.close()
  217. ..
  218. """
  219. if isinstance(key, slice):
  220. return [self.read(indx)
  221. for indx in range(key.start if key.start else 1,
  222. key.stop if key.stop else len(self),
  223. key.step if key.step else 1)]
  224. elif isinstance(key, int):
  225. return self.read(key)
  226. else:
  227. raise ValueError("Invalid argument type: %r." % key)
  228. @must_be_open
  229. def num_primitive_of(self, primitive):
  230. """Return the number of primitive
  231. :param primitive: the name of primitive to query; the supported values are:
  232. * *boundary*,
  233. * *centroid*,
  234. * *face*,
  235. * *kernel*,
  236. * *line*,
  237. * *point*
  238. * *area*
  239. * *volume*
  240. :type primitive: str
  241. ::
  242. >>> cens = VectorTopo('census')
  243. >>> cens.open(mode='r')
  244. >>> cens.num_primitive_of('point')
  245. 0
  246. >>> cens.num_primitive_of('line')
  247. 0
  248. >>> cens.num_primitive_of('centroid')
  249. 2537
  250. >>> cens.num_primitive_of('boundary')
  251. 6383
  252. >>> cens.close()
  253. ..
  254. """
  255. return libvect.Vect_get_num_primitives(self.c_mapinfo,
  256. VTYPE[primitive])
  257. @must_be_open
  258. def number_of(self, vtype):
  259. """Return the number of the choosen element type
  260. :param vtype: the name of type to query; the supported values are:
  261. *areas*, *dblinks*, *faces*, *holes*, *islands*,
  262. *kernels*, *line_points*, *lines*, *nodes*,
  263. *update_lines*, *update_nodes*, *volumes*
  264. :type vtype: str
  265. >>> cens = VectorTopo('census')
  266. >>> cens.open(mode='r')
  267. >>> cens.number_of("areas")
  268. 2547
  269. >>> cens.number_of("islands")
  270. 49
  271. >>> cens.number_of("holes")
  272. 0
  273. >>> cens.number_of("lines")
  274. 8920
  275. >>> cens.number_of("nodes")
  276. 3885
  277. >>> cens.number_of("pizza")
  278. ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
  279. Traceback (most recent call last):
  280. ...
  281. ValueError: vtype not supported, use one of: 'areas', ...
  282. >>> cens.close()
  283. ..
  284. """
  285. if vtype in _NUMOF.keys():
  286. return _NUMOF[vtype](self.c_mapinfo)
  287. else:
  288. keys = "', '".join(sorted(_NUMOF.keys()))
  289. raise ValueError("vtype not supported, use one of: '%s'" % keys)
  290. @must_be_open
  291. def num_primitives(self):
  292. """Return dictionary with the number of all primitives
  293. """
  294. output = {}
  295. for prim in VTYPE.keys():
  296. output[prim] = self.num_primitive_of(prim)
  297. return output
  298. @must_be_open
  299. def viter(self, vtype, idonly=False):
  300. """Return an iterator of vector features
  301. :param vtype: the name of type to query; the supported values are:
  302. *areas*, *dblinks*, *faces*, *holes*, *islands*,
  303. *kernels*, *line_points*, *lines*, *nodes*,
  304. *update_lines*, *update_nodes*, *volumes*
  305. :type vtype: str
  306. :param idonly: variable to return only the id of features instead of
  307. full features
  308. :type idonly: bool
  309. >>> cens = VectorTopo('census', mode='r')
  310. >>> cens.open(mode='r')
  311. >>> big = [area for area in cens.viter('areas')
  312. ... if area.alive() and area.area() >= 10000]
  313. >>> big[:3]
  314. [Area(5), Area(6), Area(13)]
  315. to sort the result in a efficient way, use: ::
  316. >>> from operator import methodcaller as method
  317. >>> big.sort(key=method('area'), reverse=True) # sort the list
  318. >>> for area in big[:3]:
  319. ... print area, area.area()
  320. Area(2099) 5392751.5304
  321. Area(2171) 4799921.30863
  322. Area(495) 4055812.49695
  323. >>> cens.close()
  324. """
  325. if vtype in _GEOOBJ.keys():
  326. if _GEOOBJ[vtype] is not None:
  327. ids = (indx for indx in range(1, self.number_of(vtype) + 1))
  328. if idonly:
  329. return ids
  330. return (_GEOOBJ[vtype](v_id=indx, c_mapinfo=self.c_mapinfo,
  331. table=self.table,
  332. writable=self.writable)
  333. for indx in ids)
  334. else:
  335. keys = "', '".join(sorted(_GEOOBJ.keys()))
  336. raise ValueError("vtype not supported, use one of: '%s'" % keys)
  337. @must_be_open
  338. def rewind(self):
  339. """Rewind vector map to cause reads to start at beginning. ::
  340. >>> cens = VectorTopo('census')
  341. >>> cens.open(mode='r')
  342. >>> cens.next()
  343. Boundary(v_id=1)
  344. >>> cens.next()
  345. Boundary(v_id=2)
  346. >>> cens.next()
  347. Boundary(v_id=3)
  348. >>> cens.rewind()
  349. >>> cens.next()
  350. Boundary(v_id=1)
  351. >>> cens.close()
  352. ..
  353. """
  354. libvect.Vect_rewind(self.c_mapinfo)
  355. @must_be_open
  356. def cat(self, cat_id, vtype, layer=None, generator=False, geo=None):
  357. """Return the geometry features with category == cat_id.
  358. :param cat_id: the category number
  359. :type cat_id: int
  360. :param vtype: the type of geometry feature that we are looking for
  361. :type vtype: str
  362. :param layer: the layer number that will be used
  363. :type layer: int
  364. :param generator: if True return a generator otherwise it return a
  365. list of features
  366. :type generator: bool
  367. """
  368. if geo is None and vtype not in _GEOOBJ:
  369. keys = "', '".join(sorted(_GEOOBJ.keys()))
  370. raise ValueError("vtype not supported, use one of: '%s'" % keys)
  371. Obj = _GEOOBJ[vtype] if geo is None else geo
  372. ilist = Ilist()
  373. libvect.Vect_cidx_find_all(self.c_mapinfo,
  374. layer if layer else self.layer,
  375. Obj.gtype, cat_id, ilist.c_ilist)
  376. is2D = not self.is_3D()
  377. if generator:
  378. return (read_line(feature_id=v_id, c_mapinfo=self.c_mapinfo,
  379. table=self.table, writable=self.writable,
  380. is2D=is2D)
  381. for v_id in ilist)
  382. else:
  383. return [read_line(feature_id=v_id, c_mapinfo=self.c_mapinfo,
  384. table=self.table, writable=self.writable,
  385. is2D=is2D)
  386. for v_id in ilist]
  387. @must_be_open
  388. def read(self, feature_id):
  389. """Return a geometry object given the feature id.
  390. :param int feature_id: the id of feature to obtain
  391. >>> cens = VectorTopo('census')
  392. >>> cens.open(mode='r')
  393. >>> feature1 = cens.read(0) #doctest: +ELLIPSIS
  394. Traceback (most recent call last):
  395. ...
  396. ValueError: The index must be >0, 0 given.
  397. >>> feature1 = cens.read(1)
  398. >>> feature1
  399. Boundary(v_id=1)
  400. >>> feature1.length()
  401. 444.54490917696944
  402. >>> cens.read(-1)
  403. Centoid(642963.159711, 214994.016279)
  404. >>> len(cens)
  405. 8920
  406. >>> cens.read(8920)
  407. Centoid(642963.159711, 214994.016279)
  408. >>> cens.read(8921) #doctest: +ELLIPSIS
  409. Traceback (most recent call last):
  410. ...
  411. IndexError: Index out of range
  412. >>> cens.close()
  413. """
  414. return read_line(feature_id, self.c_mapinfo, self.table, self.writable,
  415. is2D=not self.is_3D())
  416. @must_be_open
  417. def is_empty(self):
  418. """Return if a vector map is empty or not
  419. """
  420. primitives = self.num_primitives()
  421. output = True
  422. for v in primitives.values():
  423. if v != 0:
  424. output = False
  425. break
  426. return output
  427. @must_be_open
  428. def rewrite(self, line, geo_obj, attrs=None, **kargs):
  429. """Rewrite a geometry features
  430. """
  431. if self.table is not None and attrs:
  432. attr = [line, ]
  433. attr.extend(attrs)
  434. self.table.update(key=line, values=attr)
  435. elif self.table is None and attrs:
  436. print "Table for vector {name} does not exist, attributes not" \
  437. " loaded".format(name=self.name)
  438. libvect.Vect_cat_set(geo_obj.c_cats, self.layer, line)
  439. result = libvect.Vect_rewrite_line(self.c_mapinfo,
  440. line, geo_obj.gtype,
  441. geo_obj.c_points,
  442. geo_obj.c_cats)
  443. if result == -1:
  444. raise GrassError("Not able to write the vector feature.")
  445. # return offset into file where the feature starts
  446. geo_obj.offset = result
  447. @must_be_open
  448. def delete(self, feature_id):
  449. """Remove a feature by its id
  450. :param feature_id: the id of the feature
  451. :type feature_id: int
  452. """
  453. if libvect.Vect_rewrite_line(self.c_mapinfo, feature_id) == -1:
  454. raise GrassError("C funtion: Vect_rewrite_line.")
  455. @must_be_open
  456. def restore(self, geo_obj):
  457. if hasattr(geo_obj, 'offset'):
  458. if libvect.Vect_restore_line(self.c_mapinfo, geo_obj.id,
  459. geo_obj.offset) == -1:
  460. raise GrassError("C funtion: Vect_restore_line.")
  461. else:
  462. raise ValueError("The value have not an offset attribute.")
  463. @must_be_open
  464. def bbox(self):
  465. """Return the BBox of the vecor map
  466. """
  467. bbox = Bbox()
  468. if libvect.Vect_get_map_box(self.c_mapinfo, bbox.c_bbox) == 0:
  469. raise GrassError("I can not find the Bbox.")
  470. return bbox
  471. @must_be_open
  472. def select_by_bbox(self, bbox):
  473. """Return the BBox of the vector map
  474. """
  475. # TODO replace with bbox if bbox else Bbox() ??
  476. bbox = Bbox()
  477. if libvect.Vect_get_map_box(self.c_mapinfo, bbox.c_bbox) == 0:
  478. raise GrassError("I can not find the Bbox.")
  479. return bbox
  480. def close(self, build=True, release=True):
  481. """Close the VectorTopo map, if release is True, the memory
  482. occupied by spatial index is released"""
  483. if release:
  484. libvect.Vect_set_release_support(self.c_mapinfo)
  485. super(VectorTopo, self).close(build=build)