geometry.py 63 KB

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