geometry.py 48 KB

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