geometry.py 52 KB

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