GRASS GIS logo

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()
build()[source]

Close the vector map and build vector Topology

close(build=False)[source]

Method to close the Vector

Parameters:build (bool) – True if the vector map should be build before close it
comment

Set or obtain the Vector comment

date

Set or obtain the Vector date

exist()[source]

Return if the Vector exists or not

full_name[source]

Return the full name of Vector

is_3D()[source]

Return if the Vector is 3D

is_open()[source]

Return if the Vector is open

map_date

Set or obtain the Vector map date

mapset

Set or obtain the Vector mapset

maptype[source]

Return the map type of Vector

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 in rw read and write mode
  • layer (int) – specify the layer that you want to use
  • overwrite (bool) – valid only for w mode
  • with_z (bool) – specify if vector map must be open with third dimension enabled or not. Valid only for w mode, default: False
  • tab_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 vecto map
  • link_name (str) – define the name of the link connecttion with the database
  • link_key (str) – define the nema of the column that will be use 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 or rw

See more examples in the documentation of the read and write methods

organization

Set or obtain the Vector organization

person

Set or obtain the Vector author

proj

Set or obtain the Vector projection code

proj_name[source]

Return the project name of Vector

remove()[source]

Remove vector map

rename(newname)[source]

Method to rename the Vector map

Parameters:newname (str) – the new name for the Vector map
scale

Set or obtain the Vector scale

thresh

Set or obtain the Vector threshold

title

Set or obtain the Vector title

write_header()[source]

Save the change in the C struct permanently to disk.

zone

Set or obtain the Vector projection zone

pygrass.vector.abstract.is_open(c_mapinfo)[source]

Return if the Vector is open

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)
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
east

Set and obtain east value

items()[source]
keys()[source]
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
south

Set and obtain south value

top

Set and obtain top value

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:
  • bbox – the bounding box to add to the list
  • bbox – a Bbox object
>>> 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
have_boxes()[source]
ids[source]
n_values[source]
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 the Vect_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)])
reset()[source]

Reset the c_boxlist C struct, using the Vect_reset_boxlist C function.

>>> boxlist = BoxList([Bbox(),
...                    Bbox(1, 0, 0, 1),
...                    Bbox(1, -1, -1, 1)])
>>> len(boxlist)
3
>>> boxlist.reset()
>>> len(boxlist)
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 xrange(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
[]
cat[source]
check_cats_constraints(cats_list, layer=1)[source]

Check if categories match with category constraints

Parameters:
  • cats_list (list) – a list of categories
  • layer (int) – the number of layer
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).

Parameters:
  • cat (int) – the cat to add
  • layer (int) – the number of layer
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
layer[source]
n_cats[source]

Return the number of categories

reset()[source]

Reset the C cats struct from previous values.

set(cat, layer=1)[source]

Add new field/cat to category structure if doesn’t exist yet.

Parameters:
  • cat (int) – the cat to add
  • layer (int) – the number of layer
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
layer[source]

Return the layer number

max[source]

Return the maximum value

min[source]

Return the minimum value

n_ranges[source]

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 as c_ilist attribute.

append(value)[source]

Append an integer to the list

contains(value)[source]

Check if value is in the list

extend(ilist)[source]

Extend the list with another Ilist object or with a list of integers

Parameters:ilist (a Ilist object) – the ilist to append
remove(value)[source]

Remove a value from a list

reset()[source]

Reset the list

pygrass.vector.find module

Created on Tue Mar 19 11:09:30 2013

@author: pietro

class pygrass.vector.find.AbstractFinder(c_mapinfo, table=None, writeable=False)[source]

Bases: object

is_open()[source]

Check if the vector map is open or not

class pygrass.vector.find.BboxFinder(c_mapinfo, table=None, writeable=False)[source]

Bases: pygrass.vector.find.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.

