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