__init__.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Tue Jul 17 08:51:53 2012
  4. @author: pietro
  5. """
  6. import grass.lib.vector as libvect
  7. from grass.pygrass.vector.vector_type import VTYPE
  8. from os.path import join, exists
  9. #
  10. # import pygrass modules
  11. #
  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. "lines": libvect.Vect_get_num_line_points,
  26. "points": 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. #=============================================
  32. # VECTOR
  33. #=============================================
  34. class Vector(Info):
  35. """Vector class is the grass vector format without topology
  36. >>> from grass.pygrass.vector import Vector
  37. >>> cens = Vector('census')
  38. >>> cens.is_open()
  39. False
  40. >>> cens.mapset
  41. ''
  42. >>> cens.exist()
  43. True
  44. >>> cens.mapset
  45. 'PERMANENT'
  46. >>> cens.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. def __repr__(self):
  56. if self.exist():
  57. return "%s(%r, %r)" % (self._class_name, self.name, self.mapset)
  58. else:
  59. return "%s(%r)" % (self._class_name, self.name)
  60. def __iter__(self):
  61. """::
  62. >>> mun = Vector('census')
  63. >>> mun.open()
  64. >>> features = [feature for feature in mun]
  65. >>> features[:3]
  66. [Boundary(v_id=None), Boundary(v_id=None), Boundary(v_id=None)]
  67. >>> mun.close()
  68. ..
  69. """
  70. #return (self.read(f_id) for f_id in xrange(self.num_of_features()))
  71. return self
  72. @must_be_open
  73. def next(self):
  74. """::
  75. >>> mun = Vector('census')
  76. >>> mun.open()
  77. >>> mun.next()
  78. Boundary(v_id=None)
  79. >>> mun.next()
  80. Boundary(v_id=None)
  81. >>> mun.close()
  82. ..
  83. """
  84. return read_next_line(self.c_mapinfo, self.table, self.writable)
  85. @must_be_open
  86. def rewind(self):
  87. """Rewind vector map to cause reads to start at beginning."""
  88. if libvect.Vect_rewind(self.c_mapinfo) == -1:
  89. raise GrassError("Vect_rewind raise an error.")
  90. @must_be_open
  91. def write(self, geo_obj, attrs=None, set_cats=True):
  92. """Write geometry features and attributes.
  93. :param geo_obj: a geometry grass object define in
  94. grass.pygrass.vector.geometry
  95. :type geo_obj: geometry GRASS object
  96. :param attrs: a list with the values that will be insert in the
  97. attribute table.
  98. :type attrs: list
  99. :param set_cats: if True, the category of the geometry feature is set
  100. using the default layer of the vector map and a
  101. progressive category value (default), otherwise the
  102. c_cats attribute of the geometry object will be used.
  103. :type set_cats: bool
  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(636981.336043, 256517.602235)
  117. >>> point1 = Point(637209.083058, 257970.129540)
  118. then write the two points on the map, with ::
  119. >>> new.write(point0, ('pub', ))
  120. >>> new.write(point1, ('resturnat', ))
  121. close the vector map ::
  122. >>> new.close()
  123. >>> new.exist()
  124. True
  125. then play with the map ::
  126. >>> new.open()
  127. >>> new.read(1)
  128. Point(636981.336043, 256517.602235)
  129. >>> new.read(2)
  130. Point(637209.083058, 257970.129540)
  131. >>> new.read(1).attrs['name']
  132. u'pub'
  133. >>> new.read(2).attrs['cat', 'name']
  134. (2, u'resturnat')
  135. >>> new.close()
  136. >>> new.remove()
  137. """
  138. self.n_lines += 1
  139. if self.table is not None and attrs:
  140. attr = [self.n_lines, ]
  141. attr.extend(attrs)
  142. cur = self.table.conn.cursor()
  143. cur.execute(self.table.columns.insert_str, attr)
  144. cur.close()
  145. if set_cats:
  146. cats = Cats(geo_obj.c_cats)
  147. cats.reset()
  148. cats.set(self.n_lines, self.layer)
  149. if geo_obj.gtype == _Area.gtype:
  150. result = self._write_area(geo_obj)
  151. result = libvect.Vect_write_line(self.c_mapinfo, geo_obj.gtype,
  152. geo_obj.c_points, geo_obj.c_cats)
  153. if result == -1:
  154. raise GrassError("Not able to write the vector feature.")
  155. if self._topo_level == 2:
  156. # return new feature id (on level 2)
  157. geo_obj.id = result
  158. else:
  159. # return offset into file where the feature starts (on level 1)
  160. geo_obj.offset = result
  161. @must_be_open
  162. def has_color_table(self):
  163. """Return if vector has color table associated in file system;
  164. Color table stored in the vector's attribute table well be not checked
  165. >>> cens = Vector('census')
  166. >>> cens.open()
  167. >>> cens.has_color_table()
  168. False
  169. >>> cens.close()
  170. >>> from grass.pygrass.functions import copy, remove
  171. >>> copy('census','mycensus','vect')
  172. >>> from grass.pygrass.modules.shortcuts import vector as v
  173. >>> v.colors(map='mycensus', color='population', column='TOTAL_POP')
  174. >>> mycens = Vector('mycensus')
  175. >>> mycens.open()
  176. >>> mycens.has_color_table()
  177. True
  178. >>> mycens.close()
  179. >>> remove('mycensus', 'vect')
  180. """
  181. loc = Location()
  182. path = join(loc.path(), self.mapset, 'vector', self.name, 'colr')
  183. return True if exists(path) else False
  184. #=============================================
  185. # VECTOR WITH TOPOLOGY
  186. #=============================================
  187. class VectorTopo(Vector):
  188. """Vector class with the support of the GRASS topology.
  189. Open a vector map using the *with statement*: ::
  190. >>> with VectorTopo('schools') as schools:
  191. ... for school in schools[:3]:
  192. ... print school.attrs['NAMESHORT']
  193. ...
  194. SWIFT CREEK
  195. BRIARCLIFF
  196. FARMINGTON WOODS
  197. >>> schools.is_open()
  198. False
  199. ..
  200. """
  201. def __init__(self, name, mapset='', *args, **kwargs):
  202. super(VectorTopo, self).__init__(name, mapset, *args, **kwargs)
  203. self._topo_level = 2
  204. self._class_name = 'VectorTopo'
  205. def __len__(self):
  206. return libvect.Vect_get_num_lines(self.c_mapinfo)
  207. def __getitem__(self, key):
  208. """::
  209. >>> mun = VectorTopo('census')
  210. >>> mun.open()
  211. >>> mun[:3]
  212. [Boundary(v_id=1), Boundary(v_id=2), Boundary(v_id=3)]
  213. >>> mun.close()
  214. ..
  215. """
  216. if isinstance(key, slice):
  217. #import pdb; pdb.set_trace()
  218. #Get the start, stop, and step from the slice
  219. return [self.read(indx + 1)
  220. for indx in range(*key.indices(len(self)))]
  221. elif isinstance(key, int):
  222. return self.read(key)
  223. else:
  224. raise ValueError("Invalid argument type: %r." % key)
  225. @must_be_open
  226. def num_primitive_of(self, primitive):
  227. """Return the number of primitive
  228. :param primitive: the name of primitive to query; the supported values are:
  229. * *boundary*,
  230. * *centroid*,
  231. * *face*,
  232. * *kernel*,
  233. * *line*,
  234. * *point*
  235. * *area*
  236. * *volume*
  237. :type primitive: str
  238. ::
  239. >>> cens = VectorTopo('boundary_municp_sqlite')
  240. >>> cens.open()
  241. >>> cens.num_primitive_of('point')
  242. 0
  243. >>> cens.num_primitive_of('line')
  244. 0
  245. >>> cens.num_primitive_of('centroid')
  246. 3579
  247. >>> cens.num_primitive_of('boundary')
  248. 5128
  249. >>> cens.close()
  250. ..
  251. """
  252. return libvect.Vect_get_num_primitives(self.c_mapinfo,
  253. VTYPE[primitive])
  254. @must_be_open
  255. def number_of(self, vtype):
  256. """Return the number of the choosen element type
  257. :param vtype: the name of type to query; the supported values are:
  258. *areas*, *dblinks*, *faces*, *holes*, *islands*,
  259. *kernels*, *line_points*, *lines*, *nodes*,
  260. *update_lines*, *update_nodes*, *volumes*
  261. :type vtype: str
  262. >>> cens = VectorTopo('boundary_municp_sqlite')
  263. >>> cens.open()
  264. >>> cens.number_of("areas")
  265. 3579
  266. >>> cens.number_of("islands")
  267. 2629
  268. >>> cens.number_of("holes")
  269. 0
  270. >>> cens.number_of("lines")
  271. 8707
  272. >>> cens.number_of("nodes")
  273. 4178
  274. >>> cens.number_of("pizza")
  275. ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
  276. Traceback (most recent call last):
  277. ...
  278. ValueError: vtype not supported, use one of:
  279. 'areas', 'dblinks', 'faces', 'holes', 'islands', 'kernels',
  280. 'line_points', 'lines', 'nodes', 'updated_lines', 'updated_nodes',
  281. 'volumes'
  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')
  310. >>> cens.open()
  311. >>> big = [area for area in cens.viter('areas')
  312. ... if area.alive() and area.area >= 10000]
  313. >>> big[:3]
  314. [Area(1), Area(2), Area(3)]
  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(3102) 697521857.848
  321. Area(2682) 320224369.66
  322. Area(2552) 298356117.948
  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. >>> mun = VectorTopo('boundary_municp_sqlite')
  341. >>> mun.open()
  342. >>> mun.next()
  343. Boundary(v_id=1)
  344. >>> mun.next()
  345. Boundary(v_id=2)
  346. >>> mun.next()
  347. Boundary(v_id=3)
  348. >>> mun.rewind()
  349. >>> mun.next()
  350. Boundary(v_id=1)
  351. >>> mun.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. if generator:
  377. return (read_line(feature_id=v_id, c_mapinfo=self.c_mapinfo,
  378. table=self.table, writable=self.writable)
  379. for v_id in ilist)
  380. else:
  381. return [read_line(feature_id=v_id, c_mapinfo=self.c_mapinfo,
  382. table=self.table, writable=self.writable)
  383. for v_id in ilist]
  384. @must_be_open
  385. def read(self, feature_id):
  386. """Return a geometry object given the feature id.
  387. :param feature_id: the id of feature to obtain
  388. :type feature_id: int
  389. >>> mun = VectorTopo('boundary_municp_sqlite')
  390. >>> mun.open()
  391. >>> feature1 = mun.read(0) #doctest: +ELLIPSIS
  392. Traceback (most recent call last):
  393. ...
  394. ValueError: The index must be >0, 0 given.
  395. >>> feature1 = mun.read(1)
  396. >>> feature1
  397. Boundary(v_id=1)
  398. >>> feature1.length()
  399. 1415.3348048582038
  400. >>> mun.read(-1)
  401. Centoid(649102.382010, 15945.714502)
  402. >>> len(mun)
  403. 8707
  404. >>> mun.read(8707)
  405. Centoid(649102.382010, 15945.714502)
  406. >>> mun.read(8708) #doctest: +ELLIPSIS
  407. Traceback (most recent call last):
  408. ...
  409. IndexError: Index out of range
  410. >>> mun.close()
  411. """
  412. return read_line(feature_id, self.c_mapinfo, self.table, self.writable)
  413. @must_be_open
  414. def is_empty(self):
  415. """Return if a vector map is empty or not
  416. """
  417. primitives = self.num_primitives()
  418. output = True
  419. for v in primitives.values():
  420. if v != 0:
  421. output = False
  422. break
  423. return output
  424. @must_be_open
  425. def rewrite(self, line, geo_obj, attrs=None, **kargs):
  426. """Rewrite a geometry features
  427. """
  428. if self.table is not None and attrs:
  429. attr = [line, ]
  430. attr.extend(attrs)
  431. self.table.update(key=line, values=attr)
  432. elif self.table is None and attrs:
  433. print "Table for vector {name} does not exist, attributes not" \
  434. " loaded".format(name=self.name)
  435. libvect.Vect_cat_set(geo_obj.c_cats, self.layer, line)
  436. result = libvect.Vect_rewrite_line(self.c_mapinfo,
  437. line, geo_obj.gtype,
  438. geo_obj.c_points,
  439. geo_obj.c_cats)
  440. if result == -1:
  441. raise GrassError("Not able to write the vector feature.")
  442. # return offset into file where the feature starts
  443. geo_obj.offset = result
  444. @must_be_open
  445. def delete(self, feature_id):
  446. """Remove a feature by its id
  447. :param feature_id: the id of the feature
  448. :type feature_id: int
  449. """
  450. if libvect.Vect_rewrite_line(self.c_mapinfo, feature_id) == -1:
  451. raise GrassError("C funtion: Vect_rewrite_line.")
  452. @must_be_open
  453. def restore(self, geo_obj):
  454. if hasattr(geo_obj, 'offset'):
  455. if libvect.Vect_restore_line(self.c_mapinfo, geo_obj.id,
  456. geo_obj.offset) == -1:
  457. raise GrassError("C funtion: Vect_restore_line.")
  458. else:
  459. raise ValueError("The value have not an offset attribute.")
  460. @must_be_open
  461. def bbox(self):
  462. """Return the BBox of the vecor map
  463. """
  464. bbox = Bbox()
  465. if libvect.Vect_get_map_box(self.c_mapinfo, bbox.c_bbox) == 0:
  466. raise GrassError("I can not find the Bbox.")
  467. return bbox
  468. @must_be_open
  469. def select_by_bbox(self, bbox):
  470. """Return the BBox of the vector map
  471. """
  472. # TODO replace with bbox if bbox else Bbox() ??
  473. bbox = Bbox()
  474. if libvect.Vect_get_map_box(self.c_mapinfo, bbox.c_bbox) == 0:
  475. raise GrassError("I can not find the Bbox.")
  476. return bbox
  477. def close(self, build=True, release=True):
  478. """Close the VectorTopo map, if release is True, the memory
  479. occupied by spatial index is released"""
  480. if release:
  481. libvect.Vect_set_release_support(self.c_mapinfo)
  482. super(VectorTopo, self).close(build=build)