geometry.py 49 KB

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