geometry.py 39 KB

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