geometry.py 63 KB

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