geometry.py 59 KB

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