vector.py 13 KB

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