geometry.py 44 KB

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