geometry.py 62 KB

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