geometry.py 44 KB

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