areas(*args, **kargs)[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(*args, **kargs)[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)]),
 Centoid(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(*args, **kargs)[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(*args, **kargs)[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=None, writeable=False)[source]

Bases: pygrass.vector.find.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.

area(*args, **kargs)[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()) #doctest: +NORMALIZE_WHITESPACE 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(*args, **kargs)[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()) #doctest: +NORMALIZE_WHITESPACE 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(*args, **kargs)[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) #doctest: +NORMALIZE_WHITESPACE [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 #doctest: +NORMALIZE_WHITESPACE [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 #doctest: +NORMALIZE_WHITESPACE [Centoid(2.500000, 2.500000),

Centoid(3.500000, 3.500000)]
>>> test_vect.find_by_point.geos(point=Point(20,20), maxdist=0)
>>> test_vect.close()
island(*args, **kargs)[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()) #doctest: +NORMALIZE_WHITESPACE 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(*args, **kargs)[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=None, writeable=False)[source]

Bases: pygrass.vector.find.AbstractFinder

areas(polygon, isles=None)[source]
lines(polygon, isles=None)[source]

pygrass.vector.geometry module

Created on Wed Jul 18 10:46:25 2012

@author: pietro

class pygrass.vector.geometry.Area(**kargs)[source]

Bases: pygrass.vector.geometry.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

alive(*args, **kargs)[source]

Check if area is alive or dead (topology required)

area(*args, **kargs)[source]

Returns area of area without areas of isles. double Vect_get_area_area (const struct Map_info *Map, int area)

bbox(*args, **kargs)[source]

Return the Bbox of area

Parameters:bbox (a Bbox object) – a Bbox object to fill with info from bounding box of area
boundaries(*args, **kargs)[source]

Creates list of boundaries for given area.

int Vect_get_area_boundaries(const struct Map_info *Map,
int area, struct ilist *List)
buffer(*args, **kargs)[source]

Return the buffer area around the area, using the Vect_area_buffer2 C function.

Parameters:
  • dist (num) – the distance around the area
  • dist_x (num) – the distance along x
  • dist_y (num) – the distance along y
  • angle (num) – the angle between 0x and major axis
  • round (bool) – to make corners round
  • tol (float) – fix the maximum distance between theoretical arc and output segments
Returns:

the buffer as line, centroid, isles object tuple

cat[source]
cats(*args, **kargs)[source]

Get area categories.

Parameters:cats (a Cats object) – a Cats object to fill with info with area categories
centroid(*args, **kargs)[source]

Return the centroid

Parameters:centroid (a Centroid object) – a Centroid object to fill with info from centroid of area
contains_point(*args, **kargs)[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
isles(*args, **kargs)[source]

Return a list of islands located in this area

num_isles(*args, **kargs)[source]
perimeter(*args, **kargs)[source]

Calculate area perimeter.

Returns:double Vect_area_perimeter (const struct line_pnts *Points)
points(*args, **kargs)[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]
to_wkb()[source]

Return a “well know binary” (WKB) area byte array, this method uses the GEOS implementation in the vector library.

to_wkt()[source]

Return a “well know text” (WKT) area string, this method uses the GEOS implementation in the vector library.

class pygrass.vector.geometry.Attrs(cat, table, writeable=False)[source]

Bases: object

cat

Set and obtain cat value

commit()[source]

Save the changes

keys()[source]

Return the column name of the attribute table.

>>> from grass.pygrass.vector import VectorTopo
>>> test_vect = VectorTopo(test_vector_name)
>>> test_vect.open('r')
>>> v1 = test_vect[1]
>>> v1.attrs.keys()
[u'cat', u'name', u'value']
 >>> test_vect.close()
values()[source]

Return the values of the attribute table row.

>>> from grass.pygrass.vector import VectorTopo
>>> test_vect = VectorTopo(test_vector_name)
>>> test_vect.open('r')
>>> v1 = test_vect[1]
>>> v1.attrs.values()
(1, u'point', 1.0)
 >>> test_vect.close()
class pygrass.vector.geometry.Boundary(**kargs)[source]

Bases: pygrass.vector.geometry.Line

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
left_area_id[source]

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
read_area_ids(*args, **kargs)[source]

Read and return left and right area ids of the boundary

right_area_id[source]

Right side area id, only available after read_area_ids() was called

right_centroid(idonly=False)[source]

Return right centroid

Parameters:idonly (bool) – True to return only the cat of feature
class pygrass.vector.geometry.Centroid(area_id=None, **kargs)[source]

Bases: pygrass.vector.geometry.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
Centoid(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
Centoid(3.500000, 3.500000)
>>> test_vect.close()
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

cat[source]
gtype = None
has_topology()[source]
read(*args, **kargs)[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

to_wkb()[source]

Return a “well know binary” (WKB) geometry byte array, this method uses the GEOS implementation in the vector library.

>>> pnt = Point(10, 100)
>>> wkb = pnt.to_wkb()
>>> len(wkb)
21
to_wkt()[source]

Return a “well know text” (WKT) geometry string, this method uses the GEOS implementation in the vector library.

>>> pnt = Point(10, 100)
>>> pnt.to_wkt()
'POINT (10.0000000000000000 100.0000000000000000)'
class pygrass.vector.geometry.Isle(**kargs)[source]

Bases: pygrass.vector.geometry.Geo

An Isle is an area contained by another area.

alive(*args, **kargs)[source]

Check if isle is alive or dead (topology required)

area()[source]

Return the area value of an Isle

area_id(*args, **kargs)[source]

Returns area id for isle.

bbox(*args, **kargs)[source]

Return bounding box of Isle

boundaries(*args, **kargs)[source]

Return a list of boundaries

contain_pnt(*args, **kargs)[source]

Check if point is in area.

Parameters:pnt (a Point object or a tuple with the coordinates) – the point to remove
perimeter()[source]

Return the perimeter value of an Isle.

points(*args, **kargs)[source]

Return a Line object with the outer ring points

points_geos(*args, **kargs)[source]

Return a Line object with the outer ring points

to_wkb()[source]

Return a “well know text” (WKB) geometry array.

to_wkt()[source]

Return a Well Known Text string of the isle.

For now the outer ring is returned

TODO: Implement inner rings detected from isles

class pygrass.vector.geometry.Isles(c_mapinfo, area_id=None)[source]

Bases: object

isles(*args, **kargs)[source]

Return isles

isles_ids(*args, **kargs)[source]

Return the id of isles

class pygrass.vector.geometry.Line(points=None, **kargs)[source]

Bases: pygrass.vector.geometry.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)])
alive(*args, **kargs)[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 – the point to add to line

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:
  • dist (num) – the distance around the line
  • dist_x (num) – the distance along x
  • dist_y (num) – the distance along y
  • angle (num) – the angle between 0x and major axis
  • round (bool) – to make corners round
  • tol (float) – fix the maximum distance between theoretical arc and output segments
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 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 object ot list of points) – it is possible to extend a line, give a list of points, or directly with a line_pnts struct.
  • forward – if forward is True the line is extend forward otherwise is extend backward. The method use the Vect_append_points C function.
first_cat(*args, **kargs)[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 – the WKT string containing the LINESTRING
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 – the point to add
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, usig Vect_line_geodesic_length C function.

>>> line = Line([(0, 0), (1, 1), (0, 1)])
>>> line.length_geodesic()
2.414213562373095
nodes(*args, **kargs)[source]

Return the start and end nodes of the line

This method requires topology build.

return: 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. 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)
Traceback (most recent call last):
    ...
ValueError: The distance exceed the length of the line,
pop(indx)[source]

Return the point in the index position and remove from the Line.

Parameters:indx – the index where add new point
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 – the threshold value where prune points

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 – the point to remove
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:
  • start (float) – distance from the beginning of the line where the segment start
  • end (float) – distance from the beginning of the line where the segment end
::

# 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.]])
to_list()[source]

Return a list of tuple.

>>> line = Line([(0, 0), (1, 1), (2, 0), (1, -1)])
>>> line.to_list()
[(0.0, 0.0), (1.0, 1.0), (2.0, 0.0), (1.0, -1.0)]
to_wkt_p()[source]

Return a Well Known Text string of the line.

>>> line = Line([(0, 0), (1, 1), (1, 2)])
>>> line.to_wkt_p()                 
'LINESTRING(0.000000 0.000000, ..., 1.000000 2.000000)'
class pygrass.vector.geometry.LineDist

Bases: tuple

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.

alive(*args, **kargs)[source]

Return True if this node is alive or False if this node is dead or its index is out of range.

angles(*args, **kargs)[source]

Return a generator with all lines angles in a node.

coords(*args, **kargs)[source]

Return a tuple with the node coordinates.

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.

Parameters:
  • only_in (bool) – Return only the lines that are ending in the node
  • only_out (bool) – Return only the lines that are starting in the node
lines(*args, **kargs)[source]

Return a generator with all lines connected to a node.

Parameters:
  • only_in (bool) – Return only the lines that are ending in the node
  • only_out (bool) – Return only the lines that are starting in the node
to_wkb()[source]

Return a “well know binary” (WKB) geometry array.

TODO: Must be implemented

to_wkt()[source]

Return a “well know text” (WKT) geometry string.

class pygrass.vector.geometry.Point(x=0, y=0, z=None, **kargs)[source]

Bases: pygrass.vector.geometry.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
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:
  • dist (num) – the distance around the point
  • dist_x (num) – the distance along x
  • dist_y (num) – the distance along y
  • angle (num) – the angle between 0x and major axis
  • round (bool) – to make corners round
  • tol (float) – fix the maximum distance between theoretical arc and output segments
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.
>>> 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 – the point for calculate the distance
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 and POINT with: XYZM are not supported yet.

x

Set and obtain x coordinate

y

Set and obtain y coordinate

z

Set and obtain z coordinate

pygrass.vector.geometry.c_read_line(feature_id, c_mapinfo, c_points, c_cats)[source]
pygrass.vector.geometry.c_read_next_line(c_mapinfo, c_points, c_cats)[source]
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)
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_WKB(buff)[source]

