geometry.py 64 KB

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