geometry.py 39 KB

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