Read the binary buffer and return a geometry object

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.geometry.read_line(feature_id, c_mapinfo, table=None, writeable=False, c_points=None, c_cats=None, is2D=True)[source]

Return a geometry object given the feature id and the c_mapinfo.

pygrass.vector.geometry.read_next_line(c_mapinfo, table=None, writeable=False, c_points=None, c_cats=None, is2D=True)[source]

Return the next geometry feature of a vector map.

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=u'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
>>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'
>>> cols_sqlite = Columns(test_vector_name,
...                       sqlite3.connect(get_path(path)))
>>> cols_sqlite.tname
u'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.

Parameters:
  • col_name (str) – the name of column to add
  • col_type (str) – the tipe of column to add
>>> import sqlite3
>>> 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.

Parameters:
  • col_name (str) – the name of column
  • new_type (str) – the new type of column
>>> import sqlite3
>>> 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):
  ...
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')
Traceback (most recent call last):
  ...
DBError: SQLite does not support to cast columns.

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
>>> 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
>>> 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
>>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'
>>> cols_sqlite = Columns(test_vector_name,
...                       sqlite3.connect(get_path(path)))
>>> cols_sqlite.items()                       
[(u'cat', u'INTEGER'), (u'name', u'varchar(50)'), (u'value', u'double precision')]
>>> import psycopg2 as pg                         
>>> cols_pg = Columns(test_vector_name,
...                   pg.connect('host=localhost dbname=grassdb')) 
>>> cols_pg.items()                     
[(u'cat', u'INTEGER'), (u'name', u'varchar(50)'), (u'value', u'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
>>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'
>>> cols_sqlite = Columns(test_vector_name,
...                       sqlite3.connect(get_path(path)))
>>> cols_sqlite.names()                      
[u'cat', u'name', u'value']
>>> import psycopg2 as pg                         
>>> cols_pg = Columns(test_vector_name,       
...                   pg.connect('host=localhost dbname=grassdb'))
>>> cols_pg.names()                     
[u'cat', u'name', u'value']
rename(old_name, new_name)[source]

Rename a column of the table.

Parameters:
  • old_name (str) – the name of existing column
  • new_name (str) – the name of new column
>>> import sqlite3
>>> 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
>>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'
>>> cols_sqlite = Columns(test_vector_name,
...                       sqlite3.connect(get_path(path)))
>>> cols_sqlite.sql_descr()                   
u'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()                 
u'cat INTEGER, name varchar(50), value double precision'
types()[source]

Return a list with the column types.

>>> import sqlite3
>>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'
>>> cols_sqlite = Columns(test_vector_name,
...                       sqlite3.connect(get_path(path)))
>>> cols_sqlite.types()                       
[u'INTEGER', u'varchar(50)', u'double precision']
>>> import psycopg2 as pg                         
>>> cols_pg = Columns(test_vector_name,
...                   pg.connect('host=localhost dbname=grassdb')) 
>>> cols_pg.types()                     
[u'INTEGER', u'varchar(50)', u'double precision']
update_odict()[source]

Read columns name and types from table and update the odict attribute.

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
from_name_to_num(name)[source]

Vect_get_field_number

Return the number of DBlinks

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()
u'SELECT * FROM table;'
>>> filter.where("area<10000").get_sql()
u'SELECT * FROM table WHERE area<10000;'
>>> filter.select("cat", "area").get_sql()
u'SELECT cat, area FROM table WHERE area<10000;'
>>> filter.order_by("area").limit(10).get_sql()
u'SELECT cat, area FROM table WHERE area<10000 ORDER BY area LIMIT 10;'
get_sql()[source]

Return the SQL query

group_by(*groupby)[source]

Create the group by condition

Parameters:groupby (str, list) – the name of column/s to group the result
limit(number)[source]

Create the limit condition

Parameters:number (int) – the number to limit the result
order_by(*orderby)[source]

Create the order by condition

Parameters:orderby (str) – the name of column/s to order the result
reset()[source]

Clean internal variables

select(*args)[source]

Create the select query

where(condition)[source]

Create the where condition

Parameters:condition (str) – the condition of where statement, for example cat = 1

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.
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, u'point', 1.0)
>>> cur.close()
>>> conn.close()
database

Set and obtain database value

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
key

Set and obtain cat value

layer

Set and obtain layer number

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(u'SELECT cat, name, value FROM table_doctest_map;')
>>> cur = table.execute()
>>> cur.fetchone()
(1, u'point', 1.0)
>>> cur.close()
table_name

Set and obtain table name value

class pygrass.vector.table.Table(name, connection, key=u'cat')[source]

Bases: object

>>> import sqlite3
>>> path = '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
>>> tab_sqlite = Table(name=test_vector_name,
...                    connection=sqlite3.connect(get_path(path)))
>>> tab_sqlite.name
u'table_doctest_map'
>>> import psycopg2                                   
>>> tab_pg = Table(test_vector_name,
...                psycopg2.connect('host=localhost dbname=grassdb',
...                                 'pg'))            
>>> tab_pg.columns                          
Columns([('cat', 'int4'), ...])
create(cols, name=None, overwrite=False, cursor=None)[source]

Create a new table

Parameters:
  • cols
  • name (str) – the name of table to create, None for the name of Table object
  • overwrite (bool) – overwrite existing table
  • cursor (Cursor object) – the cursor to connect, if None it use the cursor of connection table object
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:
  • sql_code (str) – the SQL code to execute, if not pass it use filters variable
  • cursor (Cursor object) – the cursor to connect, if None it use the cursor of connection table object
  • many (bool) – True to run executemany function
  • values (list of tuple) – The values to substitute into sql_code string
>>> import sqlite3
>>> 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(u'SELECT cat, name FROM table_doctest_map ORDER BY value;')
>>> cur = tab_sqlite.execute()
>>> cur.fetchone()     
 (1, u'point')
exist(cursor=None)[source]

Return True if the table already exist in the DB, False otherwise

Parameters:cursor – the cursor to connect, if None it use the cursor of connection table object
insert(values, cursor=None, many=False)[source]

Insert a new row

Parameters:
  • values (tuple) – a tuple of values to insert, it is possible to insert more rows using a list of tuple and parameter many
  • cursor (Cursor object) – the cursor to connect, if None it use the cursor of connection table object
  • many (bool) – True to run executemany function
n_rows()[source]

Return the number of rows

>>> import sqlite3
>>> 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
name

Set and obtain table name

update(key, values, cursor=None)[source]

Update a table row

Parameters:
  • key (int) – the rowid
  • values (list) – the values to insert without row id. For example if we have a table with four columns: cat, c0, c1, c2 the values list should containing only c0, c1, c2 values.
  • cursor (Cursor object) – the cursor to connect, if None it use the cursor of connection table object
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: grass.pygrass.vector.abstract.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(*args, **kargs)[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')
next(*args, **kargs)[source]
>>> test_vect = Vector(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.close()
rewind(*args, **kargs)[source]

Rewind vector map to cause reads to start at beginning.

write(*args, **kargs)[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 insert 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 = [(u'cat',       'INTEGER PRIMARY KEY'),
...         (u'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=('resturant',))

commit the db changes

>>> new.table.conn.commit()
>>> new.table.execute().fetchall()
[(1, u'pub'), (2, u'resturant')]

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']
u'pub'
>>> new.read(2).attrs['name']
u'resturant'
>>> new.close()
>>> new.remove()
class pygrass.vector.VectorTopo(name, mapset='', *args, **kwargs)[source]

Bases: pygrass.vector.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(*args, **kargs)[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()
bbox(*args, **kargs)[source]

Return the BBox of the vecor map

cat(*args, **kargs)[source]

Return the geometry features with category == cat_id.

Parameters:
  • cat_id (int) – the category number
  • vtype (str) – the type of geometry feature that we are looking for
  • layer (int) – the layer number that will be used
  • generator (bool) – if True return a generator otherwise it return a list of features
close(build=True, release=True)[source]

Close the VectorTopo map, if release is True, the memory occupied by spatial index is released

delete(*args, **kargs)[source]

Remove a feature by its id

Parameters:feature_id (int) – the id of the feature
features_to_wkb_list(*args, **kargs)[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
    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):
...
GrassError: Unsupported feature type <blub>, supported are <point,line,boundary,centroid>
Traceback (most recent call last):
...
GrassError: Unsupported feature type <blub>, supported are <point,line,boundary,centroid>
>>> test_vect.close()
is_empty(*args, **kargs)[source]

Return if a vector map is empty or not

num_primitive_of(*args, **kargs)[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()
num_primitives(*args, **kargs)[source]

Return dictionary with the number of all primitives

number_of(*args, **kargs)[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, line_points, lines, nodes, points, update_lines, update_nodes, volumes
read(*args, **kargs)[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)
Centoid(7.500000, 3.500000)
>>> len(test_vect)
21
>>> test_vect.read(21)
Centoid(7.500000, 3.500000)
>>> test_vect.read(22)                             
Traceback (most recent call last):
  ...
IndexError: Index out of range
>>> test_vect.close()
Traceback (most recent call last):
  ...
IndexError: Index out of range
restore(*args, **kargs)[source]
rewind(*args, **kargs)[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(*args, **kargs)[source]

Rewrite a geometry features

>>> cols = [(u'cat',       'INTEGER PRIMARY KEY'),
...         (u'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=('resturant',))
>>> test_vect.table.conn.commit()  # save changes in the DB
>>> test_vect.table_to_dict()
{1: [1, u'pub'], 2: [2, u'resturant']}
>>> 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(*args, **kargs)[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, u'point', 1.0], 2: [2, u'line', 2.0], 3: [3, u'centroid', 3.0]}
>>> test_vect.table_to_dict(where="value > 2")
{3: [3, u'centroid', 3.0]}
>>> test_vect.table_to_dict(where="value > 0")
{1: [1, u'point', 1.0], 2: [2, u'line', 2.0], 3: [3, u'centroid', 3.0]}
>>> test_vect.table.filters.get_sql()
u'SELECT cat,name,value FROM vector_doctest_map WHERE value > 0 ORDER BY cat;'
viter(*args, **kargs)[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 a 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()

Help Index | Topics Index | Keywords Index | Full Index

© 2003-2017 GRASS Development Team, GRASS GIS 7.5.svn Reference Manual