1 """!@package grass.script.vector
3 @brief GRASS Python scripting module (vector functions)
5 Vector related functions to be used in Python scripts.
10 from grass.script import vector as grass
16 (C) 2008-2010 by the GRASS Development Team
17 This program is free software under the GNU General Public
18 License (>=v2). Read the file COPYING that comes with GRASS
21 @author Glynn Clements
22 @author Martin Landa <landa.martin gmail.com>
33 gettext.install(
'grasslibs', os.path.join(os.getenv(
"GISBASE"),
'locale'), unicode=
True)
38 """!Return the database connection details for a vector map
39 (interface to `v.db.connect -g'). Example:
42 >>> grass.vector_db('lakes')
43 {1: {'layer': '1', 'name': '',
44 'database': '/home/martin/grassdata/nc_spm_08/PERMANENT/dbf/',
45 'driver': 'dbf', 'key': 'cat', 'table': 'lakes'}}
51 @return dictionary { layer : { 'layer', 'table, 'database', 'driver', 'key' }
53 s =
read_command(
'v.db.connect', flags =
'g', map = map, fs =
';', **args)
56 for l
in s.splitlines():
69 result[int(layer)] = {
80 """!Return the database connection details for a vector map layer.
81 If db connection for given layer is not defined, fatal() is called.
84 @param layer layer number
91 fatal(_(
"Database connection not defined for layer %s") % layer)
98 """!Return a dictionary (or a list) of the columns for the
99 database table connected to a vector map (interface to `v.info
103 >>> vector_columns(urbanarea, getDict = True)
104 {'UA_TYPE': {'index': 4, 'type': 'CHARACTER'}, 'UA': {'index': 2, 'type': 'CHARACTER'}, 'NAME': {'index': 3, 'type': 'CHARACTER'}, 'OBJECTID': {'index': 1, 'type': 'INTEGER'}, 'cat': {'index': 0, 'type': 'INTEGER'}}
106 >>> vector_columns(urbanarea, getDict = False)
107 ['cat', 'OBJECTID', 'UA', 'NAME', 'UA_TYPE']
111 @param layer layer number or name (None for all layers)
112 @param getDict True to return dictionary of columns otherwise list of column names is returned
113 @param args (v.info's arguments)
115 @return dictionary/list of columns
117 s =
read_command(
'v.info', flags =
'c', map = map, layer = layer, quiet =
True, **args)
123 for line
in s.splitlines():
124 ctype, cname = line.split(
'|')
126 result[cname] = {
'type' : ctype,
137 """!Set the command history for a vector map to the command used to
138 invoke the script (interface to `v.support').
142 @return v.support output
144 run_command(
'v.support', map = map, cmdhist = os.environ[
'CMDLINE'])
149 """!Return information about a vector map (interface to `v.info
153 >>> grass.vector_info_topo('lakes')
154 {'kernels': 0, 'lines': 0, 'centroids': 15279,
155 'boundaries': 27764, 'points': 0, 'faces': 0,
156 'primitives': 43043, 'islands': 7470, 'nodes': 35234, 'map3d': 0, 'areas': 15279}
161 @return parsed output
166 ret[
'map3d'] = bool(ret[
'map3d'])
173 """!Get attribute data of selected vector map layer.
175 Function returns list of columns and dictionary of values ordered by
176 key column value. Example:
179 >>> print grass.vector_select('lakes')['values'][3]
180 ['3', '19512.86146', '708.44683', '4', '55652', 'LAKE/POND', '39000', '']
184 @param layer layer number
185 @param kwargs v.db.select options
187 @return dictionary ('columns' and 'values')
192 error(_(
'Missing layer %(layer)d in vector map <%(map)s>') % \
193 {
'layer' : layer,
'map' : map })
194 return {
'columns' : [],
'values' : {} }
196 if 'columns' in kwargs:
197 if key
not in kwargs[
'columns'].
split(
','):
199 debug(
"Adding key column to the output")
200 kwargs[
'columns'] +=
',' + key
208 error(_(
'vector_select() failed'))
209 return {
'columns' : [],
'values' : {} }
213 for line
in ret.splitlines():
215 columns = line.split(
'|')
216 key_index = columns.index(key)
219 value = line.split(
'|')
220 key_value = int(value[key_index])
221 values[key_value] = line.split(
'|')
223 return {
'columns' : columns,
228 """!Query vector map at given locations
230 To query one vector map at one location
232 print grass.vector_what(map = 'archsites', coord = (595743, 4925281), distance = 250)
234 [{'Category': 8, 'Map': 'archsites', 'Layer': 1, 'Key_column': 'cat',
235 'Database': '/home/martin/grassdata/spearfish60/PERMANENT/dbf/',
236 'Mapset': 'PERMANENT', 'Driver': 'dbf',
237 'Attributes': {'str1': 'No_Name', 'cat': '8'},
238 'Table': 'archsites', 'Type': 'Point', 'Id': 8}]
241 To query one vector map at more locations
243 for q in grass.vector_what(map = ('archsites', 'roads'), coord = (595743, 4925281),
245 print q['Map'], q['Attributes']
247 archsites {'str1': 'No_Name', 'cat': '8'}
248 roads {'label': 'interstate', 'cat': '1'}
251 To query more vector maps at one location
253 for q in grass.vector_what(map = 'archsites', coord = [(595743, 4925281), (597950, 4918898)],
255 print q['Map'], q['Attributes']
257 archsites {'str1': 'No_Name', 'cat': '8'}
258 archsites {'str1': 'Bob_Miller', 'cat': '22'}
261 @param map vector map(s) to query given as string or list/tuple
262 @param coord coordinates of query given as tuple (easting, northing) or list of tuples
263 @param distance query threshold distance (in map units)
267 if "LC_ALL" in os.environ:
268 locale = os.environ[
"LC_ALL"]
269 os.environ[
"LC_ALL"] =
"C"
271 if type(map)
in (types.StringType, types.UnicodeType):
277 if type(coord)
is types.TupleType:
278 coord_list.append(
'%f,%f' % (coord[0], coord[1]))
281 coord_list.append(
'%f,%f' % (e, n))
286 map =
','.join(map_list),
287 east_north =
','.join(coord_list),
288 distance = float(distance))
290 if "LC_ALL" in os.environ:
291 os.environ[
"LC_ALL"] = locale
298 for item
in ret.splitlines():
300 key, value = __builtin__.map(
lambda x: x.strip(), item.split(
'=', 1))
303 if key
in (
'East',
'North'):
307 dict_main = {
'Map' : value }
309 data.append(dict_main)
312 if dict_attrb
is not None:
313 dict_attrb[key] = value
315 if key
in (
'Category',
'Layer',
'Id'):
316 dict_main[key] = int(value)
318 dict_main[key] = value
319 if key ==
'Key_column':
322 dict_main[
'Attributes'] = dict_attrb