geometry.py 39 KB

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