geometry.py 36 KB

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