vector.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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. from core import *
  20. # i18N
  21. import gettext
  22. gettext.install('grasslibs', os.path.join(os.getenv("GISBASE"), 'locale'), unicode=True)
  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
  35. @return dictionary { layer : { 'layer', 'table, 'database', 'driver', 'key' }
  36. """
  37. s = read_command('v.db.connect', flags = 'g', map = map, fs = ';', **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' : 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': 0, '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. return parse_key_val(s, val_type = int)
  125. # interface for v.db.select
  126. def vector_db_select(map, layer = 1, **kwargs):
  127. """!Get attribute data of selected vector map layer.
  128. Function returns list of columns and dictionary of values ordered by
  129. key column value. Example:
  130. \code
  131. >>> print grass.vector_select('lakes')['values'][3]
  132. ['3', '19512.86146', '708.44683', '4', '55652', 'LAKE/POND', '39000', '']
  133. \endcode
  134. @param map map name
  135. @param layer layer number
  136. @param kwargs v.db.select options
  137. @return dictionary ('columns' and 'values')
  138. """
  139. try:
  140. key = vector_db(map = map)[layer]['key']
  141. except KeyError:
  142. error(_('Missing layer %(layer)d in vector map <%(map)s>') % \
  143. { 'layer' : layer, 'map' : map })
  144. return { 'columns' : [], 'values' : {} }
  145. if kwargs.has_key('columns'):
  146. if key not in kwargs['columns'].split(','):
  147. # add key column if missing
  148. debug("Adding key column to the output")
  149. kwargs['columns'] += ',' + key
  150. ret = read_command('v.db.select',
  151. map = map,
  152. layer = layer,
  153. fs = '|', **kwargs)
  154. if not ret:
  155. error(_('vector_select() failed'))
  156. return { 'columns' : [], 'values' : {} }
  157. columns = []
  158. values = {}
  159. for line in ret.splitlines():
  160. if not columns:
  161. columns = line.split('|')
  162. key_index = columns.index(key)
  163. continue
  164. value = line.split('|')
  165. key_value = int(value[key_index])
  166. values[key_value] = line.split('|')
  167. return { 'columns' : columns,
  168. 'values' : values }
  169. # interface to v.what
  170. def vector_what(name, coord, distance = 0.0):
  171. """!Query vector map at given locations
  172. To query one vector map at one location
  173. @code
  174. print grass.vector_what(name = 'archsites', coord = (595743, 4925281), distance = 250)
  175. [{'Category': 8, 'Map': 'archsites', 'Layer': 1, 'Key_column': 'cat',
  176. 'Database': '/home/martin/grassdata/spearfish60/PERMANENT/dbf/',
  177. 'Mapset': 'PERMANENT', 'Driver': 'dbf',
  178. 'Attributes': {'str1': 'No_Name', 'cat': '8'},
  179. 'Table': 'archsites', 'Type': 'Point', 'Id': 8}]
  180. @endcode
  181. To query one vector map at more locations
  182. @code
  183. for q in grass.vector_what(name = ('archsites', 'roads'), coord = (595743, 4925281),
  184. distance = 250):
  185. print q['Map'], q['Attributes']
  186. archsites {'str1': 'No_Name', 'cat': '8'}
  187. roads {'label': 'interstate', 'cat': '1'}
  188. @endcode
  189. To query more vector maps at one location
  190. @code
  191. for q in grass.vector_what(name = 'archsites', coord = [(595743, 4925281), (597950, 4918898)],
  192. distance = 250):
  193. print q['Map'], q['Attributes']
  194. archsites {'str1': 'No_Name', 'cat': '8'}
  195. archsites {'str1': 'Bob_Miller', 'cat': '22'}
  196. @endcode
  197. @param name vector map(s) to query given as string or list/tuple
  198. @param coord coordinates of query given as tuple (easting, northing) or list of tuples
  199. @param distance query threshold distance (in map units)
  200. @return parsed list
  201. """
  202. if os.environ.has_key("LC_ALL"):
  203. locale = os.environ["LC_ALL"]
  204. os.environ["LC_ALL"] = "C"
  205. if type(name) in (types.StringType, types.UnicodeType):
  206. name_list = [name]
  207. else:
  208. name_list = name
  209. layer_list = ['-1'] * len(name_list)
  210. coord_list = list()
  211. if type(coord) is types.TupleType:
  212. coord_list.append('%f,%f' % (coord[0], coord[1]))
  213. else:
  214. for e, n in coord:
  215. coord_list.append('%f,%f' % (e, n))
  216. ret = read_command('v.what',
  217. quiet = True,
  218. flags = 'ag',
  219. map = ','.join(name_list),
  220. layer = ','.join(layer_list),
  221. east_north = ','.join(coord_list),
  222. distance = float(distance))
  223. if os.environ.has_key("LC_ALL"):
  224. os.environ["LC_ALL"] = locale
  225. data = list()
  226. if not ret:
  227. return data
  228. dict_attrb = None
  229. for item in ret.splitlines():
  230. try:
  231. key, value = map(lambda x: x.strip(), item.split('=', 1))
  232. except ValueError:
  233. continue
  234. if key in ('East', 'North'):
  235. continue
  236. if key == 'Map':
  237. dict_main = { 'Map' : value }
  238. dict_attrb = None
  239. data.append(dict_main)
  240. continue
  241. else:
  242. if dict_attrb is not None:
  243. dict_attrb[key] = value
  244. else:
  245. if key in ('Category', 'Layer', 'Id'):
  246. dict_main[key] = int(value)
  247. else:
  248. dict_main[key] = value
  249. if key == 'Key_column':
  250. # skip attributes
  251. dict_attrb = dict()
  252. dict_main['Attributes'] = dict_attrb
  253. return data