geometry.py 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Wed Jul 18 10:46:25 2012
  4. @author: pietro
  5. """
  6. import ctypes
  7. import re
  8. from collections import namedtuple
  9. import numpy as np
  10. import grass.lib.gis as libgis
  11. import grass.lib.vector as libvect
  12. from grass.pygrass.errors import GrassError
  13. from grass.pygrass.vector.basic import Ilist, Bbox, Cats
  14. from grass.pygrass.vector import sql
  15. LineDist = namedtuple('LineDist', 'point dist spdist sldist')
  16. WKT = {'POINT\((.*)\)': 'point', # 'POINT\(\s*([+-]*\d+\.*\d*)+\s*\)'
  17. 'LINESTRING\((.*)\)': 'line'}
  18. def read_WKT(string):
  19. """Read the string and return a geometry object
  20. **WKT**:
  21. ::
  22. POINT(0 0)
  23. LINESTRING(0 0,1 1,1 2)
  24. POLYGON((0 0,4 0,4 4,0 4,0 0),(1 1, 2 1, 2 2, 1 2,1 1))
  25. MULTIPOINT(0 0,1 2)
  26. MULTILINESTRING((0 0,1 1,1 2),(2 3,3 2,5 4))
  27. MULTIPOLYGON(((0 0,4 0,4 4,0 4,0 0),(1 1,2 1,2 2,1 2,1 1)),
  28. ((-1 -1,-1 -2,-2 -2,-2 -1,-1 -1)))
  29. GEOMETRYCOLLECTION(POINT(2 3),LINESTRING(2 3,3 4))
  30. **EWKT**:
  31. ::
  32. POINT(0 0 0) -- XYZ
  33. SRID=32632;POINT(0 0) -- XY with SRID
  34. POINTM(0 0 0) -- XYM
  35. POINT(0 0 0 0) -- XYZM
  36. SRID=4326;MULTIPOINTM(0 0 0,1 2 1) -- XYM with SRID
  37. MULTILINESTRING((0 0 0,1 1 0,1 2 1),(2 3 1,3 2 1,5 4 1))
  38. POLYGON((0 0 0,4 0 0,4 4 0,0 4 0,0 0 0),(1 1 0,2 1 0,2 2 0,1 2 0,1 1 0))
  39. MULTIPOLYGON(((0 0 0,4 0 0,4 4 0,0 4 0,0 0 0),
  40. (1 1 0,2 1 0,2 2 0,1 2 0,1 1 0)),
  41. ((-1 -1 0,-1 -2 0,-2 -2 0,-2 -1 0,-1 -1 0)))
  42. GEOMETRYCOLLECTIONM( POINTM(2 3 9), LINESTRINGM(2 3 4, 3 4 5) )
  43. MULTICURVE( (0 0, 5 5), CIRCULARSTRING(4 0, 4 4, 8 4) )
  44. POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)),
  45. ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)),
  46. ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)),
  47. ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)),
  48. ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)),
  49. ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )
  50. TRIANGLE ((0 0, 0 9, 9 0, 0 0))
  51. TIN( ((0 0 0, 0 0 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 0 0 0)) )
  52. """
  53. for regexp, obj in WKT.items():
  54. if re.match(regexp, string):
  55. geo = 10
  56. return obj(geo)
  57. def read_WKB(buff):
  58. """Read the binary buffer and return a geometry object"""
  59. pass
  60. def intersects(lineA, lineB, with_z=False):
  61. """Return a list of points
  62. >>> lineA = Line([(0, 0), (4, 0)])
  63. >>> lineB = Line([(2, 2), (2, -2)])
  64. >>> intersects(lineA, lineB)
  65. Line([Point(2.000000, 0.000000)])
  66. """
  67. line = Line()
  68. if libvect.Vect_line_get_intersections(lineA.c_points, lineB.c_points,
  69. line.c_points, int(with_z)):
  70. return line
  71. else:
  72. return []
  73. #=============================================
  74. # GEOMETRY
  75. #=============================================
  76. def get_xyz(pnt):
  77. """Return a tuple with: x, y, z.
  78. >>> pnt = Point(0, 0)
  79. >>> get_xyz(pnt)
  80. (0.0, 0.0, 0.0)
  81. >>> get_xyz((1, 1))
  82. (1, 1, 0.0)
  83. >>> get_xyz((1, 1, 2))
  84. (1, 1, 2)
  85. >>> get_xyz((1, 1, 2, 2)) #doctest: +ELLIPSIS
  86. Traceback (most recent call last):
  87. ...
  88. ValueError: The the format of the point is not supported: (1, 1, 2, 2)
  89. """
  90. if isinstance(pnt, Point):
  91. if pnt.is2D:
  92. x, y = pnt.x, pnt.y
  93. z = 0.
  94. else:
  95. x, y, z = pnt.x, pnt.y, pnt.z
  96. else:
  97. if len(pnt) == 2:
  98. x, y = pnt
  99. z = 0.
  100. elif len(pnt) == 3:
  101. x, y, z = pnt
  102. else:
  103. str_error = "The the format of the point is not supported: {0!r}"
  104. raise ValueError(str_error.format(pnt))
  105. return x, y, z
  106. class Attrs(object):
  107. def __init__(self, cat, table, writable=False):
  108. self._cat = None
  109. self.cond = ''
  110. self.table = table
  111. self.cat = cat
  112. self.writable = writable
  113. def _get_cat(self):
  114. return self._cat
  115. def _set_cat(self, value):
  116. self._cat = value
  117. if value:
  118. # update condition
  119. self.cond = "%s=%d" % (self.table.key, value)
  120. cat = property(fget=_get_cat, fset=_set_cat,
  121. doc="Set and obtain cat value")
  122. def __getitem__(self, key):
  123. """Return the value stored in the attribute table.
  124. >>> from grass.pygrass.vector import VectorTopo
  125. >>> schools = VectorTopo('schools')
  126. >>> schools.open('r')
  127. >>> school = schools[1]
  128. >>> attrs = Attrs(school.cat, schools.table)
  129. >>> attrs['TAG']
  130. u'568'
  131. """
  132. #SELECT {cols} FROM {tname} WHERE {condition};
  133. try:
  134. cur = self.table.execute(sql.SELECT_WHERE.format(cols=key,
  135. tname=self.table.name,
  136. condition=self.cond))
  137. except:
  138. import ipdb; ipdb.set_trace()
  139. results = cur.fetchone()
  140. if results is not None:
  141. return results[0] if len(results) == 1 else results
  142. def __setitem__(self, key, value):
  143. """Set value of a given column of a table attribute.
  144. >>> from grass.pygrass.vector import VectorTopo
  145. >>> from grass.pygrass.utils import copy, remove
  146. >>> copy('schools', 'myschools', 'vect')
  147. >>> schools = VectorTopo('myschools')
  148. >>> schools.open('r')
  149. >>> school = schools[1]
  150. >>> attrs = Attrs(school.cat, schools.table, True)
  151. >>> attrs['TAG'] = 'New Label'
  152. >>> attrs['TAG']
  153. u'New Label'
  154. >>> attrs.table.conn.close()
  155. >>> remove('myschools','vect')
  156. """
  157. if self.writable:
  158. #UPDATE {tname} SET {new_col} = {old_col} WHERE {condition}
  159. values = '%s=%r' % (key, value)
  160. self.table.execute(sql.UPDATE_WHERE.format(tname=self.table.name,
  161. values=values,
  162. condition=self.cond))
  163. #self.table.conn.commit()
  164. else:
  165. str_err = "You can only read the attributes if the map is in another mapset"
  166. raise GrassError(str_err)
  167. def __dict__(self):
  168. """Return a dict of the attribute table row."""
  169. dic = {}
  170. for key, val in zip(self.keys(), self.values()):
  171. dic[key] = val
  172. return dic
  173. def values(self):
  174. """Return the values of the attribute table row.
  175. >>> from grass.pygrass.vector import VectorTopo
  176. >>> schools = VectorTopo('schools')
  177. >>> schools.open('r')
  178. >>> school = schools[1]
  179. >>> attrs = Attrs(school.cat, schools.table)
  180. >>> attrs.values() # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
  181. (1,
  182. ...
  183. None)
  184. """
  185. #SELECT {cols} FROM {tname} WHERE {condition}
  186. cur = self.table.execute(sql.SELECT_WHERE.format(cols='*',
  187. tname=self.table.name,
  188. condition=self.cond))
  189. return cur.fetchone()
  190. def keys(self):
  191. """Return the column name of the attribute table.
  192. >>> from grass.pygrass.vector import VectorTopo
  193. >>> schools = VectorTopo('schools')
  194. >>> schools.open('r')
  195. >>> school = schools[1]
  196. >>> attrs = Attrs(school.cat, schools.table)
  197. >>> attrs.keys() # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
  198. [u'cat',
  199. ...
  200. u'NOTES']
  201. """
  202. return self.table.columns.names()
  203. def commit(self):
  204. """Save the changes"""
  205. self.table.conn.commit()
  206. class Geo(object):
  207. """
  208. >>> geo0 = Geo()
  209. >>> points = ctypes.pointer(libvect.line_pnts())
  210. >>> cats = ctypes.pointer(libvect.line_cats())
  211. >>> geo1 = Geo(c_points=points, c_cats=cats)
  212. """
  213. gtype = None
  214. def __init__(self, v_id=0, c_mapinfo=None, c_points=None, c_cats=None,
  215. table=None, writable=False, is2D=True):
  216. self.id = v_id # vector id
  217. self.c_mapinfo = c_mapinfo
  218. self.is2D = (is2D if is2D is not None else
  219. bool(libvect.Vect_is_3d(self.c_mapinfo) != 1))
  220. read = False
  221. # set c_points
  222. if c_points is None:
  223. self.c_points = ctypes.pointer(libvect.line_pnts())
  224. read = True
  225. else:
  226. self.c_points = c_points
  227. # set c_cats
  228. if c_cats is None:
  229. self.c_cats = ctypes.pointer(libvect.line_cats())
  230. read = True
  231. else:
  232. self.c_cats = c_cats
  233. # set the attributes
  234. self.attrs = None
  235. if table is not None:
  236. self.attrs = Attrs(self.cat, table, writable)
  237. if self.id and self.c_mapinfo is not None and read:
  238. self.read()
  239. @property
  240. def cat(self):
  241. if self.c_cats.contents.cat:
  242. return self.c_cats.contents.cat.contents.value
  243. def is_with_topology(self):
  244. if self.c_mapinfo is not None:
  245. return self.c_mapinfo.contents.level == 2
  246. else:
  247. return False
  248. def read(self):
  249. """Read and set the coordinates of the centroid from the vector map,
  250. using the centroid_id and calling the Vect_read_line C function"""
  251. self.id, ftype, c_points, c_cats = c_read_line(self.id, self.c_mapinfo,
  252. self.c_points,
  253. self.c_cats)
  254. class Point(Geo):
  255. """Instantiate a Point object that could be 2 or 3D, default
  256. parameters are 0.
  257. ::
  258. >>> pnt = Point()
  259. >>> pnt.x
  260. 0.0
  261. >>> pnt.y
  262. 0.0
  263. >>> pnt.z
  264. >>> pnt.is2D
  265. True
  266. >>> pnt
  267. Point(0.000000, 0.000000)
  268. >>> pnt.z = 0
  269. >>> pnt.is2D
  270. False
  271. >>> pnt
  272. Point(0.000000, 0.000000, 0.000000)
  273. >>> print(pnt)
  274. POINT(0.000000 0.000000 0.000000)
  275. ..
  276. """
  277. # geometry type
  278. gtype = libvect.GV_POINT
  279. def __init__(self, x=0, y=0, z=None, **kargs):
  280. super(Point, self).__init__(**kargs)
  281. if self.id and self.c_mapinfo:
  282. self.read()
  283. else:
  284. self.is2D = True if z is None else False
  285. z = z if z is not None else 0
  286. libvect.Vect_append_point(self.c_points, x, y, z)
  287. def _get_x(self):
  288. return self.c_points.contents.x[0]
  289. def _set_x(self, value):
  290. self.c_points.contents.x[0] = value
  291. x = property(fget=_get_x, fset=_set_x,
  292. doc="Set and obtain x coordinate")
  293. def _get_y(self):
  294. return self.c_points.contents.y[0]
  295. def _set_y(self, value):
  296. self.c_points.contents.y[0] = value
  297. y = property(fget=_get_y, fset=_set_y,
  298. doc="Set and obtain y coordinate")
  299. def _get_z(self):
  300. if self.is2D:
  301. return None
  302. return self.c_points.contents.z[0]
  303. def _set_z(self, value):
  304. if value is None:
  305. self.is2D = True
  306. self.c_points.contents.z[0] = 0
  307. else:
  308. self.c_points.contents.z[0] = value
  309. self.is2D = False
  310. z = property(fget=_get_z, fset=_set_z,
  311. doc="Set and obtain z coordinate")
  312. def __str__(self):
  313. return self.get_wkt()
  314. def __repr__(self):
  315. return "Point(%s)" % ', '.join(['%f' % coor for coor in self.coords()])
  316. def __eq__(self, pnt):
  317. """Return True if the coordinates are the same.
  318. >>> p0 = Point()
  319. >>> p1 = Point()
  320. >>> p2 = Point(1, 1)
  321. >>> p0 == p1
  322. True
  323. >>> p1 == p2
  324. False
  325. """
  326. if isinstance(pnt, Point):
  327. return pnt.coords() == self.coords()
  328. return Point(*pnt).coords() == self.coords()
  329. def __ne__(self, other):
  330. return not self == other
  331. # Restore Python 2 hashing beaviour on Python 3
  332. __hash__ = object.__hash__
  333. def coords(self):
  334. """Return a tuple with the point coordinates. ::
  335. >>> pnt = Point(10, 100)
  336. >>> pnt.coords()
  337. (10.0, 100.0)
  338. If the point is 2D return a x, y tuple. But if we change the ``z``
  339. the Point object become a 3D point, therefore the method return a
  340. x, y, z tuple. ::
  341. >>> pnt.z = 1000.
  342. >>> pnt.coords()
  343. (10.0, 100.0, 1000.0)
  344. ..
  345. """
  346. if self.is2D:
  347. return self.x, self.y
  348. else:
  349. return self.x, self.y, self.z
  350. def get_wkt(self):
  351. """Return a "well know text" (WKT) geometry string. ::
  352. >>> pnt = Point(10, 100)
  353. >>> pnt.get_wkt()
  354. 'POINT(10.000000 100.000000)'
  355. .. warning::
  356. Only ``POINT`` (2/3D) are supported, ``POINTM`` and ``POINT`` with:
  357. ``XYZM`` are not supported yet.
  358. """
  359. return "POINT(%s)" % ' '.join(['%f' % coord
  360. for coord in self.coords()])
  361. def get_wkb(self):
  362. """Return a "well know binary" (WKB) geometry buffer
  363. .. warning::
  364. Not implemented yet.
  365. """
  366. pass
  367. def distance(self, pnt):
  368. """Calculate distance of 2 points, using the Vect_points_distance
  369. C function, If one of the point have z == None, return the 2D distance.
  370. :param pnt: the point for calculate the distance
  371. :type pnt: a Point object or a tuple with the coordinates
  372. >>> pnt0 = Point(0, 0, 0)
  373. >>> pnt1 = Point(1, 0)
  374. >>> pnt0.distance(pnt1)
  375. 1.0
  376. >>> pnt1.z = 1
  377. >>> pnt1
  378. Point(1.000000, 0.000000, 1.000000)
  379. >>> pnt0.distance(pnt1)
  380. 1.4142135623730951
  381. """
  382. if self.is2D or pnt.is2D:
  383. return libvect.Vect_points_distance(self.x, self.y, 0,
  384. pnt.x, pnt.y, 0, 0)
  385. else:
  386. return libvect.Vect_points_distance(self.x, self.y, self.z,
  387. pnt.x, pnt.y, pnt.z, 1)
  388. def buffer(self, dist=None, dist_x=None, dist_y=None, angle=0,
  389. round_=True, tol=0.1):
  390. """Return the buffer area around the point, using the
  391. ``Vect_point_buffer2`` C function.
  392. :param dist: the distance around the point
  393. :type dist: num
  394. :param dist_x: the distance along x
  395. :type dist_x: num
  396. :param dist_y: the distance along y
  397. :type dist_y: num
  398. :param angle: the angle between 0x and major axis
  399. :type angle: num
  400. :param round_: to make corners round
  401. :type round_: bool
  402. :param tol: fix the maximum distance between theoretical arc and
  403. output segments
  404. :type tol: float
  405. :returns: the buffer as Area object
  406. >>> pnt = Point(0, 0)
  407. >>> area = pnt.buffer(10)
  408. >>> area.boundary #doctest: +ELLIPSIS
  409. Line([Point(10.000000, 0.000000),...Point(10.000000, 0.000000)])
  410. >>> area.centroid
  411. Point(0.000000, 0.000000)
  412. >>> area.isles
  413. []
  414. """
  415. if dist is not None:
  416. dist_x = dist
  417. dist_y = dist
  418. elif not dist_x or not dist_y:
  419. raise TypeError('TypeError: buffer expected 1 arguments, got 0')
  420. bound = Line()
  421. p_points = ctypes.pointer(bound.c_points)
  422. libvect.Vect_point_buffer2(self.x, self.y,
  423. dist_x, dist_y,
  424. angle, int(round_), tol,
  425. p_points)
  426. return Area(boundary=bound, centroid=self)
  427. class Line(Geo):
  428. """Instantiate a new Line with a list of tuple, or with a list of Point. ::
  429. >>> line = Line([(0, 0), (1, 1), (2, 0), (1, -1)])
  430. >>> line #doctest: +NORMALIZE_WHITESPACE
  431. Line([Point(0.000000, 0.000000),
  432. Point(1.000000, 1.000000),
  433. Point(2.000000, 0.000000),
  434. Point(1.000000, -1.000000)])
  435. ..
  436. """
  437. # geometry type
  438. gtype = libvect.GV_LINE
  439. def __init__(self, points=None, **kargs):
  440. super(Line, self).__init__(**kargs)
  441. if points is not None:
  442. for pnt in points:
  443. self.append(pnt)
  444. def __getitem__(self, key):
  445. """Get line point of given index, slice allowed. ::
  446. >>> line = Line([(0, 0), (1, 1), (2, 2), (3, 3)])
  447. >>> line[1]
  448. Point(1.000000, 1.000000)
  449. >>> line[-1]
  450. Point(3.000000, 3.000000)
  451. >>> line[:2]
  452. [Point(0.000000, 0.000000), Point(1.000000, 1.000000)]
  453. ..
  454. """
  455. #TODO:
  456. # line[0].x = 10 is not working
  457. #pnt.c_px = ctypes.pointer(self.c_points.contents.x[indx])
  458. # pnt.c_px = ctypes.cast(id(self.c_points.contents.x[indx]),
  459. # ctypes.POINTER(ctypes.c_double))
  460. if isinstance(key, slice):
  461. #import pdb; pdb.set_trace()
  462. #Get the start, stop, and step from the slice
  463. return [Point(self.c_points.contents.x[indx],
  464. self.c_points.contents.y[indx],
  465. None if self.is2D else self.c_points.contents.z[indx])
  466. for indx in range(*key.indices(len(self)))]
  467. elif isinstance(key, int):
  468. if key < 0: # Handle negative indices
  469. key += self.c_points.contents.n_points
  470. if key >= self.c_points.contents.n_points:
  471. raise IndexError('Index out of range')
  472. return Point(self.c_points.contents.x[key],
  473. self.c_points.contents.y[key],
  474. None if self.is2D else self.c_points.contents.z[key])
  475. else:
  476. raise ValueError("Invalid argument type: %r." % key)
  477. def __setitem__(self, indx, pnt):
  478. """Change the coordinate of point. ::
  479. >>> line = Line([(0, 0), (1, 1)])
  480. >>> line[0] = (2, 2)
  481. >>> line
  482. Line([Point(2.000000, 2.000000), Point(1.000000, 1.000000)])
  483. ..
  484. """
  485. x, y, z = get_xyz(pnt)
  486. self.c_points.contents.x[indx] = x
  487. self.c_points.contents.y[indx] = y
  488. self.c_points.contents.z[indx] = z
  489. def __iter__(self):
  490. """Return a Point generator of the Line"""
  491. return (self.__getitem__(i) for i in range(self.__len__()))
  492. def __len__(self):
  493. """Return the number of points of the line."""
  494. return self.c_points.contents.n_points
  495. def __str__(self):
  496. return self.get_wkt()
  497. def __repr__(self):
  498. return "Line([%s])" % ', '.join([repr(pnt) for pnt in self.__iter__()])
  499. def get_pnt(self, distance, angle=0, slope=0):
  500. """Return a Point object on line in the specified distance, using the
  501. `Vect_point_on_line` C function.
  502. Raise a ValueError If the distance exceed the Line length. ::
  503. >>> line = Line([(0, 0), (1, 1)])
  504. >>> line.get_pnt(5) #doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
  505. Traceback (most recent call last):
  506. ...
  507. ValueError: The distance exceed the lenght of the line,
  508. that is: 1.414214
  509. >>> line.get_pnt(1)
  510. Point(0.707107, 0.707107)
  511. ..
  512. """
  513. # instantiate an empty Point object
  514. maxdist = self.length()
  515. if distance > maxdist:
  516. str_err = "The distance exceed the lenght of the line, that is: %f"
  517. raise ValueError(str_err % maxdist)
  518. pnt = Point(0, 0, -9999)
  519. libvect.Vect_point_on_line(self.c_points, distance,
  520. pnt.c_points.contents.x,
  521. pnt.c_points.contents.y,
  522. pnt.c_points.contents.z,
  523. angle, slope)
  524. pnt.is2D = self.is2D
  525. return pnt
  526. def append(self, pnt):
  527. """Appends one point to the end of a line, using the
  528. ``Vect_append_point`` C function.
  529. :param pnt: the point to add to line
  530. :type pnt: a Point object or a tuple with the coordinates
  531. >>> line = Line()
  532. >>> line.append((10, 100))
  533. >>> line
  534. Line([Point(10.000000, 100.000000)])
  535. >>> line.append((20, 200))
  536. >>> line
  537. Line([Point(10.000000, 100.000000), Point(20.000000, 200.000000)])
  538. Like python list.
  539. """
  540. x, y, z = get_xyz(pnt)
  541. libvect.Vect_append_point(self.c_points, x, y, z)
  542. def bbox(self, bbox=None):
  543. """Return the bounding box of the line, using ``Vect_line_box``
  544. C function. ::
  545. >>> line = Line([(0, 0), (0, 1), (2, 1), (2, 0)])
  546. >>> bbox = line.bbox()
  547. >>> bbox
  548. Bbox(1.0, 0.0, 2.0, 0.0)
  549. ..
  550. """
  551. bbox = bbox if bbox else Bbox()
  552. libvect.Vect_line_box(self.c_points, bbox.c_bbox)
  553. return bbox
  554. def extend(self, line, forward=True):
  555. """Appends points to the end of a line.
  556. :param line: it is possible to extend a line, give a list of points,
  557. or directly with a line_pnts struct.
  558. :type line: Line object ot list of points
  559. :param forward: if forward is True the line is extend forward otherwise
  560. is extend backward. The method use the
  561. `Vect_append_points` C function.
  562. :type forward: bool
  563. >>> line = Line([(0, 0), (1, 1)])
  564. >>> line.extend( Line([(2, 2), (3, 3)]) )
  565. >>> line #doctest: +NORMALIZE_WHITESPACE
  566. Line([Point(0.000000, 0.000000),
  567. Point(1.000000, 1.000000),
  568. Point(2.000000, 2.000000),
  569. Point(3.000000, 3.000000)])
  570. """
  571. # set direction
  572. if forward:
  573. direction = libvect.GV_FORWARD
  574. else:
  575. direction = libvect.GV_BACKWARD
  576. # check if is a Line object
  577. if isinstance(line, Line):
  578. c_points = line.c_points
  579. else:
  580. # instantiate a Line object
  581. lin = Line()
  582. for pnt in line:
  583. # add the points to the line
  584. lin.append(pnt)
  585. c_points = lin.c_points
  586. libvect.Vect_append_points(self.c_points, c_points, direction)
  587. def insert(self, indx, pnt):
  588. """Insert new point at index position and move all old points at
  589. that position and above up, using ``Vect_line_insert_point``
  590. C function.
  591. :param indx: the index where add new point
  592. :type indx: int
  593. :param pnt: the point to add
  594. :type pnt: a Point object
  595. >>> line = Line([(0, 0), (1, 1)])
  596. >>> line.insert(0, Point(1.000000, -1.000000) )
  597. >>> line #doctest: +NORMALIZE_WHITESPACE
  598. Line([Point(1.000000, -1.000000),
  599. Point(0.000000, 0.000000),
  600. Point(1.000000, 1.000000)])
  601. """
  602. if indx < 0: # Handle negative indices
  603. indx += self.c_points.contents.n_points
  604. if indx >= self.c_points.contents.n_points:
  605. raise IndexError('Index out of range')
  606. x, y, z = get_xyz(pnt)
  607. libvect.Vect_line_insert_point(self.c_points, indx, x, y, z)
  608. def length(self):
  609. """Calculate line length, 3D-length in case of 3D vector line, using
  610. `Vect_line_length` C function. ::
  611. >>> line = Line([(0, 0), (1, 1), (0, 1)])
  612. >>> line.length()
  613. 2.414213562373095
  614. ..
  615. """
  616. return libvect.Vect_line_length(self.c_points)
  617. def length_geodesic(self):
  618. """Calculate line length, usig `Vect_line_geodesic_length` C function.
  619. ::
  620. >>> line = Line([(0, 0), (1, 1), (0, 1)])
  621. >>> line.length_geodesic()
  622. 2.414213562373095
  623. ..
  624. """
  625. return libvect.Vect_line_geodesic_length(self.c_points)
  626. def distance(self, pnt):
  627. """Calculate the distance between line and a point.
  628. :param pnt: the point to calculate distance
  629. :type pnt: a Point object or a tuple with the coordinates
  630. Return a namedtuple with:
  631. * point: the closest point on the line,
  632. * dist: the distance between these two points,
  633. * spdist: distance to point on line from segment beginning
  634. * sldist: distance to point on line form line beginning along line
  635. The distance is compute using the ``Vect_line_distance`` C function.
  636. >>> point = Point(2.3, 0.5)
  637. >>> line = Line([(0, 0), (2, 0), (3, 0)])
  638. >>> line.distance(point) #doctest: +NORMALIZE_WHITESPACE
  639. LineDist(point=Point(2.300000, 0.000000),
  640. dist=0.5, spdist=0.2999999999999998, sldist=2.3)
  641. """
  642. # instantite outputs
  643. cx = ctypes.c_double(0)
  644. cy = ctypes.c_double(0)
  645. cz = ctypes.c_double(0)
  646. dist = ctypes.c_double(0)
  647. sp_dist = ctypes.c_double(0)
  648. lp_dist = ctypes.c_double(0)
  649. libvect.Vect_line_distance(self.c_points,
  650. pnt.x, pnt.y, 0 if pnt.is2D else pnt.z,
  651. 0 if self.is2D else 1,
  652. ctypes.byref(cx), ctypes.byref(cy),
  653. ctypes.byref(cz), ctypes.byref(dist),
  654. ctypes.byref(sp_dist),
  655. ctypes.byref(lp_dist))
  656. # instantiate the Point class
  657. point = Point(cx.value, cy.value, cz.value)
  658. point.is2D = self.is2D
  659. return LineDist(point, dist.value, sp_dist.value, lp_dist.value)
  660. def get_first_cat(self):
  661. """Fetches FIRST category number for given vector line and field, using
  662. the ``Vect_get_line_cat`` C function.
  663. .. warning::
  664. Not implemented yet.
  665. """
  666. # TODO: add this method.
  667. libvect.Vect_get_line_cat(self.map, self.id, self.field)
  668. pass
  669. def pop(self, indx):
  670. """Return the point in the index position and remove from the Line.
  671. :param indx: the index where add new point
  672. :type indx: int
  673. >>> line = Line([(0, 0), (1, 1), (2, 2)])
  674. >>> midle_pnt = line.pop(1)
  675. >>> midle_pnt
  676. Point(1.000000, 1.000000)
  677. >>> line
  678. Line([Point(0.000000, 0.000000), Point(2.000000, 2.000000)])
  679. """
  680. if indx < 0: # Handle negative indices
  681. indx += self.c_points.contents.n_points
  682. if indx >= self.c_points.contents.n_points:
  683. raise IndexError('Index out of range')
  684. pnt = self.__getitem__(indx)
  685. libvect.Vect_line_delete_point(self.c_points, indx)
  686. return pnt
  687. def delete(self, indx):
  688. """Remove the point in the index position.
  689. :param indx: the index where add new point
  690. :type indx: int
  691. >>> line = Line([(0, 0), (1, 1), (2, 2)])
  692. >>> line.delete(-1)
  693. >>> line
  694. Line([Point(0.000000, 0.000000), Point(1.000000, 1.000000)])
  695. """
  696. if indx < 0: # Handle negative indices
  697. indx += self.c_points.contents.n_points
  698. if indx >= self.c_points.contents.n_points:
  699. raise IndexError('Index out of range')
  700. libvect.Vect_line_delete_point(self.c_points, indx)
  701. def prune(self):
  702. """Remove duplicate points, i.e. zero length segments, using
  703. `Vect_line_prune` C function. ::
  704. >>> line = Line([(0, 0), (1, 1), (1, 1), (2, 2)])
  705. >>> line.prune()
  706. >>> line #doctest: +NORMALIZE_WHITESPACE
  707. Line([Point(0.000000, 0.000000),
  708. Point(1.000000, 1.000000),
  709. Point(2.000000, 2.000000)])
  710. ..
  711. """
  712. libvect.Vect_line_prune(self.c_points)
  713. def prune_thresh(self, threshold):
  714. """Remove points in threshold, using the ``Vect_line_prune_thresh``
  715. C funtion.
  716. :param threshold: the threshold value where prune points
  717. :type threshold: num
  718. >>> line = Line([(0, 0), (1.0, 1.0), (1.2, 0.9), (2, 2)])
  719. >>> line.prune_thresh(0.5)
  720. >>> line #doctest: +SKIP +NORMALIZE_WHITESPACE
  721. Line([Point(0.000000, 0.000000),
  722. Point(1.000000, 1.000000),
  723. Point(2.000000, 2.000000)])
  724. .. warning ::
  725. prune_thresh is not working yet.
  726. """
  727. libvect.Vect_line_prune(self.c_points, ctypes.c_double(threshold))
  728. def remove(self, pnt):
  729. """Delete point at given index and move all points above down, using
  730. `Vect_line_delete_point` C function.
  731. :param pnt: the point to remove
  732. :type pnt: a Point object or a tuple with the coordinates
  733. >>> line = Line([(0, 0), (1, 1), (2, 2)])
  734. >>> line.remove((2, 2))
  735. >>> line[-1]
  736. Point(1.000000, 1.000000)
  737. ..
  738. """
  739. for indx, point in enumerate(self.__iter__()):
  740. if pnt == point:
  741. libvect.Vect_line_delete_point(self.c_points, indx)
  742. return
  743. raise ValueError('list.remove(x): x not in list')
  744. def reverse(self):
  745. """Reverse the order of vertices, using `Vect_line_reverse`
  746. C function. ::
  747. >>> line = Line([(0, 0), (1, 1), (2, 2)])
  748. >>> line.reverse()
  749. >>> line #doctest: +NORMALIZE_WHITESPACE
  750. Line([Point(2.000000, 2.000000),
  751. Point(1.000000, 1.000000),
  752. Point(0.000000, 0.000000)])
  753. ..
  754. """
  755. libvect.Vect_line_reverse(self.c_points)
  756. def segment(self, start, end):
  757. """Create line segment. using the ``Vect_line_segment`` C function.
  758. :param start: distance from the begining of the line where
  759. the segment start
  760. :type start: float
  761. :param end: distance from the begining of the line where
  762. the segment end
  763. :type end: float
  764. ::
  765. # x (1, 1)
  766. # |
  767. # |-
  768. # |
  769. # x--------x (1, 0)
  770. # (0, 0) ^
  771. >>> line = Line([(0, 0), (1, 0), (1, 1)])
  772. >>> line.segment(0.5, 1.5) #doctest: +NORMALIZE_WHITESPACE
  773. Line([Point(0.500000, 0.000000),
  774. Point(1.000000, 0.000000),
  775. Point(1.000000, 0.500000)])
  776. """
  777. line = Line()
  778. libvect.Vect_line_segment(self.c_points, start, end, line.c_points)
  779. return line
  780. def tolist(self):
  781. """Return a list of tuple. ::
  782. >>> line = Line([(0, 0), (1, 1), (2, 0), (1, -1)])
  783. >>> line.tolist()
  784. [(0.0, 0.0), (1.0, 1.0), (2.0, 0.0), (1.0, -1.0)]
  785. ..
  786. """
  787. return [pnt.coords() for pnt in self.__iter__()]
  788. def toarray(self):
  789. """Return an array of coordinates. ::
  790. >>> line = Line([(0, 0), (1, 1), (2, 0), (1, -1)])
  791. >>> line.toarray() #doctest: +NORMALIZE_WHITESPACE
  792. array([[ 0., 0.],
  793. [ 1., 1.],
  794. [ 2., 0.],
  795. [ 1., -1.]])
  796. ..
  797. """
  798. return np.array(self.tolist())
  799. def get_wkt(self):
  800. """Return a Well Known Text string of the line. ::
  801. >>> line = Line([(0, 0), (1, 1), (1, 2)])
  802. >>> line.get_wkt() #doctest: +ELLIPSIS
  803. 'LINESTRING(0.000000 0.000000, ..., 1.000000 2.000000)'
  804. ..
  805. """
  806. return "LINESTRING(%s)" % ', '.join([
  807. ' '.join(['%f' % coord for coord in pnt.coords()])
  808. for pnt in self.__iter__()])
  809. def from_wkt(self, wkt):
  810. """Create a line reading a WKT string.
  811. :param wkt: the WKT string containing the LINESTRING
  812. :type wkt: str
  813. >>> line = Line()
  814. >>> line.from_wkt("LINESTRING(0 0,1 1,1 2)")
  815. >>> line #doctest: +NORMALIZE_WHITESPACE
  816. Line([Point(0.000000, 0.000000),
  817. Point(1.000000, 1.000000),
  818. Point(1.000000, 2.000000)])
  819. ..
  820. """
  821. match = re.match('LINESTRING\((.*)\)', wkt)
  822. if match:
  823. self.reset()
  824. for coord in match.groups()[0].strip().split(','):
  825. self.append(tuple([float(e) for e in coord.split(' ')]))
  826. else:
  827. return None
  828. def get_wkb(self):
  829. """Return a WKB buffer.
  830. .. warning::
  831. Not implemented yet.
  832. """
  833. pass
  834. def buffer(self, dist=None, dist_x=None, dist_y=None,
  835. angle=0, round_=True, caps=True, tol=0.1):
  836. """Return the buffer area around the line, using the
  837. ``Vect_line_buffer2`` C function.
  838. :param dist: the distance around the line
  839. :type dist: num
  840. :param dist_x: the distance along x
  841. :type dist_x: num
  842. :param dist_y: the distance along y
  843. :type dist_y: num
  844. :param angle: the angle between 0x and major axis
  845. :type angle: num
  846. :param round_: to make corners round
  847. :type round_: bool
  848. :param tol: fix the maximum distance between theoretical arc and
  849. output segments
  850. :type tol: float
  851. :returns: the buffer as Area object
  852. >>> line = Line([(0, 0), (0, 2)])
  853. >>> area = line.buffer(10)
  854. >>> area.boundary #doctest: +ELLIPSIS
  855. Line([Point(-10.000000, 0.000000),...Point(-10.000000, 0.000000)])
  856. >>> area.centroid
  857. Point(0.000000, 0.000000)
  858. >>> area.isles
  859. []
  860. ..
  861. """
  862. if dist is not None:
  863. dist_x = dist
  864. dist_y = dist
  865. elif not dist_x or not dist_y:
  866. raise TypeError('TypeError: buffer expected 1 arguments, got 0')
  867. p_bound = ctypes.pointer(ctypes.pointer(libvect.line_pnts()))
  868. pp_isle = ctypes.pointer(ctypes.pointer(
  869. ctypes.pointer(libvect.line_pnts())))
  870. n_isles = ctypes.pointer(ctypes.c_int())
  871. libvect.Vect_line_buffer2(self.c_points,
  872. dist_x, dist_y, angle,
  873. int(round_), int(caps), tol,
  874. p_bound, pp_isle, n_isles)
  875. return Area(boundary=Line(c_points=p_bound.contents),
  876. centroid=self[0],
  877. isles=[Line(c_points=pp_isle[i].contents)
  878. for i in range(n_isles.contents.value)])
  879. def reset(self):
  880. """Reset line, using `Vect_reset_line` C function. ::
  881. >>> line = Line([(0, 0), (1, 1), (2, 0), (1, -1)])
  882. >>> len(line)
  883. 4
  884. >>> line.reset()
  885. >>> len(line)
  886. 0
  887. >>> line
  888. Line([])
  889. ..
  890. """
  891. libvect.Vect_reset_line(self.c_points)
  892. def nodes(self):
  893. """Return the nodes in the line"""
  894. if self.is_with_topology():
  895. n1 = ctypes.c_int()
  896. n2 = ctypes.c_int()
  897. libvect.Vect_get_line_nodes(self.c_mapinfo, self.id,
  898. ctypes.byref(n1),
  899. ctypes.byref(n2))
  900. return (Node(n1.value, self.c_mapinfo),
  901. Node(n2.value, self.c_mapinfo))
  902. class Node(object):
  903. def __init__(self, v_id, c_mapinfo):
  904. self.id = v_id # vector id
  905. self.c_mapinfo = c_mapinfo
  906. self.is2D = bool(libvect.Vect_is_3d(self.c_mapinfo) != 1)
  907. self.nlines = libvect.Vect_get_node_n_lines(self.c_mapinfo, self.id)
  908. def __len__(self):
  909. return self.nlines
  910. def __iter__(self):
  911. return self.ilines()
  912. def __repr__(self):
  913. return "Node(%d)" % self.id
  914. def coords(self):
  915. """Return a tuple with the node coordinates."""
  916. x = ctypes.c_double()
  917. y = ctypes.c_double()
  918. z = ctypes.c_double()
  919. libvect.Vect_get_node_coor(self.c_mapinfo, self.id, ctypes.byref(x),
  920. ctypes.byref(y), ctypes.byref(z))
  921. return (x.value, y.value) if self.is2D else (x.value, y.value, z.value)
  922. def ilines(self, only_in=False, only_out=False):
  923. """Return a generator with all lines id connected to a node.
  924. The line id is negative if line is ending on the node and positive if
  925. starting from the node.
  926. :param only_in: Return only the lines that are ending in the node
  927. :type only_in: bool
  928. :param only_out: Return only the lines that are starting in the node
  929. :type only_out: bool
  930. """
  931. for iline in range(self.nlines):
  932. lid = libvect.Vect_get_node_line(self.c_mapinfo, self.id, iline)
  933. if (not only_in and lid > 0) or (not only_out and lid < 0):
  934. yield lid
  935. def lines(self, only_in=False, only_out=False):
  936. """Return a generator with all lines connected to a node.
  937. :param only_in: Return only the lines that are ending in the node
  938. :type only_in: bool
  939. :param only_out: Return only the lines that are starting in the node
  940. :type only_out: bool
  941. """
  942. for iline in self.ilines(only_in, only_out):
  943. yield Line(v_id=abs(iline), c_mapinfo=self.c_mapinfo)
  944. def angles(self):
  945. """Return a generator with all lines angles in a node."""
  946. for iline in range(self.nlines):
  947. yield libvect.Vect_get_node_line_angle(self.c_mapinfo,
  948. self.id, iline)
  949. class Boundary(Line):
  950. """
  951. """
  952. # geometry type
  953. gtype = libvect.GV_BOUNDARY
  954. def __init__(self, lines=None, left=None, right=None,
  955. **kargs):
  956. v_id = kargs.get('v_id', 0)
  957. self.dir = libvect.GV_FORWARD if v_id > 0 else libvect.GV_BACKWARD
  958. super(Boundary, self).__init__(**kargs)
  959. self.c_left = ctypes.pointer(ctypes.c_int())
  960. self.c_right = ctypes.pointer(ctypes.c_int())
  961. #self.get_left_right()
  962. @property
  963. def left_id(self):
  964. return self.c_left.contents.value
  965. @property
  966. def right_id(self):
  967. return self.c_right.contents.value
  968. def __repr__(self):
  969. return "Boundary(v_id=%r)" % self.id
  970. def _get_centroid(self, side, idonly=False):
  971. if side > 0:
  972. v_id = libvect.Vect_get_area_centroid(self.c_mapinfo, side)
  973. v_id = v_id if v_id else None
  974. if idonly:
  975. return v_id
  976. else:
  977. cntr = Centroid(v_id=v_id, c_mapinfo=self.c_mapinfo)
  978. return cntr
  979. def get_left_centroid(self, idonly=False):
  980. """Return left value
  981. :param idonly: True to return only the cat of feature
  982. :type idonly: bool
  983. """
  984. return self._get_centroid(self.left_id, idonly)
  985. def get_right_centroid(self, idonly=False):
  986. """Return right value
  987. :param idonly: True to return only the cat of feature
  988. :type idonly: bool
  989. """
  990. return self._get_centroid(self.left_id, idonly)
  991. def get_left_right(self):
  992. """Return left and right value"""
  993. libvect.Vect_get_line_areas(self.c_mapinfo, self.id,
  994. self.c_left, self.c_right)
  995. return self.c_left.contents.value, self.c_right.contents.value
  996. def area(self):
  997. """Return the area of the polygon.
  998. >>> bound = Boundary(points=[(0, 0), (0, 2), (2, 2), (2, 0),
  999. ... (0, 0)])
  1000. >>> bound.area()
  1001. 4.0
  1002. """
  1003. libgis.G_begin_polygon_area_calculations()
  1004. return libgis.G_area_of_polygon(self.c_points.contents.x,
  1005. self.c_points.contents.y,
  1006. self.c_points.contents.n_points)
  1007. class Centroid(Point):
  1008. """The Centroid class inherit from the Point class.
  1009. Centroid contains an attribute with the C Map_info struct, and attributes
  1010. with the id of the Area. ::
  1011. >>> centroid = Centroid(x=0, y=10)
  1012. >>> centroid
  1013. Centoid(0.000000, 10.000000)
  1014. >>> from grass.pygrass.vector import VectorTopo
  1015. >>> geo = VectorTopo('geology')
  1016. >>> geo.open(mode='r')
  1017. >>> centroid = Centroid(v_id=1, c_mapinfo=geo.c_mapinfo)
  1018. >>> centroid
  1019. Centoid(893202.874416, 297339.312795)
  1020. ..
  1021. """
  1022. # geometry type
  1023. gtype = libvect.GV_CENTROID
  1024. def __init__(self, area_id=None, **kargs):
  1025. super(Centroid, self).__init__(**kargs)
  1026. self.area_id = area_id
  1027. if self.id and self.c_mapinfo and self.area_id is None:
  1028. self.area_id = self.get_area_id()
  1029. elif self.c_mapinfo and self.area_id and self.id is None:
  1030. self.id = self.get_centroid_id()
  1031. if self.area_id is not None:
  1032. self.read()
  1033. #self.c_pline = ctypes.pointer(libvect.P_line()) if topology else None
  1034. def __repr__(self):
  1035. return "Centoid(%s)" % ', '.join(['%f' % co for co in self.coords()])
  1036. def get_centroid_id(self):
  1037. """Return the centroid_id, using the c_mapinfo and an area_id
  1038. attributes of the class, and calling the Vect_get_area_centroid
  1039. C function, if no centroid_id were found return None"""
  1040. centroid_id = libvect.Vect_get_area_centroid(self.c_mapinfo,
  1041. self.area_id)
  1042. return centroid_id if centroid_id != 0 else None
  1043. def get_area_id(self):
  1044. """Return the area_id, using the c_mapinfo and an centroid_id
  1045. attributes of the class, and calling the Vect_get_centroid_area
  1046. C function, if no area_id were found return None"""
  1047. area_id = libvect.Vect_get_centroid_area(self.c_mapinfo,
  1048. self.id)
  1049. return area_id if area_id != 0 else None
  1050. class Isle(Geo):
  1051. """An Isle is an area contained by another area.
  1052. """
  1053. def __init__(self, **kargs):
  1054. super(Isle, self).__init__(**kargs)
  1055. #self.area_id = area_id
  1056. def __repr__(self):
  1057. return "Isle(%d)" % (self.id)
  1058. def boundaries(self):
  1059. """Return a list of boundaries"""
  1060. ilist = Ilist()
  1061. libvect.Vect_get_isle_boundaries(self.c_mapinfo, self.id,
  1062. ilist.c_ilist)
  1063. return ilist
  1064. def bbox(self, bbox=None):
  1065. """Return bounding box of Isle"""
  1066. bbox = bbox if bbox else Bbox()
  1067. libvect.Vect_get_isle_box(self.c_mapinfo, self.id, bbox.c_bbox)
  1068. return bbox
  1069. def points(self):
  1070. """Return a Line object with the outer ring points"""
  1071. line = Line()
  1072. libvect.Vect_get_isle_points(self.c_mapinfo, self.id, line.c_points)
  1073. return line
  1074. def points_geos(self):
  1075. """Return a Line object with the outer ring points
  1076. """
  1077. return libvect.Vect_get_isle_points_geos(self.c_mapinfo, self.id)
  1078. def area_id(self):
  1079. """Returns area id for isle."""
  1080. return libvect.Vect_get_isle_area(self.c_mapinfo, self.id)
  1081. def alive(self):
  1082. """Check if isle is alive or dead (topology required)"""
  1083. return bool(libvect.Vect_isle_alive(self.c_mapinfo, self.id))
  1084. def contain_pnt(self, pnt):
  1085. """Check if point is in area.
  1086. :param pnt: the point to remove
  1087. :type pnt: a Point object or a tuple with the coordinates
  1088. """
  1089. bbox = self.bbox()
  1090. return bool(libvect.Vect_point_in_island(pnt.x, pnt.y,
  1091. self.c_mapinfo, self.id,
  1092. bbox.c_bbox.contents))
  1093. def area(self):
  1094. """Return the area value of an Isle"""
  1095. border = self.points()
  1096. return libgis.G_area_of_polygon(border.c_points.contents.x,
  1097. border.c_points.contents.y,
  1098. border.c_points.contents.n_points)
  1099. def perimeter(self):
  1100. """Return the perimeter value of an Isle.
  1101. """
  1102. border = self.points()
  1103. return libvect.Vect_line_geodesic_length(border.c_points)
  1104. class Isles(object):
  1105. def __init__(self, c_mapinfo, area_id=None):
  1106. self.c_mapinfo = c_mapinfo
  1107. self.area_id = area_id
  1108. self._isles_id = None
  1109. self._isles = None
  1110. if area_id:
  1111. self._isles_id = self.get_isles_id()
  1112. self._isles = self.get_isles()
  1113. def __len__(self):
  1114. return libvect.Vect_get_area_num_isles(self.c_mapinfo, self.area_id)
  1115. def __repr__(self):
  1116. return "Isles(%r)" % self.area_id
  1117. def __getitem__(self, key):
  1118. if self._isles is None:
  1119. self.get_isles()
  1120. return self._isles[key]
  1121. def get_isles_id(self):
  1122. """Return the id of isles"""
  1123. return [libvect.Vect_get_area_isle(self.c_mapinfo, self.area_id, i)
  1124. for i in range(self.__len__())]
  1125. def get_isles(self):
  1126. """Return isles"""
  1127. return [Isle(v_id=isle_id, c_mapinfo=self.c_mapinfo)
  1128. for isle_id in self._isles_id]
  1129. def select_by_bbox(self, bbox):
  1130. """Vect_select_isles_by_box
  1131. .. warning::
  1132. Not implemented yet.
  1133. """
  1134. pass
  1135. class Area(Geo):
  1136. """
  1137. Vect_build_line_area,
  1138. Vect_find_area,
  1139. Vect_get_area_box,
  1140. Vect_get_area_points_geos,
  1141. Vect_get_centroid_area,
  1142. Vect_get_isle_area,
  1143. Vect_get_line_areas,
  1144. Vect_get_num_areas,
  1145. Vect_get_point_in_area,
  1146. Vect_isle_find_area,
  1147. Vect_point_in_area,
  1148. Vect_point_in_area_outer_ring,
  1149. Vect_read_area_geos,
  1150. Vect_remove_small_areas,
  1151. Vect_select_areas_by_box,
  1152. Vect_select_areas_by_polygon
  1153. """
  1154. # geometry type
  1155. gtype = libvect.GV_AREA
  1156. def __init__(self, boundary=None, centroid=None, isles=None, **kargs):
  1157. super(Area, self).__init__(**kargs)
  1158. self.boundary = None
  1159. self.centroid = None
  1160. self.isles = None
  1161. if boundary and centroid:
  1162. self.boundary = boundary
  1163. self.centroid = centroid
  1164. self.isles = isles if isles else []
  1165. # set the attributes
  1166. if self.attrs and self.cat:
  1167. self.attrs.cat = self.cat
  1168. def __repr__(self):
  1169. return "Area(%d)" % self.id if self.id else "Area( )"
  1170. def init_from_id(self, area_id=None):
  1171. """Return an Area object"""
  1172. if area_id is None and self.id is None:
  1173. raise ValueError("You need to give or set the area_id")
  1174. self.id = area_id if area_id is not None else self.id
  1175. # get boundary
  1176. self.get_points()
  1177. # get isles
  1178. self.get_isles()
  1179. def get_points(self, line=None):
  1180. """Return a Line object with the outer ring
  1181. :param line: a Line object to fill with info from points of area
  1182. :type line: a Line object
  1183. """
  1184. line = Line() if line is None else line
  1185. libvect.Vect_get_area_points(self.c_mapinfo, self.id, line.c_points)
  1186. return line
  1187. def get_centroid(self, centroid=None):
  1188. """Return the centroid
  1189. :param centroid: a Centroid object to fill with info from centroid of area
  1190. :type centroid: a Centroid object
  1191. """
  1192. centroid_id = libvect.Vect_get_area_centroid(self.c_mapinfo, self.id)
  1193. if centroid_id:
  1194. if centroid:
  1195. centroid.id = centroid_id
  1196. centroid.read()
  1197. return centroid
  1198. return Centroid(v_id=centroid_id, c_mapinfo=self.c_mapinfo,
  1199. area_id=self.id)
  1200. def num_isles(self):
  1201. return libvect.Vect_get_area_num_isles(self.c_mapinfo, self.id)
  1202. def get_isles(self, isles=None):
  1203. """Instantiate the boundary attribute reading area_id"""
  1204. if isles is not None:
  1205. isles.area_id = self.id
  1206. return isles
  1207. return Isles(self.c_mapinfo, self.id)
  1208. def area(self):
  1209. """Returns area of area without areas of isles.
  1210. double Vect_get_area_area (const struct Map_info \*Map, int area)
  1211. """
  1212. return libvect.Vect_get_area_area(self.c_mapinfo, self.id)
  1213. def alive(self):
  1214. """Check if area is alive or dead (topology required)
  1215. """
  1216. return bool(libvect.Vect_area_alive(self.c_mapinfo, self.id))
  1217. def bbox(self, bbox=None):
  1218. """Return the Bbox of area
  1219. :param bbox: a Bbox object to fill with info from bounding box of area
  1220. :type bbox: a Bbox object
  1221. """
  1222. bbox = bbox if bbox else Bbox()
  1223. libvect.Vect_get_area_box(self.c_mapinfo, self.id, bbox.c_bbox)
  1224. return bbox
  1225. def buffer(self, dist=None, dist_x=None, dist_y=None,
  1226. angle=0, round_=True, caps=True, tol=0.1):
  1227. """Return the buffer area around the area, using the
  1228. ``Vect_area_buffer2`` C function.
  1229. :param dist: the distance around the area
  1230. :type dist: num
  1231. :param dist_x: the distance along x
  1232. :type dist_x: num
  1233. :param dist_y: the distance along y
  1234. :type dist_y: num
  1235. :param angle: the angle between 0x and major axis
  1236. :type angle: num
  1237. :param round_: to make corners round
  1238. :type round_: bool
  1239. :param tol: fix the maximum distance between theoretical arc and
  1240. output segments
  1241. :type tol: float
  1242. :returns: the buffer as Area object
  1243. """
  1244. if dist is not None:
  1245. dist_x = dist
  1246. dist_y = dist
  1247. elif not dist_x or not dist_y:
  1248. raise TypeError('TypeError: buffer expected 1 arguments, got 0')
  1249. p_bound = ctypes.pointer(ctypes.pointer(libvect.line_pnts()))
  1250. pp_isle = ctypes.pointer(ctypes.pointer(
  1251. ctypes.pointer(libvect.line_pnts())))
  1252. n_isles = ctypes.pointer(ctypes.c_int())
  1253. libvect.Vect_area_buffer2(self.c_mapinfo, self.id,
  1254. dist_x, dist_y, angle,
  1255. int(round_), int(caps), tol,
  1256. p_bound, pp_isle, n_isles)
  1257. return Area(boundary=Line(c_points=p_bound.contents),
  1258. centroid=self.centroid,
  1259. isles=[Line(c_points=pp_isle[i].contents)
  1260. for i in range(n_isles.contents.value)])
  1261. def boundaries(self, ilist=False):
  1262. """Creates list of boundaries for given area.
  1263. int Vect_get_area_boundaries(const struct Map_info \*Map,
  1264. int area, struct ilist \*List)
  1265. """
  1266. ilst = Ilist()
  1267. libvect.Vect_get_area_boundaries(self.c_mapinfo, self.id,
  1268. ilst.c_ilist)
  1269. if ilist:
  1270. return ilist
  1271. return [Boundary(v_id, c_mapinfo=self.c_mapinfo) for v_id in ilst]
  1272. def cats(self, cats=None):
  1273. """Get area categories.
  1274. :param cats: a Cats object to fill with info with area categories
  1275. :type cats: a Cats object
  1276. """
  1277. cats = cats if cats else Cats()
  1278. libvect.Vect_get_area_cats(self.c_mapinfo, self.id, cats.c_cats)
  1279. return cats
  1280. def get_first_cat(self):
  1281. """Find FIRST category of given field and area.
  1282. int Vect_get_area_cat(const struct Map_info \*Map, int area, int field)
  1283. """
  1284. pass
  1285. def contain_pnt(self, pnt, bbox=None):
  1286. """Check if point is in area.
  1287. :param pnt: the point to analyze
  1288. :type pnt: a Point object or a tuple with the coordinates
  1289. :param bbox: the bounding box where run the analysis
  1290. :type bbox: a Bbox object
  1291. """
  1292. bbox = bbox if bbox else self.bbox()
  1293. return bool(libvect.Vect_point_in_area(pnt.x, pnt.y,
  1294. self.c_mapinfo, self.id,
  1295. bbox.c_bbox))
  1296. def perimeter(self):
  1297. """Calculate area perimeter.
  1298. :return: double Vect_area_perimeter (const struct line_pnts \*Points)
  1299. """
  1300. border = self.get_points()
  1301. return libvect.Vect_line_geodesic_length(border.c_points)
  1302. def read(self, line=None, centroid=None, isles=None):
  1303. self.boundary = self.get_points(line)
  1304. self.centroid = self.get_centroid(centroid)
  1305. #self.isles = self.get_isles(isles)
  1306. if self.centroid:
  1307. libvect.Vect_read_line(self.c_mapinfo, None, self.c_cats,
  1308. self.centroid.id)
  1309. #
  1310. # Define a dictionary to convert the feature type to name and or object
  1311. #
  1312. GV_TYPE = {libvect.GV_POINT: {'label': 'point', 'obj': Point},
  1313. libvect.GV_LINE: {'label': 'line', 'obj': Line},
  1314. libvect.GV_BOUNDARY: {'label': 'boundary', 'obj': Boundary},
  1315. libvect.GV_CENTROID: {'label': 'centroid', 'obj': Centroid},
  1316. libvect.GV_FACE: {'label': 'face', 'obj': None},
  1317. libvect.GV_KERNEL: {'label': 'kernel', 'obj': None},
  1318. libvect.GV_AREA: {'label': 'area', 'obj': Area},
  1319. libvect.GV_VOLUME: {'label': 'volume', 'obj': None}, }
  1320. GEOOBJ = {"areas": Area,
  1321. "dblinks": None,
  1322. "faces": None,
  1323. "holes": None,
  1324. "islands": Isle,
  1325. "kernels": None,
  1326. "line_points": None,
  1327. "points": Point,
  1328. "lines": Line,
  1329. "nodes": Node,
  1330. "volumes": None}
  1331. def c_read_next_line(c_mapinfo, c_points, c_cats):
  1332. v_id = c_mapinfo.contents.next_line
  1333. v_id = v_id if v_id != 0 else None
  1334. ftype = libvect.Vect_read_next_line(c_mapinfo, c_points, c_cats)
  1335. if ftype == -2:
  1336. raise StopIteration()
  1337. if ftype == -1:
  1338. raise
  1339. return ftype, v_id, c_points, c_cats
  1340. def read_next_line(c_mapinfo, table=None, writable=False,
  1341. c_points=None, c_cats=None, is2D=True):
  1342. """Return the next geometry feature of a vector map."""
  1343. c_points = c_points if c_points else ctypes.pointer(libvect.line_pnts())
  1344. c_cats = c_cats if c_cats else ctypes.pointer(libvect.line_cats())
  1345. ftype, v_id, c_points, c_cats = c_read_next_line(c_mapinfo, c_points,
  1346. c_cats)
  1347. return GV_TYPE[ftype]['obj'](v_id=v_id, c_mapinfo=c_mapinfo,
  1348. c_points=c_points, c_cats=c_cats,
  1349. table=table, writable=writable, is2D=is2D)
  1350. def c_read_line(feature_id, c_mapinfo, c_points, c_cats):
  1351. nmax = libvect.Vect_get_num_lines(c_mapinfo)
  1352. if feature_id < 0: # Handle negative indices
  1353. feature_id += nmax + 1
  1354. if feature_id > nmax:
  1355. raise IndexError('Index out of range')
  1356. if feature_id > 0:
  1357. ftype = libvect.Vect_read_line(c_mapinfo, c_points, c_cats, feature_id)
  1358. return feature_id, ftype, c_points, c_cats
  1359. else:
  1360. raise ValueError('The index must be >0, %r given.' % feature_id)
  1361. def read_line(feature_id, c_mapinfo, table=None, writable=False,
  1362. c_points=None, c_cats=None, is2D=True):
  1363. """Return a geometry object given the feature id and the c_mapinfo.
  1364. """
  1365. c_points = c_points if c_points else ctypes.pointer(libvect.line_pnts())
  1366. c_cats = c_cats if c_cats else ctypes.pointer(libvect.line_cats())
  1367. feature_id, ftype, c_points, c_cats = c_read_line(feature_id, c_mapinfo,
  1368. c_points, c_cats)
  1369. if GV_TYPE[ftype]['obj'] is not None:
  1370. return GV_TYPE[ftype]['obj'](v_id=feature_id, c_mapinfo=c_mapinfo,
  1371. c_points=c_points, c_cats=c_cats,
  1372. table=table, writable=writable, is2D=is2D)