utils.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. """
  2. @package utils.py
  3. @brief Misc utilities for GRASS wxPython GUI
  4. (C) 2007-2008 by the GRASS Development Team
  5. This program is free software under the GNU General Public
  6. License (>=v2). Read the file COPYING that comes with GRASS
  7. for details.
  8. @author Martin Landa, Jachym Cepicky
  9. @date 2007-2008
  10. """
  11. import os
  12. import sys
  13. import platform
  14. import string
  15. import globalvar
  16. grassPath = os.path.join(globalvar.ETCDIR, "python")
  17. sys.path.append(grassPath)
  18. from grass.script import core as grass
  19. import gcmd
  20. try:
  21. import subprocess
  22. except:
  23. compatPath = os.path.join(globalvar.ETCWXDIR, "compat")
  24. sys.path.append(compatPath)
  25. import subprocess
  26. def normalize_whitespace(text):
  27. """!Remove redundant whitespace from a string"""
  28. return string.join( string.split(text), ' ')
  29. def GetTempfile(pref=None):
  30. """
  31. Creates GRASS temporary file using defined prefix.
  32. @todo Fix path on MS Windows/MSYS
  33. @param pref prefer the given path
  34. @return Path to file name (string) or None
  35. """
  36. import gcmd
  37. ret = gcmd.RunCommand('g.tempfile',
  38. read = True,
  39. pid = os.getpid())
  40. tempfile = ret.splitlines()[0].strip()
  41. # FIXME
  42. # ugly hack for MSYS (MS Windows)
  43. if platform.system() == 'Windows':
  44. tempfile = tempfile.replace("/", "\\")
  45. try:
  46. path, file = os.path.split(tempfile)
  47. if pref:
  48. return os.path.join(pref, file)
  49. else:
  50. return tempfile
  51. except:
  52. return None
  53. def GetLayerNameFromCmd(dcmd, fullyQualified=False, param=None,
  54. layerType=None):
  55. """!Get map name from GRASS command
  56. @param dcmd GRASS command (given as tuple)
  57. @param fullyQualified change map name to be fully qualified
  58. @param force parameter otherwise 'input'/'map'
  59. @param update change map name in command
  60. @param layerType check also layer type ('raster', 'vector', '3d-raster', ...)
  61. @return map name
  62. @return '' if no map name found in command
  63. """
  64. mapname = ''
  65. if not dcmd:
  66. return mapname
  67. if 'd.grid' == dcmd[0]:
  68. mapname = 'grid'
  69. elif 'd.geodesic' in dcmd[0]:
  70. mapname = 'geodesic'
  71. elif 'd.rhumbline' in dcmd[0]:
  72. mapname = 'rhumb'
  73. elif 'labels=' in dcmd[0]:
  74. mapname = dcmd[idx].split('=')[1]+' labels'
  75. else:
  76. for idx in range(len(dcmd)):
  77. if param and param in dcmd[idx]:
  78. break
  79. elif not param:
  80. if 'map=' in dcmd[idx] or \
  81. 'input=' in dcmd[idx] or \
  82. 'red=' in dcmd[idx] or \
  83. 'h_map=' in dcmd[idx] or \
  84. 'reliefmap' in dcmd[idx]:
  85. break
  86. if idx < len(dcmd):
  87. try:
  88. mapname = dcmd[idx].split('=')[1]
  89. except IndexError:
  90. return ''
  91. if fullyQualified and '@' not in mapname:
  92. if layerType in ('raster', 'vector', '3d-raster'):
  93. try:
  94. if layerType == 'raster':
  95. findType = 'cell'
  96. else:
  97. findType = layerType
  98. result = grass.find_file(mapname, element=findType)
  99. except AttributeError, e: # not found
  100. return ''
  101. if result:
  102. mapname = result['fullname']
  103. else:
  104. mapname += '@' + grass.gisenv()['MAPSET']
  105. else:
  106. mapname += '@' + grass.gisenv()['MAPSET']
  107. dcmd[idx] = dcmd[idx].split('=')[0] + '=' + mapname
  108. return mapname
  109. def GetValidLayerName(name):
  110. """!Make layer name SQL compliant, based on G_str_to_sql()
  111. @todo: Better use directly GRASS Python SWIG...
  112. """
  113. retName = str(name).strip()
  114. # check if name is fully qualified
  115. if '@' in retName:
  116. retName, mapset = retName.split('@')
  117. else:
  118. mapset = None
  119. for c in retName:
  120. # c = toascii(c)
  121. if not (c >= 'A' and c <= 'Z') and \
  122. not (c >= 'a' and c <= 'z') and \
  123. not (c >= '0' and c <= '9'):
  124. c = '_'
  125. if not (retName[0] >= 'A' and retName[0] <= 'Z') and \
  126. not (retName[0] >= 'a' and retName[0] <= 'z'):
  127. retName = 'x' + retName[1:]
  128. if mapset:
  129. retName = retName + '@' + mapset
  130. return retName
  131. def ListOfCatsToRange(cats):
  132. """!Convert list of category number to range(s)
  133. Used for example for d.vect cats=[range]
  134. @param cats category list
  135. @return category range string
  136. @return '' on error
  137. """
  138. catstr = ''
  139. try:
  140. cats = map(int, cats)
  141. except:
  142. return catstr
  143. i = 0
  144. while i < len(cats):
  145. next = 0
  146. j = i + 1
  147. while j < len(cats):
  148. if cats[i + next] == cats[j] - 1:
  149. next += 1
  150. else:
  151. break
  152. j += 1
  153. if next > 1:
  154. catstr += '%d-%d,' % (cats[i], cats[i + next])
  155. i += next + 1
  156. else:
  157. catstr += '%d,' % (cats[i])
  158. i += 1
  159. return catstr.strip(',')
  160. def ListOfMapsets(all=False):
  161. """!Get list of available/accessible mapsets
  162. @param all if True get list of all mapsets
  163. @return list of mapsets
  164. """
  165. mapsets = []
  166. if all:
  167. ret = gcmd.RunCommand('g.mapsets',
  168. read = True,
  169. flags = 'l',
  170. fs = ';')
  171. if ret:
  172. mapsets = ret.rstrip('\n').split(';')
  173. else:
  174. raise gcmd.CmdError(cmd = 'g.mapsets',
  175. message = _('Unable to get list of available mapsets.'))
  176. else:
  177. ret = gcmd.RunCommand('g.mapsets',
  178. read = True,
  179. flags = 'p',
  180. fs = ';')
  181. if ret:
  182. mapsets = ret.rstrip('\n').split(';')
  183. else:
  184. raise gcmd.CmdError(cmd = 'g.mapsets',
  185. message = _('Unable to get list of accessible mapsets.'))
  186. ListSortLower(mapsets)
  187. return mapsets
  188. def ListSortLower(list):
  189. """!Sort list items (not case-sensitive)"""
  190. list.sort(cmp=lambda x, y: cmp(x.lower(), y.lower()))
  191. def GetVectorNumberOfLayers(vector):
  192. """!Get list of vector layers"""
  193. cmdlist = ['v.category',
  194. 'input=%s' % vector,
  195. 'option=report']
  196. layers = []
  197. ret = gcmd.RunCommand('v.category',
  198. read = True,
  199. input = vector,
  200. option = 'report')
  201. if not ret:
  202. return layers
  203. for line in ret.splitlines():
  204. if not 'Layer' in line:
  205. continue
  206. value = line.split(':')[1].strip()
  207. if '/' in value: # value/name
  208. layers.append(value.split('/')[0])
  209. else:
  210. layers.append(value)
  211. return layers
  212. def Deg2DMS(lon, lat):
  213. """!Convert deg value to dms string
  214. @param lat latitude
  215. @param lon longitude
  216. @return DMS string
  217. @return empty string on error
  218. """
  219. try:
  220. flat = float(lat)
  221. flon = float(lon)
  222. except ValueError:
  223. return ''
  224. # fix longitude
  225. while flon > 180.0:
  226. flon -= 360.0
  227. while flon < -180.0:
  228. flon += 360.0
  229. # hemisphere
  230. if flat < 0.0:
  231. flat = abs(flat)
  232. hlat = 'S'
  233. else:
  234. hlat = 'N'
  235. if flon < 0.0:
  236. hlon = 'W'
  237. flon = abs(flon)
  238. else:
  239. hlon = 'E'
  240. slat = __ll_parts(flat)
  241. slon = __ll_parts(flon)
  242. return slon + hlon + '; ' + slat + hlat
  243. def __ll_parts(value):
  244. """!Converts deg to d:m:s string"""
  245. if value == 0.0:
  246. return '00:00:00.0000'
  247. d = int(int(value))
  248. m = int((value - d) * 60)
  249. s = ((value - d) * 60 - m) * 60
  250. if m < 0:
  251. m = '00'
  252. elif m < 10:
  253. m = '0' + str(m)
  254. else:
  255. m = str(m)
  256. if s < 0:
  257. s = '00.0000'
  258. elif s < 10.0:
  259. s = '0%.4f' % s
  260. else:
  261. s = '%.4f' % s
  262. return str(d) + ':' + m + ':' + s
  263. def GetCmdString(cmd):
  264. """
  265. Get GRASS command as string.
  266. @param cmd GRASS command given as tuple
  267. @return command string
  268. """
  269. scmd = ''
  270. if not cmd:
  271. return ''
  272. scmd = cmd[0]
  273. for k, v in cmd[1].iteritems():
  274. scmd += ' %s=%s' % (k, v)
  275. return scmd
  276. def CmdToTuple(cmd):
  277. """!Convert command list to tuple for gcmd.RunCommand()"""
  278. if len(cmd) < 1:
  279. return None
  280. dcmd = {}
  281. for item in cmd[1:]:
  282. if '=' in item:
  283. key, value = item.split('=', 1)
  284. dcmd[str(key)] = str(value)
  285. else: # -> flags
  286. if not dcmd.has_key('flags'):
  287. dcmd['flags'] = ''
  288. dcmd['flags'] += item.replace('-', '')
  289. return (cmd[0],
  290. dcmd)
  291. def PathJoin(*args):
  292. """!Check path created by os.path.join"""
  293. path = os.path.join(*args)
  294. if platform.system() == 'Windows' and \
  295. '/' in path:
  296. return path[1].upper() + ':\\' + path[3:].replace('/', '\\')
  297. return path
  298. def reexec_with_pythonw():
  299. """!Re-execute Python on Mac OS"""
  300. if sys.platform == 'darwin' and \
  301. not sys.executable.endswith('MacOS/Python'):
  302. print >> sys.stderr, 're-executing using pythonw'
  303. os.execvp('pythonw', ['pythonw', __file__] + sys.argv[1:])