Note: A new GRASS GIS stable version has been released: GRASS GIS 7.4. Go directly to the new manual page here
Created on Fri Aug 17 17:24:03 2012
@author: pietro
Bases: object
Basic vector info. To get access to the vector info the map must be opened.
>>> cens = Info('census')
>>> cens.open(mode='r')
Then it is possible to read and write the following map attributes:
>>> cens.organization
'NC OneMap'
>>> cens.person
'hmitaso'
>>> cens.title
'Wake County census blocks with attributes, clipped (polygon map)'
>>> cens.map_date
datetime.datetime(2007, 3, 19, 22, 1, 37)
>>> cens.date
''
>>> cens.scale
1
>>> cens.comment
''
>>> cens.comment = "One useful comment!"
>>> cens.comment
'One useful comment!'
>>> cens.zone
0
>>> cens.proj
99
There are some read only attributes:
>>> cens.full_name
'census@PERMANENT'
>>> cens.proj_name
'Lambert Conformal Conic'
>>> cens.maptype
'native'
And some basic methods:
>>> cens.is_3D()
False
>>> cens.exist()
True
>>> cens.is_open()
True
>>> cens.close()
Method to close the Vector
Parameters: | build (bool) – True if the vector map should be build before close it |
---|
Set or obtain the Vector comment
Set or obtain the Vector date
Set or obtain the Vector map date
Set or obtain the Vector mapset
Set or obtain the Vector name
Open a Vector map.
Parameters: |
|
---|
Some of the parameters are valid only with mode w or rw
See more examples in the documentation of the read and write methods
Set or obtain the Vector organization
Set or obtain the Vector author
Set or obtain the Vector projection code
Method to rename the Vector map
Parameters: | newname (str) – the new name for the Vector map |
---|
Set or obtain the Vector scale
Set or obtain the Vector threshold
Set or obtain the Vector title
Set or obtain the Vector projection zone
Created on Tue Jul 31 13:06:20 2012
@author: pietro
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)
Set and obtain bottom value
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
Set and obtain east value
Set and obtain north value
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 |
---|
Set and obtain south value
Set and obtain top value
Set and obtain west value
Bases: object
Instantiate a BoxList class to create a list of Bounding Box
Append a Bbox object to a Boxlist object, using the Vect_boxlist_append C fuction.
Parameters: |
|
---|
>>> 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
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: |
|
---|
>>> 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)])
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
[]
Check if categories match with category constraints
Parameters: |
|
---|
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: |
|
---|
Return the first found category of given layer and the number of category found.
Parameters: | layer (int) – the number of layer |
---|
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
Convert ordered array of integers to cat_list structure.
Parameters: | array (array) – the input array containing the cats |
---|
Bases: object
Instantiate a list of integer using the C GRASS struct ilist, the class contains this struct as c_ilist attribute.
Created on Tue Mar 19 11:09:30 2013
@author: pietro
Bases: object
Bases: pygrass.vector.find.AbstractFinder
PointFinder
Find the geomtry features of a vector map that are close to a point.
>>> from grass.pygrass.vector import VectorTopo
>>> zipcodes = VectorTopo('zipcodes', 'PERMANENT')
>>> schools = VectorTopo('schools', 'PERMANENT')
>>> zipcodes.open('r')
>>> schools.open('r')
>>> result = []
>>> for school in schools:
... zipcode = zipcodes.find['by_point'].area(school)
... result.append((school.attrs['NAMESHORT'],
... zipcode.attrs['ZIPCODE']))
...
>>> result[0]
(u'SWIFT CREEK', u'RALEIGH 27606')
>>> result[1]
(u'BRIARCLIFF', u'CARY 27511')
>>> result[2]
(u'FARMINGTON WOODS', u'CARY 27511')
>>> from grass.pygrass.vector.geometry import Point
>>> pnt = Point(631213.349291, 224684.900084)
>>> school = schools.find['by_point'].geo(pnt, maxdist=300.)
>>> school.attrs['NAMELONG']
u'ADAMS ELEMENTARY'
>>> for school in schools.find['by_point'].geos(pnt, maxdist=1000.):
... print school.attrs['NAMELONG']
...
CARY HIGH
EAST CARY MIDDLE SITE
ADAMS ELEMENTARY
>>> schools.close()
>>> zipcodes.close()
Find the nearest line. Vect_find_line
Valid type are all the keys in find.vtype dictionary
Created on Wed Jul 18 10:46:25 2012
@author: pietro
Bases: pygrass.vector.geometry.Geo
Vect_build_line_area, Vect_find_area, Vect_get_area_box, Vect_get_area_points_geos, Vect_get_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
Returns area of area without areas of isles. double Vect_get_area_area (const struct Map_info *Map, int area)
Return the Bbox of area
Parameters: | bbox (a Bbox object) – a Bbox object to fill with info from bounding box of area |
---|
Creates list of boundaries for given area.
Return the buffer area around the area, using the Vect_area_buffer2 C function.
Parameters: |
|
---|---|
Returns: | the buffer as Area object |
Get area categories.
Parameters: | cats (a Cats object) – a Cats object to fill with info with area categories |
---|
Check if point is in area.
Parameters: |
|
---|
Return the centroid
Parameters: | centroid (a Centroid object) – a Centroid object to fill with info from centroid of area |
---|
Find FIRST category of given field and area.
int Vect_get_area_cat(const struct Map_info *Map, int area, int field)
Return a Line object with the outer ring
Parameters: | line (a Line object) – a Line object to fill with info from points of area |
---|
Bases: object
Set and obtain cat value
Return the column name of the attribute table. >>> from grass.pygrass.vector import VectorTopo >>> schools = VectorTopo(‘schools’) >>> schools.open(‘r’) >>> school = schools[1] >>> attrs = Attrs(school.cat, schools.table) >>> attrs.keys() # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE [u’cat’, ... u’NOTES’]
Return the values of the attribute table row. >>> from grass.pygrass.vector import VectorTopo >>> schools = VectorTopo(‘schools’) >>> schools.open(‘r’) >>> school = schools[1] >>> attrs = Attrs(school.cat, schools.table) >>> attrs.values() # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE (1, ... None)
Bases: pygrass.vector.geometry.Line
Return the area of the polygon.
>>> bound = Boundary(points=[(0, 0), (0, 2), (2, 2), (2, 0),
... (0, 0)])
>>> bound.area()
4.0
Return left value
Parameters: | idonly (bool) – True to return only the cat of feature |
---|
Return right value
Parameters: | idonly (bool) – True to return only the cat of feature |
---|
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
>>> geo = VectorTopo('geology')
>>> geo.open(mode='r')
>>> centroid = Centroid(v_id=1, c_mapinfo=geo.c_mapinfo)
>>> centroid
Centoid(893202.874416, 297339.312795)
Return the area_id, using the c_mapinfo and an centroid_id attributes of the class, and calling the Vect_get_centroid_area C function, if no area_id were found return None
Return the centroid_id, using the c_mapinfo and an area_id attributes of the class, and calling the Vect_get_area_centroid C function, if no centroid_id were found return None
Bases: object
>>> geo0 = Geo()
>>> points = ctypes.pointer(libvect.line_pnts())
>>> cats = ctypes.pointer(libvect.line_cats())
>>> geo1 = Geo(c_points=points, c_cats=cats)
Bases: pygrass.vector.geometry.Geo
An Isle is an area contained by another area.
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)])
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.
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)
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)])
>>> area = line.buffer(10)
>>> area.boundary
Line([Point(-10.000000, 0.000000),...Point(-10.000000, 0.000000)])
>>> area.centroid
Point(0.000000, 0.000000)
>>> area.isles
[]
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)])
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)
Appends points to the end of a line.
Parameters: |
|
---|
Create a line reading a WKT string.
Parameters: | wkt – the WKT string containing the LINESTRING |
---|
Fetches FIRST category number for given vector line and field, using the Vect_get_line_cat C function.
Warning
Not implemented yet.
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.get_pnt(5)
Traceback (most recent call last):
...
ValueError: The distance exceed the length of the line,
that is: 1.414214
>>> line.get_pnt(1)
Point(0.707107, 0.707107)
Traceback (most recent call last):
...
ValueError: The distance exceed the length of the line,
Return a Well Known Text string of the line.
>>> line = Line([(0, 0), (1, 1), (1, 2)])
>>> line.get_wkt()
'LINESTRING(0.000000 0.000000, ..., 1.000000 2.000000)'
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: |
|
---|
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
Calculate line length, usig Vect_line_geodesic_length C function.
>>> line = Line([(0, 0), (1, 1), (0, 1)])
>>> line.length_geodesic()
2.414213562373095
Return the point in the index position and remove from the Line.
Parameters: | indx – the index where add new point |
---|
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)])
Remove points in threshold, using the Vect_line_prune_thresh C funtion.
Parameters: | threshold – the threshold value where prune points |
---|
Warning
prune_thresh is not working yet.
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 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 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)])
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)])
Bases: tuple
LineDist(point, dist, spdist, sldist)
Alias for field number 1
Alias for field number 0
Alias for field number 3
Alias for field number 2
Bases: object
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: |
|
---|
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(0.000000 0.000000 0.000000)
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)
>>> area = pnt.buffer(10)
>>> area.boundary
Line([Point(10.000000, 0.000000),...Point(10.000000, 0.000000)])
>>> area.centroid
Point(0.000000, 0.000000)
>>> area.isles
[]
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)
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 |
---|
Return a “well know text” (WKT) geometry string.
>>> pnt = Point(10, 100)
>>> pnt.get_wkt()
'POINT(10.000000 100.000000)'
Warning
Only POINT (2/3D) are supported, POINTM and POINT with: XYZM are not supported yet.
Set and obtain x coordinate
Set and obtain y coordinate
Set and obtain z coordinate
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)
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)])
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)) )
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;'
Created on Wed Aug 8 15:29:21 2012
@author: pietro
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/PERMANENT/sqlite/sqlite.db'
>>> cols_sqlite = Columns('census',
... sqlite3.connect(get_path(path)))
>>> cols_sqlite.tname
u'census'
For a postgreSQL table:
>>> import psycopg2 as pg
>>> cols_pg = Columns('boundary_municp_pg',
... pg.connect('host=localhost dbname=grassdb'))
>>> cols_pg.tname
'boundary_municp_pg'
Add a new column to the table.
Parameters: |
|
---|
>>> import sqlite3
>>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'
>>> from grass.pygrass.utils import copy, remove
>>> copy('census','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')
Change the column type.
Parameters: |
|
---|
>>> import sqlite3
>>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'
>>> from grass.pygrass.utils import copy, remove
>>> copy('census','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('boundary_municp_pg',
... 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 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('census','mycensus','vect')
>>> cols_sqlite = Columns('mycensus',
... sqlite3.connect(get_path(path)))
>>> cols_sqlite.drop('CHILD')
>>> 'CHILD' in cols_sqlite
False
>>> import psycopg2 as pg
>>> cols_pg = Columns('boundary_municp_pg',
... pg.connect('host=localhost dbname=grassdb'))
>>> cols_pg.drop('CHILD')
>>> 'CHILD' in cols_pg
False
>>> remove('mycensus','vect')
Return True if is a psycopg connection.
>>> import sqlite3
>>> path = '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
>>> cols_sqlite = Columns('census',
... sqlite3.connect(get_path(path)))
>>> cols_sqlite.is_pg()
False
>>> import psycopg2 as pg
>>> cols_pg = Columns('boundary_municp_pg',
... pg.connect('host=localhost dbname=grassdb'))
>>> cols_pg.is_pg()
True
Return a list of tuple with column name and column type.
>>> import sqlite3
>>> path = '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
>>> cols_sqlite = Columns('census',
... sqlite3.connect(get_path(path)))
>>> cols_sqlite.items()
[(u'cat', u'integer'), ...]
>>> import psycopg2 as pg
>>> cols_pg = Columns('boundary_municp_pg',
... pg.connect('host=localhost dbname=grassdb'))
>>> cols_pg.items()
[('cat', 'int4'), ('objectid', 'int4'), ('area', 'float8'), ...]
Return a list with the column names. Remove it is used to remove a columns.
>>> import sqlite3
>>> path = '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
>>> cols_sqlite = Columns('census',
... sqlite3.connect(get_path(path)))
>>> cols_sqlite.names()
[u'cat', u'OBJECTID', u'AREA', u'PERIMETER', ...]
>>> import psycopg2 as pg
>>> cols_pg = Columns('boundary_municp_pg',
... pg.connect('host=localhost dbname=grassdb'))
>>> cols_pg.names()
['cat', 'objectid', 'area', 'perimeter', ...]
Rename a column of the table.
Parameters: |
|
---|
>>> import sqlite3
>>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'
>>> from grass.pygrass.utils import copy, remove
>>> copy('census','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('boundary_municp_pg',
... 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')
Return a string with description of columns. Remove it is used to remove a columns.
>>> import sqlite3
>>> path = '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
>>> cols_sqlite = Columns('census',
... sqlite3.connect(get_path(path)))
>>> cols_sqlite.sql_descr()
u'cat integer, OBJECTID integer, AREA double precision, ...'
>>> import psycopg2 as pg
>>> cols_pg = Columns('boundary_municp_pg',
... pg.connect('host=localhost dbname=grassdb'))
>>> cols_pg.sql_descr()
'cat int4, objectid int4, area float8, perimeter float8, ...'
Return a list with the column types.
>>> import sqlite3
>>> path = '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
>>> cols_sqlite = Columns('census',
... sqlite3.connect(get_path(path)))
>>> cols_sqlite.types()
[u'integer', u'integer', ...]
>>> import psycopg2 as pg
>>> cols_pg = Columns('boundary_municp_pg',
... pg.connect('host=localhost dbname=grassdb'))
>>> cols_pg.types()
['int4', 'int4', 'float8', 'float8', 'float8', ...]
Bases: object
Interface containing link to the table DB.
>>> from grass.pygrass.vector import VectorTopo
>>> cens = VectorTopo('census')
>>> cens.open(mode='r')
>>> dblinks = DBlinks(cens.c_mapinfo)
>>> dblinks
DBlinks([Link(1, census, sqlite)])
>>> dblinks[0]
Link(1, census, sqlite)
>>> dblinks['census']
Link(1, census, sqlite)
>>> cens.close()
Add a new link. Need to open vector map in write mode
Parameters: | link – the Link to add to the DBlinks |
---|
Return a Link object by index
Parameters: | indx (int) – the index where add new point |
---|
Return the choosen Link using the layer
Parameters: | layer (int) – the number of layer |
---|
Return the choosen Link using the name
Parameters: | name (str) – the name of Link |
---|
Remove a link. If force set to true remove also the table
Parameters: |
|
---|
>>> from grass.pygrass.vector import VectorTopo
>>> municip = VectorTopo('census')
>>> municip.open(mode='r')
>>> dblinks = DBlinks(municip.c_mapinfo)
>>> dblinks
DBlinks([Link(1, census, sqlite)])
>>> dblinks.remove('pg_link')
>>> dblinks # need to open vector map in write mode
DBlinks([Link(1, census, sqlite)])
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;'
Create the group by condition
Parameters: | groupby (str, list) – the name of column/s to group the result |
---|
Create the limit condition
Parameters: | number (int) – the number to limit the result |
---|
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', 'census', 'cat',
... '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db', 'sqlite')
>>> link.layer
1
>>> link.name
'link0'
>>> link.table_name
'census'
>>> link.key
'cat'
>>> link.database
'$GISDBASE/$LOCATION_NAME/PERMANENT/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()))
Return a connection object.
>>> link = Link(1, 'link0', 'census', 'cat',
... '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db',
... 'sqlite')
>>> conn = link.connection()
>>> cur = conn.cursor()
>>> cur.execute("SELECT cat,TOTAL_POP,PERIMETER FROM %s" %
... link.table_name)
<sqlite3.Cursor object at ...>
>>> cur.fetchone()
(1, 44, 757.669)
>>> cur.close()
>>> conn.close()
Set and obtain database value
Set and obtain driver value. The drivers supported by PyGRASS are: SQLite and PostgreSQL
Print information of the link.
>>> link = Link(1, 'link0', 'census', 'cat',
... '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db',
... 'sqlite')
>>> link.info()
layer: 1
name: link0
table: census
key: cat
database: $GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db
driver: sqlite
Set and obtain cat value
Set and obtain layer number
Set and obtain name vale
Return a Table object.
>>> link = Link(1, 'link0', 'census', 'cat',
... '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db',
... 'sqlite')
>>> table = link.table()
>>> table.filters.select('cat', 'TOTAL_POP', 'PERIMETER')
Filters(u'SELECT cat, TOTAL_POP, PERIMETER FROM census;')
>>> cur = table.execute()
>>> cur.fetchone()
(1, 44, 757.669)
>>> cur.close()
Set and obtain table name value
Bases: object
>>> import sqlite3
>>> path = '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
>>> tab_sqlite = Table(name='census',
... connection=sqlite3.connect(get_path(path)))
>>> tab_sqlite.name
u'census'
>>> import psycopg2
>>> tab_pg = Table('boundary_municp_pg',
... psycopg2.connect('host=localhost dbname=grassdb',
... 'pg'))
>>> tab_pg.columns
Columns([('cat', 'int4'), ...])
Create a new table
Parameters: |
|
---|
Method to drop table from database
Parameters: |
|
---|
Execute SQL code from a given string or build with filters and return a cursor object.
Parameters: |
|
---|
>>> import sqlite3
>>> path = '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
>>> tab_sqlite = Table(name='census',
... connection=sqlite3.connect(get_path(path)))
>>> tab_sqlite.filters.select('cat', 'TOTAL_POP').order_by('AREA')
Filters(u'SELECT cat, TOTAL_POP FROM census ORDER BY AREA;')
>>> cur = tab_sqlite.execute()
>>> cur.fetchone()
(1856, 0)
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 a new row
Parameters: |
|
---|
Return the number of rows
>>> import sqlite3
>>> path = '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
>>> tab_sqlite = Table(name='census',
... connection=sqlite3.connect(get_path(path)))
>>> tab_sqlite.n_rows()
2537
Set and obtain table name
Update a table row
Parameters: |
|
---|
Return the full path to the database; replacing environment variable with real values
>>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'
>>> new_path = get_path(path)
>>> from grass.script.core import gisenv
>>> import os
>>> new_path2 = os.path.join(gisenv()['GISDBASE'], gisenv()['LOCATION_NAME'],
... gisenv()['MAPSET'], 'sqlite', 'sqlite.db')
>>> new_path == new_path2
True
Bases: grass.pygrass.vector.abstract.Info
Vector class is the grass vector format without topology
>>> from grass.pygrass.vector import Vector
>>> cens = Vector('census')
>>> cens.is_open()
False
>>> cens.mapset
''
>>> cens.exist()
True
>>> cens.mapset
'PERMANENT'
>>> cens.overwrite
False
Return if vector has color table associated in file system; Color table stored in the vector’s attribute table well be not checked
>>> cens = Vector('census')
>>> cens.open(mode='r')
>>> cens.has_color_table()
False
>>> cens.close()
>>> from grass.pygrass.utils import copy, remove
>>> copy('census','mycensus','vect')
>>> from grass.pygrass.modules.shortcuts import vector as v
>>> v.colors(map='mycensus', color='population', column='TOTAL_POP')
Module('v.colors')
>>> mycens = Vector('mycensus')
>>> mycens.open(mode='r')
>>> mycens.has_color_table()
True
>>> mycens.close()
>>> remove('mycensus', 'vect')
>>> cens = Vector('census')
>>> cens.open(mode='r')
>>> cens.next()
Boundary(v_id=None)
>>> cens.next()
Boundary(v_id=None)
>>> cens.close()
Write geometry features and attributes.
Parameters: |
|
---|
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(636981.336043, 256517.602235)
>>> point1 = Point(637209.083058, 257970.129540)
then write the two points on the map, with
>>> new.write(point0, ('pub', ))
>>> new.write(point1, ('resturnat', ))
commit the db changes
>>> new.table.conn.commit()
>>> new.table.execute().fetchall()
[(1, u'pub'), (2, u'resturnat')]
close the vector map
>>> new.close()
>>> new.exist()
True
then play with the map
>>> new.open(mode='r')
>>> new.read(1)
Point(636981.336043, 256517.602235)
>>> new.read(2)
Point(637209.083058, 257970.129540)
>>> new.read(1).attrs['name']
u'pub'
>>> new.read(2).attrs['name']
u'resturnat'
>>> new.close()
>>> new.remove()
Bases: pygrass.vector.Vector
Vector class with the support of the GRASS topology.
Open a vector map using the with statement:
>>> with VectorTopo('schools', mode='r') as schools:
... for school in schools[:3]:
... print school.attrs['NAMESHORT']
...
SWIFT CREEK
BRIARCLIFF
FARMINGTON WOODS
>>> schools.is_open()
False
Return the geometry features with category == cat_id.
Parameters: |
|
---|
Close the VectorTopo map, if release is True, the memory occupied by spatial index is released
Remove a feature by its id
Parameters: | feature_id (int) – the id of the feature |
---|
Return the number of primitive
Parameters: | primitive (str) – the name of primitive to query; the supported values are:
|
---|
>>> cens = VectorTopo('census')
>>> cens.open(mode='r')
>>> cens.num_primitive_of('point')
0
>>> cens.num_primitive_of('line')
0
>>> cens.num_primitive_of('centroid')
2537
>>> cens.num_primitive_of('boundary')
6383
>>> cens.close()
Return the number of the choosen element type
Parameters: | vtype – the name of type to query; the supported values are: areas, dblinks, faces, holes, islands, kernels, line_points, lines, nodes, update_lines, update_nodes, volumes |
---|
Return a geometry object given the feature id.
Parameters: | feature_id (int) – the id of feature to obtain |
---|
>>> cens = VectorTopo('census')
>>> cens.open(mode='r')
>>> feature1 = cens.read(0)
Traceback (most recent call last):
...
ValueError: The index must be >0, 0 given.
>>> feature1 = cens.read(1)
>>> feature1
Boundary(v_id=1)
>>> feature1.length()
444.54490917696944
>>> cens.read(-1)
Centoid(642963.159711, 214994.016279)
>>> len(cens)
8920
>>> cens.read(8920)
Centoid(642963.159711, 214994.016279)
>>> cens.read(8921)
Traceback (most recent call last):
...
IndexError: Index out of range
>>> cens.close()
Traceback (most recent call last):
...
IndexError: Index out of range
Rewind vector map to cause reads to start at beginning.
>>> cens = VectorTopo('census')
>>> cens.open(mode='r')
>>> cens.next()
Boundary(v_id=1)
>>> cens.next()
Boundary(v_id=2)
>>> cens.next()
Boundary(v_id=3)
>>> cens.rewind()
>>> cens.next()
Boundary(v_id=1)
>>> cens.close()
Return an iterator of vector features
Parameters: |
|
---|
to sort the result in a efficient way, use:
>>> from operator import methodcaller as method
>>> big.sort(key=method('area'), reverse=True) # sort the list
>>> for area in big[:3]:
... print area, area.area()
Area(2099) 5392751.5304
Area(2171) 4799921.30863
Area(495) 4055812.49695
>>> cens.close()
Note: A new GRASS GIS stable version has been released: GRASS GIS 7.4. Go directly to the new manual page here
Help Index | Topics Index | Keywords Index | Full Index
© 2003-2018 GRASS Development Team, GRASS GIS 7.0.7svn Reference Manual