vector.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. """!@package grass.script.vector
  2. @brief GRASS Python scripting module (vector functions)
  3. Vector related functions to be used in Python scripts.
  4. Usage:
  5. @code
  6. from grass.script import vector as grass
  7. grass.vector_db(map)
  8. ...
  9. @endcode
  10. (C) 2008-2010 by the GRASS Development Team
  11. This program is free software under the GNU General Public
  12. License (>=v2). Read the file COPYING that comes with GRASS
  13. for details.
  14. @author Glynn Clements
  15. @author Martin Landa <landa.martin gmail.com>
  16. """
  17. import os
  18. import types
  19. import copy
  20. import __builtin__
  21. from core import *
  22. # run "v.db.connect -g ..." and parse output
  23. def vector_db(map, **args):
  24. """!Return the database connection details for a vector map
  25. (interface to `v.db.connect -g'). Example:
  26. \code
  27. >>> grass.vector_db('lakes')
  28. {1: {'layer': 1, 'name': '',
  29. 'database': '/home/martin/grassdata/nc_spm_08/PERMANENT/dbf/',
  30. 'driver': 'dbf', 'key': 'cat', 'table': 'lakes'}}
  31. \endcode
  32. @param map vector map
  33. @param args other v.db.connect's arguments
  34. @return dictionary
  35. """
  36. s = read_command('v.db.connect', quiet = True, flags = 'g', map = map, sep = ';', **args)
  37. result = {}
  38. for l in s.splitlines():
  39. f = l.split(';')
  40. if len(f) != 5:
  41. continue
  42. if '/' in f[0]:
  43. f1 = f[0].split('/')
  44. layer = f1[0]
  45. name = f1[1]
  46. else:
  47. layer = f[0]
  48. name = ''
  49. result[int(layer)] = {
  50. 'layer' : int(layer),
  51. 'name' : name,
  52. 'table' : f[1],
  53. 'key' : f[2],
  54. 'database' : f[3],
  55. 'driver' : f[4] }
  56. return result
  57. def vector_layer_db(map, layer):
  58. """!Return the database connection details for a vector map layer.
  59. If db connection for given layer is not defined, fatal() is called.
  60. @param map map name
  61. @param layer layer number
  62. @return parsed output
  63. """
  64. try:
  65. f = vector_db(map)[int(layer)]
  66. except KeyError:
  67. fatal(_("Database connection not defined for layer %s") % layer)
  68. return f
  69. # run "v.info -c ..." and parse output
  70. def vector_columns(map, layer = None, getDict = True, **args):
  71. """!Return a dictionary (or a list) of the columns for the
  72. database table connected to a vector map (interface to `v.info
  73. -c').
  74. @code
  75. >>> vector_columns(urbanarea, getDict = True)
  76. {'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'}}
  77. >>> vector_columns(urbanarea, getDict = False)
  78. ['cat', 'OBJECTID', 'UA', 'NAME', 'UA_TYPE']
  79. @endcode
  80. @param map map name
  81. @param layer layer number or name (None for all layers)
  82. @param getDict True to return dictionary of columns otherwise list of column names is returned
  83. @param args (v.info's arguments)
  84. @return dictionary/list of columns
  85. """
  86. s = read_command('v.info', flags = 'c', map = map, layer = layer, quiet = True, **args)
  87. if getDict:
  88. result = dict()
  89. else:
  90. result = list()
  91. i = 0
  92. for line in s.splitlines():
  93. ctype, cname = line.split('|')
  94. if getDict:
  95. result[cname] = { 'type' : ctype,
  96. 'index' : i }
  97. else:
  98. result.append(cname)
  99. i+=1
  100. return result
  101. # add vector history
  102. def vector_history(map):
  103. """!Set the command history for a vector map to the command used to
  104. invoke the script (interface to `v.support').
  105. @param map mapname
  106. @return v.support output
  107. """
  108. run_command('v.support', map = map, cmdhist = os.environ['CMDLINE'])
  109. # run "v.info -t" and parse output
  110. def vector_info_topo(map):
  111. """!Return information about a vector map (interface to `v.info
  112. -t'). Example:
  113. \code
  114. >>> grass.vector_info_topo('lakes')
  115. {'kernels': 0, 'lines': 0, 'centroids': 15279,
  116. 'boundaries': 27764, 'points': 0, 'faces': 0,
  117. 'primitives': 43043, 'islands': 7470, 'nodes': 35234, 'map3d': False, 'areas': 15279}
  118. \endcode
  119. @param map map name
  120. @return parsed output
  121. """
  122. s = read_command('v.info', flags = 't', map = map)
  123. ret = parse_key_val(s, val_type = int)
  124. if 'map3d' in ret:
  125. ret['map3d'] = bool(ret['map3d'])
  126. return ret
  127. # run "v.info -get ..." and parse output
  128. def vector_info(map):
  129. """!Return information about a vector map (interface to
  130. `v.info'). Example:
  131. \code
  132. >>> grass.vector_info('random_points')
  133. {'comment': '', 'projection': 'x,y', 'creator': 'soeren', 'holes': 0,
  134. 'primitives': 20, 'kernels': 0, 'scale': '1:1', 'title': '',
  135. 'west': 0.046125489999999998, 'top': 2376.133159, 'boundaries': 0,
  136. 'location': 'XYLocation', 'nodes': 0, 'east': 0.97305646000000001,
  137. 'source_date': 'Mon Aug 29 10:55:57 2011', 'north': 0.9589993,
  138. 'format': 'native', 'faces': 0, 'centroids': 0,
  139. 'digitization_threshold': '0.000000', 'islands': 0, 'level': 2,
  140. 'mapset': 'test', 'areas': 0, 'name': 'random_points',
  141. 'database': '/home/soeren/grassdata', 'bottom': 22.186596999999999,
  142. 'lines': 0, 'points': 20, 'map3d': True, 'volumes': 0, 'num_dblinks': 0,
  143. 'organization': '', 'south': 0.066047099999999997}
  144. \endcode
  145. @param map map name
  146. @return parsed vector info
  147. """
  148. s = read_command('v.info', flags = 'get', map = map)
  149. kv = parse_key_val(s)
  150. for k in ['north', 'south', 'east', 'west', 'top', 'bottom']:
  151. kv[k] = float(kv[k])
  152. for k in ['level', 'num_dblinks']:
  153. kv[k] = int(kv[k])
  154. for k in ['nodes', 'points', 'lines', 'boundaries', 'centroids', 'areas', 'islands', 'primitives']:
  155. kv[k] = int(kv[k])
  156. if 'map3d' in kv:
  157. kv['map3d'] = bool(int(kv['map3d']))
  158. if kv['map3d']:
  159. for k in ['faces', 'kernels', 'volumes', 'holes']:
  160. kv[k] = int(kv[k])
  161. return kv
  162. # interface for v.db.select
  163. def vector_db_select(map, layer = 1, **kwargs):
  164. """!Get attribute data of selected vector map layer.
  165. Function returns list of columns and dictionary of values ordered by
  166. key column value. Example:
  167. \code
  168. >>> print grass.vector_db_select('lakes')['columns']
  169. ['cat', 'AREA', 'PERIMETER', 'FULL_HYDRO', 'FULL_HYDR2', 'FTYPE', 'FCODE', 'NAME']
  170. >>> print grass.vector_db_select('lakes')['values'][3]
  171. ['3', '19512.86146', '708.44683', '4', '55652', 'LAKE/POND', '39000', '']
  172. >>> print grass.vector_db_select('lakes', columns = 'FTYPE')['values'][3]
  173. ['LAKE/POND']
  174. \endcode
  175. @param map map name
  176. @param layer layer number
  177. @param kwargs v.db.select options
  178. @return dictionary ('columns' and 'values')
  179. """
  180. try:
  181. key = vector_db(map = map)[layer]['key']
  182. except KeyError:
  183. error(_('Missing layer %(layer)d in vector map <%(map)s>') % \
  184. { 'layer' : layer, 'map' : map })
  185. return { 'columns' : [], 'values' : {} }
  186. if 'columns' in kwargs:
  187. if key not in kwargs['columns'].split(','):
  188. # add key column if missing
  189. debug("Adding key column to the output")
  190. kwargs['columns'] += ',' + key
  191. ret = read_command('v.db.select',
  192. map = map,
  193. layer = layer,
  194. **kwargs)
  195. if not ret:
  196. error(_('vector_db_select() failed'))
  197. return { 'columns' : [], 'values' : {} }
  198. columns = []
  199. values = {}
  200. for line in ret.splitlines():
  201. if not columns:
  202. columns = line.split('|')
  203. key_index = columns.index(key)
  204. continue
  205. value = line.split('|')
  206. key_value = int(value[key_index])
  207. values[key_value] = line.split('|')
  208. return { 'columns' : columns,
  209. 'values' : values }
  210. # interface to v.what
  211. def vector_what(map, coord, distance = 0.0, ttype = None):
  212. """!Query vector map at given locations
  213. To query one vector map at one location
  214. @code
  215. print grass.vector_what(map = 'archsites', coord = (595743, 4925281), distance = 250)
  216. [{'Category': 8, 'Map': 'archsites', 'Layer': 1, 'Key_column': 'cat',
  217. 'Database': '/home/martin/grassdata/spearfish60/PERMANENT/dbf/',
  218. 'Mapset': 'PERMANENT', 'Driver': 'dbf',
  219. 'Attributes': {'str1': 'No_Name', 'cat': '8'},
  220. 'Table': 'archsites', 'Type': 'Point', 'Id': 8}]
  221. @endcode
  222. To query one vector map with multiple layers (no additional parameters required)
  223. @code
  224. for q in grass.vector_what(map = 'some_map', coord = (596532.357143,4920486.21429), distance = 100.0):
  225. print q['Map'], q['Layer'], q['Attributes']
  226. new_bug_sites 1 {'str1': 'Beetle_site', 'GRASSRGB': '', 'cat': '80'}
  227. new_bug_sites 2 {'cat': '80'}
  228. @endcode
  229. To query more vector maps at one location
  230. @code
  231. for q in grass.vector_what(map = ('archsites', 'roads'), coord = (595743, 4925281),
  232. distance = 250):
  233. print q['Map'], q['Attributes']
  234. archsites {'str1': 'No_Name', 'cat': '8'}
  235. roads {'label': 'interstate', 'cat': '1'}
  236. @endcode
  237. To query one vector map at more locations
  238. @code
  239. for q in grass.vector_what(map = 'archsites', coord = [(595743, 4925281), (597950, 4918898)],
  240. distance = 250):
  241. print q['Map'], q['Attributes']
  242. archsites {'str1': 'No_Name', 'cat': '8'}
  243. archsites {'str1': 'Bob_Miller', 'cat': '22'}
  244. @endcode
  245. @param map vector map(s) to query given as string or list/tuple
  246. @param coord coordinates of query given as tuple (easting, northing) or list of tuples
  247. @param distance query threshold distance (in map units)
  248. @param ttype list of topology types (default of v.what are point, line, area, face)
  249. @return parsed list
  250. """
  251. if "LC_ALL" in os.environ:
  252. locale = os.environ["LC_ALL"]
  253. os.environ["LC_ALL"] = "C"
  254. if type(map) in (types.StringType, types.UnicodeType):
  255. map_list = [map]
  256. else:
  257. map_list = map
  258. layer_list = ['-1'] * len(map_list)
  259. coord_list = list()
  260. if type(coord) is types.TupleType:
  261. coord_list.append('%f,%f' % (coord[0], coord[1]))
  262. else:
  263. for e, n in coord:
  264. coord_list.append('%f,%f' % (e, n))
  265. cmdParams = dict(quiet = True,
  266. flags = 'ag',
  267. map = ','.join(map_list),
  268. layer = ','.join(layer_list),
  269. coordinates = ','.join(coord_list),
  270. distance = float(distance))
  271. if ttype:
  272. cmdParams['type'] = ','.join(ttype)
  273. ret = read_command('v.what',
  274. **cmdParams)
  275. if "LC_ALL" in os.environ:
  276. os.environ["LC_ALL"] = locale
  277. data = list()
  278. if not ret:
  279. return data
  280. dict_attrb = None
  281. dict_map = None
  282. dict_layer = None
  283. attr_pseudo_key = 'Attributes'
  284. for item in ret.splitlines():
  285. try:
  286. key, value = __builtin__.map(lambda x: x.strip(), item.split('=', 1))
  287. except ValueError:
  288. continue
  289. if key in ('East', 'North'):
  290. continue
  291. if key == 'Map':
  292. # attach the last one from the previous map
  293. if dict_map is not None:
  294. dict_main = copy.copy(dict_map)
  295. if dict_layer is not None:
  296. dict_main.update(dict_layer)
  297. data.append(dict_main)
  298. dict_map = { key : value }
  299. dict_layer = None
  300. dict_attrb = None
  301. elif key == 'Layer':
  302. # attach the last the previous Layer
  303. if dict_layer is not None:
  304. dict_main = copy.copy(dict_map)
  305. dict_main.update(dict_layer)
  306. data.append(dict_main)
  307. dict_layer = { key: int(value) }
  308. dict_attrb = None
  309. elif key == 'Key_column':
  310. dict_layer[key] = value
  311. dict_attrb = dict()
  312. dict_layer[attr_pseudo_key] = dict_attrb
  313. elif dict_attrb is not None:
  314. dict_attrb[key] = value
  315. elif dict_layer is not None:
  316. if key == 'Category':
  317. dict_layer[key] = int(value)
  318. else:
  319. dict_layer[key] = value
  320. else:
  321. dict_map[key] = value
  322. # TODO: there are some keys which has non-string values
  323. # examples: Sq_Meters, Hectares, Acres, Sq_Miles
  324. # attach the last one
  325. if dict_map is not None:
  326. dict_main = copy.copy(dict_map)
  327. if dict_layer:
  328. dict_main.update(dict_layer)
  329. data.append(dict_main)
  330. return data