geometry.py 45 KB

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