pygrass.vector package¶
Submodules¶
pygrass.vector.abstract module¶
Created on Fri Aug 17 17:24:03 2012
@author: pietro
- class pygrass.vector.abstract.Info(name, mapset='', *aopen, **kwopen)[source]¶
Bases:
object
Basic vector info. To get access to the vector info the map must be opened.
>>> test_vect = Info(test_vector_name) >>> test_vect.open(mode='r')
Then it is possible to read and write the following map attributes:
>>> test_vect.organization 'Thuenen Institut' >>> test_vect.person 'Soeren Gebbert' >>> test_vect.title 'Test dataset' >>> test_vect.scale 1 >>> test_vect.comment 'This is a comment' >>> test_vect.comment = "One useful comment!" >>> test_vect.comment 'One useful comment!'
There are some read only attributes:
>>> test_vect.maptype 'native'
And some basic methods:
>>> test_vect.is_3D() False >>> test_vect.exist() True >>> test_vect.is_open() True >>> test_vect.close()
- close(build=False)[source]¶
Method to close the Vector
- Parameters:
build (bool) – True if the vector map should be build before close it
- property comment¶
Set or obtain the Vector comment
- property date¶
Set or obtain the Vector date
- property full_name¶
Return the full name of Vector
- property map_date¶
Set or obtain the Vector map date
- property mapset¶
Set or obtain the Vector mapset
- property maptype¶
Return the map type of Vector
- property mode¶
- property name¶
Set or obtain the Vector name
- open(mode=None, layer=1, overwrite=None, with_z=None, tab_name='', tab_cols=None, link_name=None, link_key='cat', link_db='$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db', link_driver='sqlite')[source]¶
Open a Vector map.
- Parameters:
mode (str) – open a vector map in
r
in reading,w
in writing and inrw
read and write modelayer (int) – specify the layer that you want to use
overwrite (bool) – valid only for
w
modewith_z (bool) – specify if vector map must be open with third dimension enabled or not. Valid only for
w
mode, default: Falsetab_name (str) – define the name of the table that will be generate
tab_cols (list of pairs) – define the name and type of the columns of the attribute table of the vector map
link_name (str) – define the name of the link connection with the database
link_key (str) – define the name of the column that will be used as vector category
link_db (str) – define the database connection parameters
link_driver – define witch database driver will be used
link_driver – str
Some of the parameters are valid only with mode
w
orrw
See more examples in the documentation of the
read
andwrite
methods
- property organization¶
Set or obtain the Vector organization
- property person¶
Set or obtain the Vector author
- property proj¶
Set or obtain the Vector projection code
- property proj_name¶
Return the project name of Vector
- rename(newname)[source]¶
Method to rename the Vector map
- Parameters:
newname (str) – the new name for the Vector map
- property scale¶
Set or obtain the Vector scale
- property thresh¶
Set or obtain the Vector threshold
- property title¶
Set or obtain the Vector title
- property zone¶
Set or obtain the Vector projection zone
pygrass.vector.basic module¶
Created on Tue Jul 31 13:06:20 2012
@author: pietro
- class pygrass.vector.basic.Bbox(north=0, south=0, east=0, west=0, top=0, bottom=0)[source]¶
Bases:
object
Instantiate a Bounding Box class that contains a ctypes pointer to the C struct bound_box, that could be used by C GRASS functions.
>>> bbox = Bbox() >>> bbox Bbox(0.0, 0.0, 0.0, 0.0)
The default parameters are 0. It is possible to set or change the parameters later, with:
>>> bbox.north = 10 >>> bbox.south = -10 >>> bbox.east = -20 >>> bbox.west = 20 >>> bbox Bbox(10.0, -10.0, -20.0, 20.0)
Or directly istantiate the class with the values, with:
>>> bbox = Bbox(north=100, south=0, east=0, west=100) >>> bbox Bbox(100.0, 0.0, 0.0, 100.0)
- property bottom¶
Set and obtain bottom value
- contains(point)[source]¶
Return True if the object is contained by the BoundingBox
- Parameters:
point (a Point object or a tuple with the coordinates) – the point to analyze
>>> from grass.pygrass.vector.geometry import Point >>> poi = Point(5, 5) >>> bbox = Bbox(north=10, south=0, west=0, east=10) >>> bbox.contains(poi) True
- property east¶
Set and obtain east value
- property north¶
Set and obtain north value
- nsewtb(tb=True)[source]¶
Return a list of values from bounding box
- Parameters:
tb (bool) – if tb parameter is False return only: north, south, east, west and not top and bottom
- property south¶
Set and obtain south value
- property top¶
Set and obtain top value
- property west¶
Set and obtain west value
- class pygrass.vector.basic.BoxList(boxlist=None)[source]¶
Bases:
object
Instantiate a BoxList class to create a list of Bounding Box
- append(box)[source]¶
Append a Bbox object to a Boxlist object, using the
Vect_boxlist_append
C function.- Parameters:
box (a Bbox object) – the bounding box to add to the list
>>> box0 = Bbox() >>> box1 = Bbox(1, 2, 3, 4) >>> box2 = Bbox(5, 6, 7, 8) >>> boxlist = BoxList([box0, box1]) >>> boxlist Boxlist([Bbox(0.0, 0.0, 0.0, 0.0), Bbox(1.0, 2.0, 3.0, 4.0)]) >>> len(boxlist) 2 >>> boxlist.append(box2) >>> len(boxlist) 3
- property ids¶
- property n_values¶
- remove(indx)[source]¶
Remove Bbox from the boxlist, given an integer or a list of integer or a boxlist, using
Vect_boxlist_delete
C function or theVect_boxlist_delete_boxlist
.- Parameters:
indx – the index value of the Bbox to remove
indx – int
>>> boxlist = BoxList([Bbox(), Bbox(1, 0, 0, 1), Bbox(1, -1, -1, 1)]) >>> boxlist.remove(0) >>> boxlist Boxlist([Bbox(1.0, 0.0, 0.0, 1.0), Bbox(1.0, -1.0, -1.0, 1.0)])
- class pygrass.vector.basic.Cats(c_cats=None)[source]¶
Bases:
object
Instantiate a Category class that contains a ctypes pointer to the C line_cats struct.
>>> cats = Cats() >>> for cat in range(100, 110): ... cats.set(cat, layer=cat - 50) >>> cats.n_cats 10 >>> cats.cat [100, 101, 102, 103, 104, 105, 106, 107, 108, 109] >>> cats.layer [50, 51, 52, 53, 54, 55, 56, 57, 58, 59] >>> cats.get() # default layer is 1 (-1, 0) >>> cats.get(50) (100, 1) >>> cats.get(51) (101, 1) >>> cats.set(1001, 52) >>> cats.cat [100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 1001] >>> cats.layer [50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 52] >>> cats.get(52) (102, 2) >>> cats.reset() >>> cats.layer [] >>> cats.cat []
- property cat¶
- check_cats_constraints(cats_list, layer=1)[source]¶
Check if categories match with category constraints
- delete(cat=None, layer=1)[source]¶
If cat is given delete cat from line_cats structure (using Vect_field_cat_del) else delete all categories of given layer (using Vect_cat_del).
- get(layer=1)[source]¶
Return the first found category of given layer and the number of category found.
- Parameters:
layer (int) – the number of layer
- get_list(layer=1)[source]¶
Get list of categories of given field.
- Parameters:
layer (int) – the number of layer
- property layer¶
- property n_cats¶
Return the number of categories
- class pygrass.vector.basic.CatsList(c_cat_list=None)[source]¶
Bases:
object
>>> cats_list = CatsList() >>> cats_list.min [] >>> cats_list.max [] >>> cats_list.n_ranges 0 >>> cats_list.layer 0 >>> string = "2,3,5-9,20" >>> cats_list.from_string(string) >>> cats_list.min [2, 3, 5, 20] >>> cats_list.max [2, 3, 9, 20] >>> cats_list.n_ranges 4
- from_array(array)[source]¶
Convert ordered array of integers to cat_list structure.
- Parameters:
array (array) – the input array containing the cats
- from_string(string)[source]¶
Converts string of categories and cat ranges separated by commas to cat_list.
- Parameters:
string (str) – a string containing the cats separated by commas
- property layer¶
Return the layer number
- property max¶
Return the maximum value
- property min¶
Return the minimum value
- property n_ranges¶
Return the ranges number
- class pygrass.vector.basic.Ilist(integer_list=None)[source]¶
Bases:
object
Instantiate a list of integer using the C GRASS struct
ilist
, the class contains this struct asc_ilist
attribute.
pygrass.vector.find module¶
Created on Tue Mar 19 11:09:30 2013
@author: pietro
- class pygrass.vector.find.AbstractFinder(c_mapinfo, table: Table | None = None, writeable: bool = False)[source]¶
Bases:
object
Find geometry feature(s) around a point or that are inside or intersect with a bounding box.
- Parameters:
c_mapinfo (ctypes pointer to mapinfo structure) – Pointer to the vector layer mapinfo structure
table (Table) – Attribute table of the vector layer
writeable – True or False
- class pygrass.vector.find.BboxFinder(c_mapinfo, table: Table | None = None, writeable: bool = False)[source]¶
Bases:
AbstractFinder
Bounding Box finder
This class provides an interface to search geometry features of a vector map that are inside or intersect a boundingbox. The BboxFinder class is part of a topological vector map object.
Find geometry feature(s) around a point or that are inside or intersect with a bounding box.
- Parameters:
c_mapinfo (ctypes pointer to mapinfo structure) – Pointer to the vector layer mapinfo structure
table (Table) – Attribute table of the vector layer
writeable – True or False
- areas(bbox, boxlist=None, bboxlist_only=False)[source]¶
Find areas inside a boundingbox.
- Parameters:
bbox (grass.pygrass.vector.basic.Bbox) – The boundingbox to search in
boxlist – An existing BoxList to be filled with
bboxlist_only (boolean) – If true the BoxList will be returned, no features are generated
- Type_boxlist:
grass.pygrass.vector.basic.BoxList
- Returns:
A list of areas or None if nothing was found
This methods uses libvect.Vect_select_areas_by_box()
Examples:
>>> from grass.pygrass.vector import VectorTopo >>> from grass.pygrass.vector.basic import Bbox >>> test_vect = VectorTopo(test_vector_name) >>> test_vect.open("r") # Find areas in box >>> bbox = Bbox(north=5, south=-1, east=9, west=-1) >>> result = test_vect.find_by_bbox.areas(bbox=bbox) >>> [area for area in result] [Area(1), Area(2), Area(3), Area(4)] >>> bbox = Bbox(north=5, south=-1, east=9, west=-1) >>> result = test_vect.find_by_bbox.areas(bbox=bbox, bboxlist_only=True) >>> result Boxlist([Bbox(4.0, 0.0, 4.0, 0.0), Bbox(4.0, 0.0, 6.0, 4.0), Bbox(3.0, 1.0, 3.0, 1.0), Bbox(4.0, 0.0, 8.0, 6.0)]) >>> bbox = Bbox(north=20, south=18, east=20, west=18) >>> test_vect.find_by_bbox.areas(bbox=bbox) >>> test_vect.find_by_bbox.areas(bbox=bbox, bboxlist_only=True) >>> test_vect.close()
- geos(bbox, type='all', bboxlist_only=False)[source]¶
Find vector features inside a boundingbox.
- Parameters:
bbox (grass.pygrass.vector.basic.Bbox) – The boundingbox to search in
type (string) – The type of feature to search for Valid type are all the keys in find.vtype dictionary
bboxlist_only (boolean) – If true the BoxList will be returned, no features are generated
- Returns:
A list of grass.pygrass.vector.geometry (Line, Point, Boundary, Centroid) if found, or None if nothing was found. If bboxlist_only is True a BoxList object will be returned, or None if nothing was found.
This methods uses
libvect.Vect_select_lines_by_box()
Examples:
>>> from grass.pygrass.vector import VectorTopo >>> from grass.pygrass.vector.basic import Bbox >>> test_vect = VectorTopo(test_vector_name) >>> test_vect.open("r") >>> bbox = Bbox(north=5, south=-1, east=3, west=-1) >>> result = test_vect.find_by_bbox.geos(bbox=bbox) >>> [bbox for bbox in result] [Boundary([Point(4.000000, 0.000000), Point(0.000000, 0.000000)]), Boundary([Point(0.000000, 0.000000), Point(0.000000, 4.000000)]), Boundary([Point(0.000000, 4.000000), Point(4.000000, 4.000000)]), Boundary([Point(1.000000, 1.000000), Point(1.000000, 3.000000), Point(3.000000, 3.000000), Point(3.000000, 1.000000), Point(1.000000, 1.000000)]), Centroid(2.500000, 2.500000)] >>> bbox = Bbox(north=5, south=-1, east=3, west=-1) >>> result = test_vect.find_by_bbox.geos(bbox=bbox, bboxlist_only=True) >>> result Boxlist([Bbox(0.0, 0.0, 4.0, 0.0), Bbox(4.0, 0.0, 0.0, 0.0), Bbox(4.0, 4.0, 4.0, 0.0), Bbox(3.0, 1.0, 3.0, 1.0), Bbox(2.5, 2.5, 2.5, 2.5)]) >>> bbox = Bbox(north=7, south=-1, east=15, west=9) >>> result = test_vect.find_by_bbox.geos(bbox=bbox) >>> [bbox for bbox in result] [Line([Point(10.000000, 4.000000), Point(10.000000, 2.000000), Point(10.000000, 0.000000)]), Point(10.000000, 6.000000), Line([Point(12.000000, 4.000000), Point(12.000000, 2.000000), Point(12.000000, 0.000000)]), Point(12.000000, 6.000000), Line([Point(14.000000, 4.000000), Point(14.000000, 2.000000), Point(14.000000, 0.000000)]), Point(14.000000, 6.000000)] >>> bbox = Bbox(north=20, south=18, east=20, west=18) >>> test_vect.find_by_bbox.geos(bbox=bbox) >>> bbox = Bbox(north=20, south=18, east=20, west=18) >>> test_vect.find_by_bbox.geos(bbox=bbox, bboxlist_only=True) >>> test_vect.close()
- islands(bbox, bboxlist_only=False)[source]¶
Find isles inside a boundingbox.
- Parameters:
bbox (grass.pygrass.vector.basic.Bbox) – The boundingbox to search in
bboxlist_only (boolean) – If true the BoxList will be returned, no features are generated
- Returns:
A list of isles or None if nothing was found
This methods uses libvect.Vect_select_isles_by_box()
Examples:
>>> from grass.pygrass.vector import VectorTopo >>> from grass.pygrass.vector.basic import Bbox >>> test_vect = VectorTopo(test_vector_name) >>> test_vect.open("r") # Find isles in box >>> bbox = Bbox(north=5, south=-1, east=9, west=-1) >>> result = test_vect.find_by_bbox.islands(bbox=bbox) >>> [isle for isle in result] [Isle(1), Isle(2)] >>> bbox = Bbox(north=5, south=-1, east=9, west=-1) >>> result = test_vect.find_by_bbox.islands(bbox=bbox, bboxlist_only=True) >>> result Boxlist([Bbox(4.0, 0.0, 8.0, 0.0), Bbox(3.0, 1.0, 3.0, 1.0)]) >>> bbox = Bbox(north=20, south=18, east=20, west=18) >>> test_vect.find_by_bbox.islands(bbox=bbox) >>> test_vect.find_by_bbox.islands(bbox=bbox, bboxlist_only=True) >>> test_vect.close()
- nodes(bbox)[source]¶
Find nodes inside a boundingbox.
- Parameters:
bbox (grass.pygrass.vector.basic.Bbox) – The boundingbox to search in
- Returns:
A list of nodes or None if nothing was found
This methods uses libvect.Vect_select_nodes_by_box()
Examples:
>>> from grass.pygrass.vector import VectorTopo >>> from grass.pygrass.vector.basic import Bbox >>> test_vect = VectorTopo(test_vector_name) >>> test_vect.open("r") # Find nodes in box >>> bbox = Bbox(north=5, south=-1, east=15, west=9) >>> result = test_vect.find_by_bbox.nodes(bbox=bbox) >>> [node for node in result] [Node(2), Node(1), Node(4), Node(3), Node(5), Node(6)] >>> bbox = Bbox(north=20, south=18, east=20, west=18) >>> test_vect.find_by_bbox.nodes(bbox=bbox) >>> test_vect.close()
- class pygrass.vector.find.PointFinder(c_mapinfo, table: Table | None = None, writeable: bool = False)[source]¶
Bases:
AbstractFinder
Point finder
This class provides an interface to search geometry features of a vector map that are close to a point. The PointFinder class is part of a topological vector map object.
Find geometry feature(s) around a point or that are inside or intersect with a bounding box.
- Parameters:
c_mapinfo (ctypes pointer to mapinfo structure) – Pointer to the vector layer mapinfo structure
table (Table) – Attribute table of the vector layer
writeable – True or False
- area(point)[source]¶
Find the nearest area around a specific point.
- Parameters:
point (grass.pygrass.vector.geometry.Point) – The point to search
- Returns:
A grass.pygrass.vector.geometry.Area if found or None
This methods uses libvect.Vect_find_area()
Examples:
>>> from grass.pygrass.vector import VectorTopo >>> from grass.pygrass.vector.geometry import Point >>> test_vect = VectorTopo(test_vector_name) >>> test_vect.open("r") # Find AREAS >>> points = (Point(0.5, 0.5), Point(5, 1), Point(7, 1)) >>> result = [] >>> for point in points: ... area = test_vect.find_by_point.area(point) ... result.append(area) >>> result [Area(1), Area(2), Area(4)] >>> for area in result: ... print(area.to_wkt()) POLYGON ((0.0000000000000000 0.0000000000000000, 0.0000000000000000 4.0000000000000000, 0.0000000000000000 4.0000000000000000, 4.0000000000000000 4.0000000000000000, 4.0000000000000000 4.0000000000000000, 4.0000000000000000 0.0000000000000000, 4.0000000000000000 0.0000000000000000, 0.0000000000000000 0.0000000000000000), (1.0000000000000000 1.0000000000000000, 3.0000000000000000 1.0000000000000000, 3.0000000000000000 3.0000000000000000, 1.0000000000000000 3.0000000000000000, 1.0000000000000000 1.0000000000000000)) POLYGON ((4.0000000000000000 0.0000000000000000, 4.0000000000000000 4.0000000000000000, 4.0000000000000000 4.0000000000000000, 6.0000000000000000 4.0000000000000000, 6.0000000000000000 4.0000000000000000, 6.0000000000000000 0.0000000000000000, 6.0000000000000000 0.0000000000000000, 4.0000000000000000 0.0000000000000000)) POLYGON ((6.0000000000000000 0.0000000000000000, 6.0000000000000000 4.0000000000000000, 6.0000000000000000 4.0000000000000000, 8.0000000000000000 4.0000000000000000, 8.0000000000000000 4.0000000000000000, 8.0000000000000000 0.0000000000000000, 8.0000000000000000 0.0000000000000000, 6.0000000000000000 0.0000000000000000)) >>> test_vect.find_by_point.area(Point(20, 20)) >>> test_vect.close()
- geo(point, maxdist, type='all', exclude=0)[source]¶
Find the nearest vector feature around a specific point.
- Parameters:
point (grass.pygrass.vector.geometry.Point) – The point to search
maxdist (float) – The maximum search distance around the point
type (string) – The type of feature to search for Valid type are all the keys in find.vtype dictionary
exclude – if > 0 number of lines which should be excluded from selection
- Returns:
A grass.pygrass.vector.geometry.Node if found or None
This methods uses libvect.Vect_find_line()()
Examples:
>>> from grass.pygrass.vector import VectorTopo >>> from grass.pygrass.vector.geometry import Point >>> test_vect = VectorTopo(test_vector_name) >>> test_vect.open("r") # Find single features >>> points = (Point(10, 0), Point(10, 6), Point(14, 2)) >>> result = [] >>> for point in points: ... f = test_vect.find_by_point.geo(point=point, maxdist=1) ... if f: ... result.append(f) >>> for f in result: ... print(f.to_wkt_p()) LINESTRING(10.000000 4.000000, 10.000000 2.000000, 10.000000 0.000000) POINT(10.000000 6.000000) LINESTRING(14.000000 4.000000, 14.000000 2.000000, 14.000000 0.000000) >>> test_vect.find_by_point.geo(point=Point(20, 20), maxdist=0) >>> test_vect.close()
- geos(point, maxdist, type='all', exclude=None)[source]¶
Find the nearest vector features around a specific point.
- Parameters:
point (grass.pygrass.vector.geometry.Point) – The point to search
maxdist (float) – The maximum search distance around the point
type (string) – The type of feature to search for Valid type are all the keys in find.vtype dictionary
exclude – if > 0 number of lines which should be excluded from selection
- Returns:
A list of grass.pygrass.vector.geometry (Line, Point, Boundary, Centroid) if found or None
This methods uses libvect.Vect_find_line_list()()
Examples:
>>> from grass.pygrass.vector import VectorTopo >>> from grass.pygrass.vector.geometry import Point >>> test_vect = VectorTopo(test_vector_name) >>> test_vect.open("r") # Find multiple features >>> points = (Point(10, 0), Point(10, 5), Point(14, 2)) >>> result = [] >>> for point in points: ... f = test_vect.find_by_point.geos(point=point, maxdist=1.5) ... if f: ... result.append(f) >>> for f in result: ... print(f) [Line([Point(10.000000, 4.000000), Point(10.000000, 2.000000), Point(10.000000, 0.000000)])] [Line([Point(10.000000, 4.000000), Point(10.000000, 2.000000), Point(10.000000, 0.000000)]), Point(10.000000, 6.000000)] [Line([Point(14.000000, 4.000000), Point(14.000000, 2.000000), Point(14.000000, 0.000000)])] # Find multiple boundaries >>> point = Point(3, 3) >>> result = test_vect.find_by_point.geos( ... point=Point(3, 3), type="boundary", maxdist=1.5 ... ) >>> result [Boundary([Point(0.000000, 4.000000), Point(4.000000, 4.000000)]), Boundary([Point(4.000000, 4.000000), Point(4.000000, 0.000000)]), Boundary([Point(1.000000, 1.000000), Point(1.000000, 3.000000), Point(3.000000, 3.000000), Point(3.000000, 1.000000), Point(1.000000, 1.000000)]), Boundary([Point(4.000000, 4.000000), Point(6.000000, 4.000000)])] # Find multiple centroids >>> point = Point(3, 3) >>> result = test_vect.find_by_point.geos( ... point=Point(3, 3), type="centroid", maxdist=1.5 ... ) >>> result [Centroid(2.500000, 2.500000), Centroid(3.500000, 3.500000)] >>> test_vect.find_by_point.geos(point=Point(20, 20), maxdist=0) >>> test_vect.close()
- island(point)[source]¶
Find the nearest island around a specific point.
- Parameters:
point (grass.pygrass.vector.geometry.Point) – The point to search
- Returns:
A grass.pygrass.vector.geometry.Isle if found or None
This methods uses Vect_find_island.Vect_find_area()
Examples:
>>> from grass.pygrass.vector import VectorTopo >>> from grass.pygrass.vector.geometry import Point >>> test_vect = VectorTopo(test_vector_name) >>> test_vect.open("r") # Find ISLANDS >>> points = (Point(2, 2), Point(5, 1)) >>> result = [] >>> for point in points: ... area = test_vect.find_by_point.island(point) ... result.append(area) >>> result [Isle(2), Isle(1)] >>> for isle in result: ... print(isle.to_wkt()) Polygon((1.000000 1.000000, 3.000000 1.000000, 3.000000 3.000000, 1.000000 3.000000, 1.000000 1.000000)) Polygon((0.000000 4.000000, 0.000000 0.000000, 4.000000 0.000000, 6.000000 0.000000, 8.000000 0.000000, 8.000000 4.000000, 6.000000 4.000000, 4.000000 4.000000, 0.000000 4.000000)) >>> test_vect.find_by_point.island(Point(20, 20)) >>> test_vect.close()
- node(point, maxdist)[source]¶
Find the nearest node around a specific point.
- Parameters:
point (grass.pygrass.vector.geometry.Point) – The point to search
maxdist (float) – The maximum search distance around the point
- Returns:
A grass.pygrass.vector.geometry.Node if found or None
This methods uses libvect.Vect_find_node()()
Examples:
>>> from grass.pygrass.vector import VectorTopo >>> from grass.pygrass.vector.geometry import Point >>> test_vect = VectorTopo(test_vector_name) >>> test_vect.open("r") # Find nearest node >>> points = (Point(10, 0), Point(10, 4), Point(14, 0)) >>> result = [] >>> for point in points: ... f = test_vect.find_by_point.node(point=point, maxdist=1) ... if f: ... result.append(f) >>> result [Node(2), Node(1), Node(6)] >>> test_vect.find_by_point.node(point=Point(20, 20), maxdist=0) >>> test_vect.close()
- class pygrass.vector.find.PolygonFinder(c_mapinfo, table: Table | None = None, writeable: bool = False)[source]¶
Bases:
AbstractFinder
Find geometry feature(s) around a point or that are inside or intersect with a bounding box.
- Parameters:
c_mapinfo (ctypes pointer to mapinfo structure) – Pointer to the vector layer mapinfo structure
table (Table) – Attribute table of the vector layer
writeable – True or False
pygrass.vector.geometry module¶
Created on Wed Jul 18 10:46:25 2012
@author: pietro
- class pygrass.vector.geometry.Area(**kargs)[source]¶
Bases:
Geo
Vect_build_line_area, Vect_find_area, Vect_get_area_box, Vect_get_area_points_geos, Vect_centroid_area,
Vect_get_isle_area, Vect_get_line_areas, Vect_get_num_areas, Vect_get_point_in_area, Vect_isle_find_area, Vect_point_in_area, Vect_point_in_area_outer_ring,
Vect_read_area_geos, Vect_remove_small_areas, Vect_select_areas_by_box, Vect_select_areas_by_polygon
Constructor of a geometry object
- Parameters:
v_id – The vector feature id
c_mapinfo – A pointer to the vector mapinfo structure
c_points – A pointer to a libvect.line_pnts structure, this is optional, if not set an internal structure will be allocated and free’d at object destruction
c_cats – A pointer to a libvect.line_cats structure, this is optional, if not set an internal structure will be allocated and free’d at object destruction
table – The attribute table to select attributes for this feature
writeable – Not sure what this is for?
is2D – If True this feature has two dimensions, False if this feature has three dimensions
free_points – Set this True if the provided c_points structure should be free’d at object destruction, be aware that no other object should free them, otherwise you can expect a double free corruption segfault
free_cats – Set this True if the provided c_cats structure should be free’d at object destruction, be aware that no other object should free them, otherwise you can expect a double free corruption segfault
- area()[source]¶
Returns area of area without areas of isles. double Vect_get_area_area (const struct Map_info *Map, int area)
- bbox(bbox=None)[source]¶
Return the Bbox of area
- Parameters:
bbox (a Bbox object) – a Bbox object to fill with info from bounding box of area
- boundaries(ilist=False)[source]¶
Creates list of boundaries for given area.
- int Vect_get_area_boundaries(const struct Map_info *Map,
int area, struct ilist *List)
- buffer(dist=None, dist_x=None, dist_y=None, angle=0, round_=True, caps=True, tol=0.1)[source]¶
Return the buffer area around the area, using the
Vect_area_buffer2
C function.- Parameters:
- Returns:
the buffer as line, centroid, isles object tuple
- property cat¶
- cats(cats=None)[source]¶
Get area categories.
- Parameters:
cats (a Cats object) – a Cats object to fill with info with area categories
- centroid()[source]¶
Return the centroid
- Parameters:
centroid (a Centroid object) – a Centroid object to fill with info from centroid of area
- contains_point(point, bbox=None)[source]¶
Check if point is in area.
- Parameters:
point (a Point object or a tuple with the coordinates) – the point to analyze
bbox (a Bbox object) – the bounding box where run the analysis
- get_first_cat()[source]¶
Find FIRST category of given field and area.
int Vect_get_area_cat(const struct Map_info *Map, int area, int field)
Warning
Not implemented
- gtype = 64¶
- perimeter()[source]¶
Calculate area perimeter.
- Returns:
double Vect_area_perimeter (const struct line_pnts *Points)
- points(line=None)[source]¶
Return a Line object with the outer ring
- Parameters:
line (a Line object) – a Line object to fill with info from points of area
- read()[source]¶
Read and set the coordinates of the centroid from the vector map, using the centroid_id and calling the
Vect_read_line
C function
- class pygrass.vector.geometry.Attrs(cat, table, writeable=False)[source]¶
Bases:
object
- property cat¶
Set and obtain cat value
- class pygrass.vector.geometry.Boundary(**kargs)[source]¶
Bases:
Line
Constructor of a geometry object
- Parameters:
v_id – The vector feature id
c_mapinfo – A pointer to the vector mapinfo structure
c_points – A pointer to a libvect.line_pnts structure, this is optional, if not set an internal structure will be allocated and free’d at object destruction
c_cats – A pointer to a libvect.line_cats structure, this is optional, if not set an internal structure will be allocated and free’d at object destruction
table – The attribute table to select attributes for this feature
writeable – Not sure what this is for?
is2D – If True this feature has two dimensions, False if this feature has three dimensions
free_points – Set this True if the provided c_points structure should be free’d at object destruction, be aware that no other object should free them, otherwise you can expect a double free corruption segfault
free_cats – Set this True if the provided c_cats structure should be free’d at object destruction, be aware that no other object should free them, otherwise you can expect a double free corruption segfault
- area()[source]¶
Return the area of the polygon.
>>> bound = Boundary(points=[(0, 0), (0, 2), (2, 2), (2, 0), (0, 0)]) >>> bound.area() 4.0
- gtype = 4¶
- property left_area_id¶
Left side area id, only available after read_area_ids() was called
- left_centroid(idonly=False)[source]¶
Return left centroid
- Parameters:
idonly (bool) – True to return only the cat of feature
- property right_area_id¶
Right side area id, only available after read_area_ids() was called
- class pygrass.vector.geometry.Centroid(area_id=None, **kargs)[source]¶
Bases:
Point
The Centroid class inherit from the Point class. Centroid contains an attribute with the C Map_info struct, and attributes with the id of the Area.
>>> centroid = Centroid(x=0, y=10) >>> centroid Centroid(0.000000, 10.000000) >>> from grass.pygrass.vector import VectorTopo >>> test_vect = VectorTopo(test_vector_name) >>> test_vect.open(mode="r") >>> centroid = Centroid(v_id=18, c_mapinfo=test_vect.c_mapinfo) >>> centroid Centroid(3.500000, 3.500000) >>> test_vect.close()
Constructor of a geometry object
- Parameters:
v_id – The vector feature id
c_mapinfo – A pointer to the vector mapinfo structure
c_points – A pointer to a libvect.line_pnts structure, this is optional, if not set an internal structure will be allocated and free’d at object destruction
c_cats – A pointer to a libvect.line_cats structure, this is optional, if not set an internal structure will be allocated and free’d at object destruction
table – The attribute table to select attributes for this feature
writeable – Not sure what this is for?
is2D – If True this feature has two dimensions, False if this feature has three dimensions
free_points – Set this True if the provided c_points structure should be free’d at object destruction, be aware that no other object should free them, otherwise you can expect a double free corruption segfault
free_cats – Set this True if the provided c_cats structure should be free’d at object destruction, be aware that no other object should free them, otherwise you can expect a double free corruption segfault
- gtype = 8¶
- class pygrass.vector.geometry.Geo(v_id=0, c_mapinfo=None, c_points=None, c_cats=None, table=None, writeable=False, is2D=True, free_points=False, free_cats=False)[source]¶
Bases:
object
Base object for different feature types
Constructor of a geometry object
- Parameters:
v_id – The vector feature id
c_mapinfo – A pointer to the vector mapinfo structure
c_points – A pointer to a libvect.line_pnts structure, this is optional, if not set an internal structure will be allocated and free’d at object destruction
c_cats – A pointer to a libvect.line_cats structure, this is optional, if not set an internal structure will be allocated and free’d at object destruction
table – The attribute table to select attributes for this feature
writeable – Not sure what this is for?
is2D – If True this feature has two dimensions, False if this feature has three dimensions
free_points – Set this True if the provided c_points structure should be free’d at object destruction, be aware that no other object should free them, otherwise you can expect a double free corruption segfault
free_cats – Set this True if the provided c_cats structure should be free’d at object destruction, be aware that no other object should free them, otherwise you can expect a double free corruption segfault
- property cat¶
- gtype = None¶
- read()[source]¶
Read and set the coordinates of the centroid from the vector map, using the centroid_id and calling the
Vect_read_line
C function
- class pygrass.vector.geometry.Isle(**kargs)[source]¶
Bases:
Geo
An Isle is an area contained by another area.
Constructor of a geometry object
- Parameters:
v_id – The vector feature id
c_mapinfo – A pointer to the vector mapinfo structure
c_points – A pointer to a libvect.line_pnts structure, this is optional, if not set an internal structure will be allocated and free’d at object destruction
c_cats – A pointer to a libvect.line_cats structure, this is optional, if not set an internal structure will be allocated and free’d at object destruction
table – The attribute table to select attributes for this feature
writeable – Not sure what this is for?
is2D – If True this feature has two dimensions, False if this feature has three dimensions
free_points – Set this True if the provided c_points structure should be free’d at object destruction, be aware that no other object should free them, otherwise you can expect a double free corruption segfault
free_cats – Set this True if the provided c_cats structure should be free’d at object destruction, be aware that no other object should free them, otherwise you can expect a double free corruption segfault
- class pygrass.vector.geometry.Line(points=None, **kargs)[source]¶
Bases:
Geo
Instantiate a new Line with a list of tuple, or with a list of Point.
>>> line = Line([(0, 0), (1, 1), (2, 0), (1, -1)]) >>> line Line([Point(0.000000, 0.000000), Point(1.000000, 1.000000), Point(2.000000, 0.000000), Point(1.000000, -1.000000)])
Constructor of a geometry object
- Parameters:
v_id – The vector feature id
c_mapinfo – A pointer to the vector mapinfo structure
c_points – A pointer to a libvect.line_pnts structure, this is optional, if not set an internal structure will be allocated and free’d at object destruction
c_cats – A pointer to a libvect.line_cats structure, this is optional, if not set an internal structure will be allocated and free’d at object destruction
table – The attribute table to select attributes for this feature
writeable – Not sure what this is for?
is2D – If True this feature has two dimensions, False if this feature has three dimensions
free_points – Set this True if the provided c_points structure should be free’d at object destruction, be aware that no other object should free them, otherwise you can expect a double free corruption segfault
free_cats – Set this True if the provided c_cats structure should be free’d at object destruction, be aware that no other object should free them, otherwise you can expect a double free corruption segfault
- alive()[source]¶
Return True if this line is alive or False if this line is dead or its index is out of range.
- append(pnt)[source]¶
Appends one point to the end of a line, using the
Vect_append_point
C function.- Parameters:
pnt (a Point object or a tuple with the coordinates) – the point to add to line
>>> line = Line() >>> line.append((10, 100)) >>> line Line([Point(10.000000, 100.000000)]) >>> line.append((20, 200)) >>> line Line([Point(10.000000, 100.000000), Point(20.000000, 200.000000)])
Like python list.
- bbox(bbox=None)[source]¶
Return the bounding box of the line, using
Vect_line_box
C function.>>> line = Line([(0, 0), (0, 1), (2, 1), (2, 0)]) >>> bbox = line.bbox() >>> bbox Bbox(1.0, 0.0, 2.0, 0.0)
- buffer(dist=None, dist_x=None, dist_y=None, angle=0, round_=True, caps=True, tol=0.1)[source]¶
Return the buffer area around the line, using the
Vect_line_buffer2
C function.- Parameters:
- Returns:
the buffer as Area object
>>> line = Line([(0, 0), (0, 2)]) >>> boundary, centroid, isles = line.buffer(10) >>> boundary Line([Point(-10.000000, 0.000000),...Point(-10.000000, 0.000000)]) >>> centroid Point(0.000000, 0.000000) >>> isles []
- delete(indx)[source]¶
Remove the point in the index position. :param indx: the index where add new point :type indx: int
>>> line = Line([(0, 0), (1, 1), (2, 2)]) >>> line.delete(-1) >>> line Line([Point(0.000000, 0.000000), Point(1.000000, 1.000000)])
- distance(pnt)[source]¶
Calculate the distance between line and a point.
- Parameters:
pnt (a Point object or a tuple with the coordinates) – the point to calculate distance
- Return type:
Return a namedtuple with:
point: the closest point on the line,
dist: the distance between these two points,
spdist: distance to point on line from segment beginning
sldist: distance to point on line form line beginning along line
The distance is compute using the
Vect_line_distance
C function.>>> point = Point(2.3, 0.5) >>> line = Line([(0, 0), (2, 0), (3, 0)]) >>> line.distance(point) LineDist(point=Point(2.300000, 0.000000), dist=0.5, spdist=0.2999999999999998, sldist=2.3)
- extend(line, forward=True)[source]¶
Appends points to the end of a line.
- Parameters:
>>> line = Line([(0, 0), (1, 1)]) >>> line.extend(Line([(2, 2), (3, 3)])) >>> line Line([Point(0.000000, 0.000000), Point(1.000000, 1.000000), Point(2.000000, 2.000000), Point(3.000000, 3.000000)])
- first_cat()[source]¶
Fetches FIRST category number for given vector line and field, using the
Vect_get_line_cat
C function.Warning
Not implemented yet.
- from_wkt(wkt)[source]¶
Create a line reading a WKT string.
- Parameters:
wkt (str) – the WKT string containing the LINESTRING
>>> line = Line() >>> line.from_wkt("LINESTRING(0 0,1 1,1 2)") >>> line Line([Point(0.000000, 0.000000), Point(1.000000, 1.000000), Point(1.000000, 2.000000)])
- gtype = 2¶
- insert(indx, pnt)[source]¶
Insert new point at index position and move all old points at that position and above up, using
Vect_line_insert_point
C function.- Parameters:
indx (int) – the index where add new point
pnt (a Point object) – the point to add
>>> line = Line([(0, 0), (1, 1)]) >>> line.insert(0, Point(1.000000, -1.000000)) >>> line Line([Point(1.000000, -1.000000), Point(0.000000, 0.000000), Point(1.000000, 1.000000)])
- length()[source]¶
Calculate line length, 3D-length in case of 3D vector line, using
Vect_line_length
C function.>>> line = Line([(0, 0), (1, 1), (0, 1)]) >>> line.length() 2.414213562373095
- length_geodesic()[source]¶
Calculate line length, using
Vect_line_geodesic_length
C function.>>> line = Line([(0, 0), (1, 1), (0, 1)]) >>> line.length_geodesic() 2.414213562373095
- nodes()[source]¶
Return the start and end nodes of the line
This method requires topology build.
- Returns:
A tuple of Node objects that represent the start and end point of this line.
- point_on_line(distance, angle=0, slope=0)[source]¶
Return a Point object on line in the specified distance, using the Vect_point_on_line C function.
- Raises:
Raise a ValueError If the distance exceed the Line length.
>>> line = Line([(0, 0), (1, 1)]) >>> line.point_on_line(5) Traceback (most recent call last): ... ValueError: The distance exceed the length of the line, that is: 1.414214 >>> line.point_on_line(1) Point(0.707107, 0.707107)
- pop(indx)[source]¶
Return the point in the index position and remove from the Line.
- Parameters:
indx (int) – the index where add new point
>>> line = Line([(0, 0), (1, 1), (2, 2)]) >>> midle_pnt = line.pop(1) >>> midle_pnt Point(1.000000, 1.000000) >>> line Line([Point(0.000000, 0.000000), Point(2.000000, 2.000000)])
- prune()[source]¶
Remove duplicate points, i.e. zero length segments, using
Vect_line_prune
C function.>>> line = Line([(0, 0), (1, 1), (1, 1), (2, 2)]) >>> line.prune() >>> line Line([Point(0.000000, 0.000000), Point(1.000000, 1.000000), Point(2.000000, 2.000000)])
- prune_thresh(threshold)[source]¶
Remove points in threshold, using the
Vect_line_prune_thresh
C function.- Parameters:
threshold (num) – the threshold value where prune points
>>> line = Line([(0, 0), (1.0, 1.0), (1.2, 0.9), (2, 2)]) >>> line.prune_thresh(0.5) >>> line Line([Point(0.000000, 0.000000), Point(1.000000, 1.000000), Point(2.000000, 2.000000)])
Warning
prune_thresh is not working yet.
- remove(pnt)[source]¶
Delete point at given index and move all points above down, using
Vect_line_delete_point
C function.- Parameters:
pnt (a Point object or a tuple with the coordinates) – the point to remove
>>> line = Line([(0, 0), (1, 1), (2, 2)]) >>> line.remove((2, 2)) >>> line[-1] Point(1.000000, 1.000000)
- reset()[source]¶
Reset line, using Vect_reset_line C function.
>>> line = Line([(0, 0), (1, 1), (2, 0), (1, -1)]) >>> len(line) 4 >>> line.reset() >>> len(line) 0 >>> line Line([])
- reverse()[source]¶
Reverse the order of vertices, using
Vect_line_reverse
C function.>>> line = Line([(0, 0), (1, 1), (2, 2)]) >>> line.reverse() >>> line Line([Point(2.000000, 2.000000), Point(1.000000, 1.000000), Point(0.000000, 0.000000)])
- segment(start, end)[source]¶
Create line segment. using the
Vect_line_segment
C function.- Parameters:
# x (1, 1) # | # |- # | # x--------x (1, 0) # (0, 0) ^
>>> line = Line([(0, 0), (1, 0), (1, 1)]) >>> line.segment(0.5, 1.5) Line([Point(0.500000, 0.000000), Point(1.000000, 0.000000), Point(1.000000, 0.500000)])
- to_array()[source]¶
Return an array of coordinates.
>>> line = Line([(0, 0), (1, 1), (2, 0), (1, -1)]) >>> line.to_array() array([[ 0., 0.], [ 1., 1.], [ 2., 0.], [ 1., -1.]])
- class pygrass.vector.geometry.LineDist(point, dist, spdist, sldist)¶
Bases:
tuple
Create new instance of LineDist(point, dist, spdist, sldist)
- dist¶
Alias for field number 1
- point¶
Alias for field number 0
- sldist¶
Alias for field number 3
- spdist¶
Alias for field number 2
- class pygrass.vector.geometry.Node(v_id, c_mapinfo, **kwords)[source]¶
Bases:
object
Node class for topological analysis of line neighbors.
Objects of this class will be returned by the node() function of a Line object.
All methods in this class require a proper setup of the Node objects. Hence, the correct id and a valid pointer to a mapinfo object must be provided in the constructions. Otherwise a segfault may happen.
Construct a Node object
param v_id: The unique node id param c_mapinfo: A valid pointer to the mapinfo object param **kwords: Ignored
- alive()[source]¶
Return True if this node is alive or False if this node is dead or its index is out of range.
- ilines(only_in=False, only_out=False)[source]¶
Return a generator with all lines id connected to a node. The line id is negative if line is ending on the node and positive if starting from the node.
- class pygrass.vector.geometry.Point(x=0, y=0, z=None, **kargs)[source]¶
Bases:
Geo
Instantiate a Point object that could be 2 or 3D, default parameters are 0.
>>> pnt = Point() >>> pnt.x 0.0 >>> pnt.y 0.0 >>> pnt.z >>> pnt.is2D True >>> pnt Point(0.000000, 0.000000) >>> pnt.z = 0 >>> pnt.is2D False >>> pnt Point(0.000000, 0.000000, 0.000000) >>> print(pnt) POINT Z (0.0000000000000000 0.0000000000000000 0.0000000000000000) >>> c_points = ctypes.pointer(libvect.line_pnts()) >>> c_cats = ctypes.pointer(libvect.line_cats()) >>> p = Point(c_points=c_points, c_cats=c_cats) >>> del p >>> c_points = ctypes.pointer(libvect.line_pnts()) >>> c_cats = ctypes.pointer(libvect.line_cats()) >>> p = Point( ... c_points=c_points, c_cats=c_cats, free_points=True, free_cats=True ... ) >>> del p
Constructor of a geometry object
- Parameters:
v_id – The vector feature id
c_mapinfo – A pointer to the vector mapinfo structure
c_points – A pointer to a libvect.line_pnts structure, this is optional, if not set an internal structure will be allocated and free’d at object destruction
c_cats – A pointer to a libvect.line_cats structure, this is optional, if not set an internal structure will be allocated and free’d at object destruction
table – The attribute table to select attributes for this feature
writeable – Not sure what this is for?
is2D – If True this feature has two dimensions, False if this feature has three dimensions
free_points – Set this True if the provided c_points structure should be free’d at object destruction, be aware that no other object should free them, otherwise you can expect a double free corruption segfault
free_cats – Set this True if the provided c_cats structure should be free’d at object destruction, be aware that no other object should free them, otherwise you can expect a double free corruption segfault
- buffer(dist=None, dist_x=None, dist_y=None, angle=0, round_=True, tol=0.1)[source]¶
Return the buffer area around the point, using the
Vect_point_buffer2
C function.- Parameters:
- Returns:
the buffer as Area object
>>> pnt = Point(0, 0) >>> boundary, centroid = pnt.buffer(10) >>> boundary Line([Point(10.000000, 0.000000),...Point(10.000000, 0.000000)]) >>> centroid Point(0.000000, 0.000000)
- coords()[source]¶
Return a tuple with the point coordinates.
>>> pnt = Point(10, 100) >>> pnt.coords() (10.0, 100.0)
If the point is 2D return a x, y tuple. But if we change the
z
the Point object become a 3D point, therefore the method return a x, y, z tuple.>>> pnt.z = 1000.0 >>> pnt.coords() (10.0, 100.0, 1000.0)
- distance(pnt)[source]¶
Calculate distance of 2 points, using the
Vect_points_distance
C function, If one of the point have z == None, return the 2D distance.- Parameters:
pnt (a Point object or a tuple with the coordinates) – the point for calculate the distance
>>> pnt0 = Point(0, 0, 0) >>> pnt1 = Point(1, 0) >>> pnt0.distance(pnt1) 1.0 >>> pnt1.z = 1 >>> pnt1 Point(1.000000, 0.000000, 1.000000) >>> pnt0.distance(pnt1) 1.4142135623730951
- gtype = 1¶
- to_wkt_p()[source]¶
Return a “well know text” (WKT) geometry string Python implementation.
>>> pnt = Point(10, 100) >>> pnt.to_wkt_p() 'POINT(10.000000 100.000000)'
Warning
Only
POINT
(2/3D) are supported,POINTM
andPOINT
with:XYZM
are not supported yet.
- property x¶
Set and obtain x coordinate
- property y¶
Set and obtain y coordinate
- property z¶
Set and obtain z coordinate
- pygrass.vector.geometry.get_xyz(pnt)[source]¶
Return a tuple with: x, y, z.
>>> pnt = Point(0, 0) >>> get_xyz(pnt) (0.0, 0.0, 0.0) >>> get_xyz((1, 1)) (1, 1, 0.0) >>> get_xyz((1, 1, 2)) (1, 1, 2) >>> get_xyz((1, 1, 2, 2)) Traceback (most recent call last): ... ValueError: The the format of the point is not supported: (1, 1, 2, 2)
- pygrass.vector.geometry.intersects(lineA, lineB, with_z=False)[source]¶
Return a list of points
>>> lineA = Line([(0, 0), (4, 0)]) >>> lineB = Line([(2, 2), (2, -2)]) >>> intersects(lineA, lineB) Line([Point(2.000000, 0.000000)])
- pygrass.vector.geometry.read_WKT(string)[source]¶
Read the string and return a geometry object
WKT:
POINT(0 0) LINESTRING(0 0,1 1,1 2) POLYGON((0 0,4 0,4 4,0 4,0 0),(1 1, 2 1, 2 2, 1 2,1 1)) MULTIPOINT(0 0,1 2) MULTILINESTRING((0 0,1 1,1 2),(2 3,3 2,5 4)) MULTIPOLYGON(((0 0,4 0,4 4,0 4,0 0),(1 1,2 1,2 2,1 2,1 1)), ((-1 -1,-1 -2,-2 -2,-2 -1,-1 -1))) GEOMETRYCOLLECTION(POINT(2 3),LINESTRING(2 3,3 4))
EWKT:
POINT(0 0 0) -- XYZ SRID=32632;POINT(0 0) -- XY with SRID POINTM(0 0 0) -- XYM POINT(0 0 0 0) -- XYZM SRID=4326;MULTIPOINTM(0 0 0,1 2 1) -- XYM with SRID MULTILINESTRING((0 0 0,1 1 0,1 2 1),(2 3 1,3 2 1,5 4 1)) 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)) MULTIPOLYGON(((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)), ((-1 -1 0,-1 -2 0,-2 -2 0,-2 -1 0,-1 -1 0))) GEOMETRYCOLLECTIONM( POINTM(2 3 9), LINESTRINGM(2 3 4, 3 4 5) ) MULTICURVE( (0 0, 5 5), CIRCULARSTRING(4 0, 4 4, 8 4) ) POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) ) TRIANGLE ((0 0, 0 9, 9 0, 0 0)) 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)) )
pygrass.vector.sql module¶
It is a collection of strings to avoid to repeat the code.
>>> SELECT.format(cols=", ".join(["cat", "area"]), tname="table")
'SELECT cat, area FROM table;'
>>> SELECT_WHERE.format(
... cols=", ".join(["cat", "area"]), tname="table", condition="area>10000"
... )
'SELECT cat, area FROM table WHERE area>10000;'
pygrass.vector.table module¶
Created on Wed Aug 8 15:29:21 2012
@author: pietro
- class pygrass.vector.table.Columns(tname, connection, key='cat')[source]¶
Bases:
object
Object to work with columns table.
It is possible to instantiate a Columns object given the table name and the database connection.
For a sqlite table:
>>> import sqlite3 >>> from grass.pygrass.vector.table import get_path >>> path = "$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db" >>> cols_sqlite = Columns(test_vector_name, sqlite3.connect(get_path(path))) >>> cols_sqlite.tname 'table_doctest_map'
For a postgreSQL table:
>>> import psycopg2 as pg >>> cols_pg = Columns( ... test_vector_name, pg.connect("host=localhost dbname=grassdb") ... ) >>> cols_pg.tname 'table_doctest_map'
- add(col_name, col_type)[source]¶
Add a new column to the table.
>>> import sqlite3 >>> from grass.pygrass.vector.table import get_path >>> path = "$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db" >>> from grass.pygrass.utils import copy, remove >>> copy(test_vector_name, "mycensus", "vect") >>> cols_sqlite = Columns("mycensus", sqlite3.connect(get_path(path))) >>> cols_sqlite.add(["n_pizza"], ["INT"]) >>> "n_pizza" in cols_sqlite True >>> import psycopg2 as pg >>> cols_pg = Columns( ... "boundary_municp_pg", pg.connect("host=localhost dbname=grassdb") ... ) >>> cols_pg.add("n_pizza", "INT") >>> "n_pizza" in cols_pg True >>> remove("mycensus", "vect")
- cast(col_name, new_type)[source]¶
Change the column type.
>>> import sqlite3 >>> from grass.pygrass.vector.table import get_path >>> path = "$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db" >>> from grass.pygrass.utils import copy, remove >>> copy(test_vector_name, "mycensus", "vect") >>> cols_sqlite = Columns("mycensus", sqlite3.connect(get_path(path))) >>> cols_sqlite.add(["n_pizzas"], ["INT"]) >>> cols_sqlite.cast("n_pizzas", "float8") Traceback (most recent call last): ... grass.exceptions.DBError: SQLite does not support to cast columns. >>> import psycopg2 as pg >>> cols_pg = Columns( ... test_vector_name, pg.connect("host=localhost dbname=grassdb") ... ) >>> cols_pg.cast("n_pizzas", "float8") >>> cols_pg["n_pizzas"] 'float8' >>> remove("mycensus", "vect")
Warning
It is not possible to cast a column with sqlite
- drop(col_name)[source]¶
Drop a column from the table.
- Parameters:
col_name (str) – the name of column to remove
>>> import sqlite3 >>> from grass.pygrass.vector.table import get_path >>> path = "$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db" >>> from grass.pygrass.utils import copy, remove >>> copy(test_vector_name, "mycensus", "vect") >>> cols_sqlite = Columns("mycensus", sqlite3.connect(get_path(path))) >>> cols_sqlite.drop("name") >>> "name" in cols_sqlite False
>>> import psycopg2 as pg >>> cols_pg = Columns( ... test_vector_name, pg.connect("host=localhost dbname=grassdb") ... ) >>> cols_pg.drop("name") >>> "name" in cols_pg False >>> remove("mycensus", "vect")
- is_pg()[source]¶
Return True if is a psycopg connection.
>>> import sqlite3 >>> from grass.pygrass.vector.table import get_path >>> path = "$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db" >>> cols_sqlite = Columns(test_vector_name, sqlite3.connect(get_path(path))) >>> cols_sqlite.is_pg() False >>> import psycopg2 as pg >>> cols_pg = Columns( ... test_vector_name, pg.connect("host=localhost dbname=grassdb") ... ) >>> cols_pg.is_pg() True
- items()[source]¶
Return a list of tuple with column name and column type.
>>> import sqlite3 >>> from grass.pygrass.vector.table import get_path >>> path = "$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db" >>> cols_sqlite = Columns(test_vector_name, sqlite3.connect(get_path(path))) >>> cols_sqlite.items() [('cat', 'INTEGER'), ('name', 'varchar(50)'), ('value', 'double precision')] >>> import psycopg2 as pg >>> cols_pg = Columns( ... test_vector_name, pg.connect("host=localhost dbname=grassdb") ... ) >>> cols_pg.items() [('cat', 'INTEGER'), ('name', 'varchar(50)'), ('value', 'double precision')]
- names(remove=None, unicod=True)[source]¶
Return a list with the column names. Remove it is used to remove a columns.
>>> import sqlite3 >>> from grass.pygrass.vector.table import get_path >>> path = "$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db" >>> cols_sqlite = Columns(test_vector_name, sqlite3.connect(get_path(path))) >>> cols_sqlite.names() ['cat', 'name', 'value'] >>> import psycopg2 as pg >>> cols_pg = Columns( ... test_vector_name, ... pg.connect("host=localhost dbname=grassdb"), ... ) >>> cols_pg.names() ['cat', 'name', 'value']
- rename(old_name, new_name)[source]¶
Rename a column of the table.
>>> import sqlite3 >>> from grass.pygrass.vector.table import get_path >>> path = "$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db" >>> from grass.pygrass.utils import copy, remove >>> copy(test_vector_name, "mycensus", "vect") >>> cols_sqlite = Columns("mycensus", sqlite3.connect(get_path(path))) >>> cols_sqlite.add(["n_pizza"], ["INT"]) >>> "n_pizza" in cols_sqlite True >>> cols_sqlite.rename("n_pizza", "n_pizzas") >>> "n_pizza" in cols_sqlite False >>> "n_pizzas" in cols_sqlite True
>>> import psycopg2 as pg >>> cols_pg = Columns( ... test_vector_name, pg.connect("host=localhost dbname=grassdb") ... ) >>> cols_pg.rename("n_pizza", "n_pizzas") >>> "n_pizza" in cols_pg False >>> "n_pizzas" in cols_pg True >>> remove("mycensus", "vect")
- sql_descr(remove=None)[source]¶
Return a string with description of columns. Remove it is used to remove a columns.
>>> import sqlite3 >>> from grass.pygrass.vector.table import get_path >>> path = "$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db" >>> cols_sqlite = Columns(test_vector_name, sqlite3.connect(get_path(path))) >>> cols_sqlite.sql_descr() 'cat INTEGER, name varchar(50), value double precision' >>> import psycopg2 as pg >>> cols_pg = Columns( ... test_vector_name, pg.connect("host=localhost dbname=grassdb") ... ) >>> cols_pg.sql_descr() 'cat INTEGER, name varchar(50), value double precision'
- types()[source]¶
Return a list with the column types.
>>> import sqlite3 >>> from grass.pygrass.vector.table import get_path >>> path = "$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db" >>> cols_sqlite = Columns(test_vector_name, sqlite3.connect(get_path(path))) >>> cols_sqlite.types() ['INTEGER', 'varchar(50)', 'double precision'] >>> import psycopg2 as pg >>> cols_pg = Columns( ... test_vector_name, pg.connect("host=localhost dbname=grassdb") ... ) >>> cols_pg.types() ['INTEGER', 'varchar(50)', 'double precision']
- class pygrass.vector.table.DBlinks(c_mapinfo)[source]¶
Bases:
object
Interface containing link to the table DB.
>>> from grass.pygrass.vector import VectorTopo >>> cens = VectorTopo(test_vector_name) >>> cens.open(mode="r") >>> dblinks = DBlinks(cens.c_mapinfo) >>> dblinks DBlinks([Link(1, table_doctest_map, sqlite)]) >>> dblinks[0] Link(1, table_doctest_map, sqlite) >>> dblinks[test_vector_name] Link(1, table_doctest_map, sqlite) >>> cens.close()
- add(link)[source]¶
Add a new link. Need to open vector map in write mode
- Parameters:
link – the Link to add to the DBlinks
- by_index(indx)[source]¶
Return a Link object by index
- Parameters:
indx (int) – the index where add new point
- by_layer(layer)[source]¶
Return the chosen Link using the layer
- Parameters:
layer (int) – the number of layer
- by_name(name)[source]¶
Return the chosen Link using the name
- Parameters:
name (str) – the name of Link
- remove(key, force=False)[source]¶
Remove a link. If force set to true remove also the table
- Parameters:
key (str) – the key of Link
force (boole) – if True remove also the table from database otherwise only the link between table and vector
>>> from grass.pygrass.vector import VectorTopo >>> test_vect = VectorTopo(test_vector_name) >>> test_vect.open(mode="r") >>> dblinks = DBlinks(test_vect.c_mapinfo) >>> dblinks DBlinks([Link(1, table_doctest_map, sqlite)]) >>> dblinks.remove("pg_link") >>> dblinks # need to open vector map in write mode DBlinks([Link(1, table_doctest_map, sqlite)])
- class pygrass.vector.table.Filters(tname)[source]¶
Bases:
object
Help user to build a simple sql query.
>>> filter = Filters("table") >>> filter.get_sql() 'SELECT * FROM table;' >>> filter.where("area<10000").get_sql() 'SELECT * FROM table WHERE area<10000;' >>> filter.select("cat", "area").get_sql() 'SELECT cat, area FROM table WHERE area<10000;' >>> filter.order_by("area").limit(10).get_sql() 'SELECT cat, area FROM table WHERE area<10000 ORDER BY area LIMIT 10;'
- limit(number)[source]¶
Create the limit condition
- Parameters:
number (int) – the number to limit the result
- class pygrass.vector.table.Link(layer=1, name=None, table=None, key='cat', database='$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db', driver='sqlite', c_fieldinfo=None)[source]¶
Bases:
object
Define a Link between vector map and the attributes table.
It is possible to define a Link object or given all the information (layer, name, table name, key, database, driver):
>>> link = Link( ... 1, ... "link0", ... test_vector_name, ... "cat", ... "$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db", ... "sqlite", ... ) >>> link.layer 1 >>> link.name 'link0' >>> link.table_name 'table_doctest_map' >>> link.key 'cat' >>> link.database '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db' >>> link.driver 'sqlite' >>> link Link(1, link0, sqlite)
It is possible to change parameters with:
>>> link.driver = "pg" >>> link.driver 'pg' >>> link.driver = "postgres" Traceback (most recent call last): ... TypeError: Driver not supported, use: sqlite, pg. >>> link.driver 'pg' >>> link.number = 0 Traceback (most recent call last): ... TypeError: Number must be positive and greater than 0.
Or given a c_fieldinfo object that is a ctypes pointer to the field_info C struct.
>>> link = Link(c_fieldinfo=ctypes.pointer(libvect.field_info()))
- connection()[source]¶
Return a connection object.
>>> link = Link( ... 1, ... "link0", ... test_vector_name, ... "cat", ... "$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db", ... "sqlite", ... ) >>> conn = link.connection() >>> cur = conn.cursor() >>> link.table_name 'table_doctest_map' >>> cur.execute( ... "SELECT cat, name, value from %s" % link.table_name ... ) <sqlite3.Cursor object at ...> >>> cur.fetchone() (1, 'point', 1.0) >>> cur.close() >>> conn.close()
- property database¶
Set and obtain database value
- property driver¶
Set and obtain driver value. The drivers supported by PyGRASS are: SQLite and PostgreSQL
- info()[source]¶
Print information of the link.
>>> link = Link( ... 1, ... "link0", ... test_vector_name, ... "cat", ... "$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db", ... "sqlite", ... ) >>> link.info() layer: 1 name: link0 table: table_doctest_map key: cat database: $GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db driver: sqlite
- property key¶
Set and obtain cat value
- property layer¶
Set and obtain layer number
- property name¶
Set and obtain name vale
- table()[source]¶
Return a Table object.
>>> link = Link( ... 1, ... "link0", ... test_vector_name, ... "cat", ... "$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db", ... "sqlite", ... ) >>> table = link.table() >>> table.filters.select("cat", "name", "value") Filters('SELECT cat, name, value FROM table_doctest_map;') >>> cur = table.execute() >>> cur.fetchone() (1, 'point', 1.0) >>> cur.close()
- property table_name¶
Set and obtain table name value
- class pygrass.vector.table.Table(name, connection, key='cat')[source]¶
Bases:
object
>>> import sqlite3 >>> from grass.pygrass.vector.table import get_path >>> path = "$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db" >>> tab_sqlite = Table( ... name=test_vector_name, connection=sqlite3.connect(get_path(path)) ... ) >>> tab_sqlite.name 'table_doctest_map' >>> import psycopg2 >>> tab_pg = Table( ... test_vector_name, psycopg2.connect("host=localhost dbname=grassdb", "pg") ... ) >>> tab_pg.columns Columns([('cat', 'int4'), ...])
- drop(cursor=None, force=False)[source]¶
Method to drop table from database
- Parameters:
cursor (Cursor object) – the cursor to connect, if None it use the cursor of connection table object
force (bool) – True to remove the table, by default False to print advice
- execute(sql_code=None, cursor=None, many=False, values=None)[source]¶
Execute SQL code from a given string or build with filters and return a cursor object.
- Parameters:
>>> import sqlite3 >>> from grass.pygrass.vector.table import get_path >>> path = "$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db" >>> tab_sqlite = Table( ... name=test_vector_name, connection=sqlite3.connect(get_path(path)) ... ) >>> tab_sqlite.filters.select("cat", "name").order_by("value") Filters('SELECT cat, name FROM table_doctest_map ORDER BY value;') >>> cur = tab_sqlite.execute() >>> cur.fetchone() (1, 'point')
- exist(cursor=None)[source]¶
Return True if the table already exists in the DB, False otherwise
- Parameters:
cursor – the cursor to connect, if None it use the cursor of connection table object
- n_rows()[source]¶
Return the number of rows
>>> import sqlite3 >>> from grass.pygrass.vector.table import get_path >>> path = "$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db" >>> tab_sqlite = Table( ... name=test_vector_name, connection=sqlite3.connect(get_path(path)) ... ) >>> tab_sqlite.n_rows() 3
- property name¶
Set and obtain table name
- pygrass.vector.table.get_path(path, vect_name=None)[source]¶
Return the full path to the database; replacing environment variable with real values
- Parameters:
path – The path with substitutional parameter
vect_name – The name of the vector map
>>> from grass.script.core import gisenv >>> import os >>> path = "$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db" >>> new_path = get_path(path) >>> new_path2 = os.path.join( ... gisenv()["GISDBASE"], ... gisenv()["LOCATION_NAME"], ... gisenv()["MAPSET"], ... "sqlite", ... "sqlite.db", ... ) >>> new_path.replace("//", "/") == new_path2.replace("//", "/") True >>> path = "$GISDBASE/$LOCATION_NAME/$MAPSET/vector/$MAP/sqlite.db" >>> new_path = get_path(path, "test") >>> new_path2 = os.path.join( ... gisenv()["GISDBASE"], ... gisenv()["LOCATION_NAME"], ... gisenv()["MAPSET"], ... "vector", ... "test", ... "sqlite.db", ... ) >>> new_path.replace("//", "/") == new_path2.replace("//", "/") True
pygrass.vector.vector_type module¶
Created on Wed Jul 18 10:49:26 2012
@author: pietro
Module contents¶
- class pygrass.vector.Vector(name, mapset='', *args, **kwargs)[source]¶
Bases:
Info
Vector class is the grass vector format without topology
>>> from grass.pygrass.vector import Vector >>> test_vect = Vector(test_vector_name) >>> test_vect.is_open() False >>> test_vect.mapset '' >>> test_vect.exist() True >>> test_vect.overwrite False
- has_color_table()[source]¶
Return if vector has color table associated in file system; Color table stored in the vector’s attribute table well be not checked
>>> test_vect = Vector(test_vector_name) >>> test_vect.open(mode="r") >>> test_vect.has_color_table() False
>>> test_vect.close() >>> from grass.pygrass.utils import copy, remove >>> copy(test_vector_name, "mytest_vect", "vect") >>> from grass.pygrass.modules.shortcuts import vector as v >>> v.colors(map="mytest_vect", color="population", column="value") Module('v.colors') >>> mytest_vect = Vector("mytest_vect") >>> mytest_vect.open(mode="r") >>> mytest_vect.has_color_table() True >>> mytest_vect.close() >>> remove("mytest_vect", "vect")
- write(geo_obj, cat=None, attrs=None)[source]¶
Write geometry features and attributes.
- Parameters:
geo_obj (geometry GRASS object) – a geometry grass object define in grass.pygrass.vector.geometry
attrs (list) – a list with the values that will be inserted in the attribute table.
cat (integer) – The category of the geometry feature, otherwise the c_cats attribute of the geometry object will be used.
Open a new vector map
>>> new = VectorTopo("newvect") >>> new.exist() False
define the new columns of the attribute table
>>> cols = [("cat", "INTEGER PRIMARY KEY"), ("name", "TEXT")]
open the vector map in write mode
>>> new.open("w", tab_name="newvect", tab_cols=cols)
import a geometry feature
>>> from grass.pygrass.vector.geometry import Point
create two points
>>> point0 = Point(0, 0) >>> point1 = Point(1, 1)
then write the two points on the map, with
>>> new.write(point0, cat=1, attrs=("pub",)) >>> new.write(point1, cat=2, attrs=("restaurant",))
commit the db changes
>>> new.table.conn.commit() >>> new.table.execute().fetchall() [(1, 'pub'), (2, 'restaurant')]
close the vector map
>>> new.close() >>> new.exist() True
then play with the map
>>> new.open(mode="r") >>> new.read(1) Point(0.000000, 0.000000) >>> new.read(2) Point(1.000000, 1.000000) >>> new.read(1).attrs["name"] 'pub' >>> new.read(2).attrs["name"] 'restaurant' >>> new.close() >>> new.remove()
- class pygrass.vector.VectorTopo(name, mapset='', *args, **kwargs)[source]¶
Bases:
Vector
Vector class with the support of the GRASS topology.
Open a vector map using the with statement:
>>> with VectorTopo(test_vector_name, mode="r") as test_vect: ... for feature in test_vect[:7]: ... print(feature.attrs["name"]) ... point point point line line line >>> test_vect.is_open() False
- areas_to_wkb_list(bbox=None, field=1)[source]¶
Return all features of type point, line, boundary or centroid as a list of Well Known Binary representations (WKB) (id, cat, wkb) triplets located in a specific bounding box.
- Parameters:
bbox (grass.pygrass.vector.basic.Bbox) – The boundingbox to search for features, if bbox=None the boundingbox of the whole vector map layer is used
field (integer) – The centroid category field
- Returns:
A list of triplets, or None if nothing was found
The well known binary are stored in byte arrays.
Examples:
>>> from grass.pygrass.vector import VectorTopo >>> from grass.pygrass.vector.basic import Bbox >>> test_vect = VectorTopo(test_vector_name) >>> test_vect.open("r") >>> bbox = Bbox(north=20, south=-1, east=20, west=-1) >>> result = test_vect.areas_to_wkb_list(bbox=bbox) >>> len(result) 4 >>> for entry in result: ... a_id, cat, wkb = entry ... print((a_id, cat, len(wkb))) (1, 3, 225) (2, 3, 141) (3, 3, 93) (4, 3, 141) >>> result = test_vect.areas_to_wkb_list() >>> len(result) 4 >>> for entry in result: ... a_id, cat, wkb = entry ... print((a_id, cat, len(wkb))) (1, 3, 225) (2, 3, 141) (3, 3, 93) (4, 3, 141) >>> test_vect.close()
- cat(cat_id, vtype, layer=None, generator=False, geo=None)[source]¶
Return the geometry features with category == cat_id.
- close(build=True, release=True)[source]¶
Close the VectorTopo map, if release is True, the memory occupied by spatial index is released
- delete(feature_id)[source]¶
Remove a feature by its id
- Parameters:
feature_id (int) – the id of the feature
- features_to_wkb_list(bbox=None, feature_type='point', field=1)[source]¶
Return all features of type point, line, boundary or centroid as a list of Well Known Binary representations (WKB) (id, cat, wkb) triplets located in a specific bounding box.
- Parameters:
bbox (grass.pygrass.vector.basic.Bbox) – The boundingbox to search for features, if bbox=None the boundingbox of the whole vector map layer is used
feature_type (string) – The type of feature that should be converted to the Well Known Binary (WKB) format. Supported are: ‘point’ -> libvect.GV_POINT 1 ‘line’ -> libvect.GV_LINE 2 ‘boundary’ -> libvect.GV_BOUNDARY 3 ‘centroid’ -> libvect.GV_CENTROID 4
field (integer) – The category field
- Returns:
A list of triplets, or None if nothing was found
The well known binary are stored in byte arrays.
Examples:
>>> from grass.pygrass.vector import VectorTopo >>> from grass.pygrass.vector.basic import Bbox >>> test_vect = VectorTopo(test_vector_name) >>> test_vect.open("r") >>> bbox = Bbox(north=20, south=-1, east=20, west=-1) >>> result = test_vect.features_to_wkb_list(bbox=bbox, feature_type="point") >>> len(result) 3 >>> for entry in result: ... f_id, cat, wkb = entry ... print((f_id, cat, len(wkb))) (1, 1, 21) (2, 1, 21) (3, 1, 21) >>> result = test_vect.features_to_wkb_list(bbox=None, feature_type="line") >>> len(result) 3 >>> for entry in result: ... f_id, cat, wkb = entry ... print((f_id, cat, len(wkb))) (4, 2, 57) (5, 2, 57) (6, 2, 57) >>> result = test_vect.features_to_wkb_list(bbox=bbox, feature_type="boundary") >>> len(result) 11 >>> result = test_vect.features_to_wkb_list(bbox=None, feature_type="centroid") >>> len(result) 4 >>> for entry in result: ... f_id, cat, wkb = entry ... print((f_id, cat, len(wkb))) (19, 3, 21) (18, 3, 21) (20, 3, 21) (21, 3, 21) >>> result = test_vect.features_to_wkb_list(bbox=bbox, feature_type="blub") Traceback (most recent call last): ... grass.exceptions.GrassError: Unsupported feature type <blub>, supported are <point,line,boundary,centroid> >>> test_vect.close()
- num_primitive_of(primitive)[source]¶
Return the number of primitive
- Parameters:
primitive (str) –
the name of primitive to query; the supported values are:
boundary,
centroid,
face,
kernel,
line,
point
area
volume
>>> test_vect = VectorTopo(test_vector_name) >>> test_vect.open(mode="r") >>> test_vect.num_primitive_of("point") 3 >>> test_vect.num_primitive_of("line") 3 >>> test_vect.num_primitive_of("centroid") 4 >>> test_vect.num_primitive_of("boundary") 11 >>> test_vect.close()
- number_of(vtype)[source]¶
Return the number of the chosen element type
- Parameters:
vtype – the name of type to query; the supported values are: areas, dblinks, faces, holes, islands, kernels, points, lines, centroids, boundaries, nodes, line_points, update_lines, update_nodes, volumes
- read(feature_id)[source]¶
Return a geometry object given the feature id.
- Parameters:
feature_id (int) – the id of feature to obtain
>>> test_vect = VectorTopo(test_vector_name) >>> test_vect.open(mode="r") >>> feature1 = test_vect.read(0) Traceback (most recent call last): ... ValueError: The index must be >0, 0 given. >>> feature1 = test_vect.read(5) >>> feature1 Line([Point(12.000000, 4.000000), Point(12.000000, 2.000000), Point(12.000000, 0.000000)]) >>> feature1.length() 4.0 >>> test_vect.read(-1) Centroid(7.500000, 3.500000) >>> len(test_vect) 21 >>> test_vect.read(21) Centroid(7.500000, 3.500000) >>> test_vect.read(22) Traceback (most recent call last): ... IndexError: Index out of range >>> test_vect.close()
- rewind()[source]¶
Rewind vector map to cause reads to start at beginning.
>>> test_vect = VectorTopo(test_vector_name) >>> test_vect.open(mode="r") >>> test_vect.next() Point(10.000000, 6.000000) >>> test_vect.next() Point(12.000000, 6.000000) >>> test_vect.next() Point(14.000000, 6.000000) >>> test_vect.rewind() >>> test_vect.next() Point(10.000000, 6.000000) >>> test_vect.close()
- rewrite(geo_obj, cat, attrs=None, **kargs)[source]¶
Rewrite a geometry features
>>> cols = [("cat", "INTEGER PRIMARY KEY"), ("name", "TEXT")]
Generate a new vector map
>>> test_vect = VectorTopo("newvect_2") >>> test_vect.open("w", tab_name="newvect_2", tab_cols=cols, overwrite=True)
import a geometry feature
>>> from grass.pygrass.vector.geometry import Point
create two points
>>> point0 = Point(0, 0) >>> point1 = Point(1, 1) >>> point2 = Point(2, 2)
then write the two points on the map, with
>>> test_vect.write(point0, cat=1, attrs=("pub",)) >>> test_vect.write(point1, cat=2, attrs=("restaurant",)) >>> test_vect.table.conn.commit() # save changes in the DB >>> test_vect.table_to_dict() {1: [1, 'pub'], 2: [2, 'restaurant']} >>> test_vect.close()
Now rewrite one point of the vector map:
>>> test_vect.open("rw") >>> test_vect.rewrite(point2, cat=1, attrs=("Irish Pub",)) >>> test_vect.table.conn.commit() # save changes in the DB >>> test_vect.close()
Check the output:
>>> test_vect.open("r") >>> test_vect[1] == point2 True >>> test_vect[1].attrs["name"] == "Irish Pub" True >>> test_vect.close() >>> test_vect.remove()
- table_to_dict(where=None)[source]¶
Return the attribute table as a dictionary with the category as keys
The columns have the order of the self.table.columns.names() list.
Examples
>>> from grass.pygrass.vector import VectorTopo >>> from grass.pygrass.vector.basic import Bbox >>> test_vect = VectorTopo(test_vector_name) >>> test_vect.open("r")
>>> test_vect.table_to_dict() {1: [1, 'point', 1.0], 2: [2, 'line', 2.0], 3: [3, 'centroid', 3.0]}
>>> test_vect.table_to_dict(where="value > 2") {3: [3, 'centroid', 3.0]}
>>> test_vect.table_to_dict(where="value > 0") {1: [1, 'point', 1.0], 2: [2, 'line', 2.0], 3: [3, 'centroid', 3.0]}
>>> test_vect.table.filters.get_sql() 'SELECT cat,name,value FROM vector_doctest_map WHERE value > 0 ORDER BY cat;'
- viter(vtype, idonly=False)[source]¶
Return an iterator of vector features
- Parameters:
vtype (str) – the name of type to query; the supported values are: areas, dblinks, faces, holes, islands, kernels, line_points, lines, nodes, points, update_lines, update_nodes, volumes
idonly – variable to return only the id of features instead of full features
to sort the result in an efficient way, use:
>>> from operator import methodcaller as method >>> areas.sort(key=method("area"), reverse=True) # sort the list >>> for area in areas[:3]: ... print(area, area.area()) Area(1) 12.0 Area(2) 8.0 Area(4) 8.0 >>> areas = [area for area in test_vect.viter("areas")] >>> for area in areas: ... print(area.centroid().cat) ... 3 3 3 3 >>> test_vect.close()