utils.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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 globalvar
  14. grassPath = os.path.join(globalvar.ETCDIR, "python")
  15. sys.path.append(grassPath)
  16. import grass
  17. import gcmd
  18. try:
  19. import subprocess
  20. except:
  21. compatPath = os.path.join(globalvar.ETCWXDIR, "compat")
  22. sys.path.append(compatPath)
  23. import subprocess
  24. def GetTempfile(pref=None):
  25. """
  26. Creates GRASS temporary file using defined prefix.
  27. @todo Fix path on MS Windows/MSYS
  28. @param pref prefer the given path
  29. @return Path to file name (string) or None
  30. """
  31. import gcmd
  32. tempfileCmd = gcmd.Command(["g.tempfile",
  33. "pid=%d" % os.getpid()])
  34. tempfile = tempfileCmd.ReadStdOutput()[0].strip()
  35. # FIXME
  36. # ugly hack for MSYS (MS Windows)
  37. if subprocess.mswindows:
  38. tempfile = tempfile.replace("/", "\\")
  39. try:
  40. path, file = os.path.split(tempfile)
  41. if pref:
  42. return os.path.join(pref, file)
  43. else:
  44. return tempfile
  45. except:
  46. return None
  47. def GetLayerNameFromCmd(dcmd, fullyQualified=False, param=None,
  48. layerType=None):
  49. """Get map name from GRASS command
  50. @param dcmd GRASS command (given as list)
  51. @param fullyQualified change map name to be fully qualified
  52. @param force parameter otherwise 'input'/'map'
  53. @param update change map name in command
  54. @param layerType check also layer type ('raster', 'vector', '3d-raster', ...)
  55. @return map name
  56. @return '' if no map name found in command
  57. """
  58. mapname = ''
  59. if len(dcmd) < 1:
  60. return mapname
  61. if 'd.grid' == dcmd[0]:
  62. mapname = 'grid'
  63. elif 'd.geodesic' in dcmd[0]:
  64. mapname = 'geodesic'
  65. elif 'd.rhumbline' in dcmd[0]:
  66. mapname = 'rhumb'
  67. elif 'labels=' in dcmd[0]:
  68. mapname = dcmd[idx].split('=')[1]+' labels'
  69. else:
  70. for idx in range(len(dcmd)):
  71. if param and param in dcmd[idx]:
  72. break
  73. elif not param:
  74. if 'map=' in dcmd[idx] or \
  75. 'input=' in dcmd[idx] or \
  76. 'red=' in dcmd[idx] or \
  77. 'h_map=' in dcmd[idx] or \
  78. 'reliefmap' in dcmd[idx]:
  79. break
  80. if idx < len(dcmd):
  81. try:
  82. mapname = dcmd[idx].split('=')[1]
  83. except IndexError:
  84. return ''
  85. if fullyQualified and '@' not in mapname:
  86. if layerType in ('raster', 'vector', '3d-raster'):
  87. try:
  88. if layerType == 'raster':
  89. findType = 'cell'
  90. else:
  91. findType = layerType
  92. result = grass.find_file(mapname, element=findType)
  93. except AttributeError, e: # not found
  94. return ''
  95. if result:
  96. mapname = result['fullname']
  97. else:
  98. mapname += '@' + grass.gisenv()['MAPSET']
  99. else:
  100. mapname += '@' + grass.gisenv()['MAPSET']
  101. dcmd[idx] = dcmd[idx].split('=')[0] + '=' + mapname
  102. return mapname
  103. def GetValidLayerName(name):
  104. """Make layer name SQL compliant, based on G_str_to_sql()
  105. @todo: Better use directly GRASS Python SWIG...
  106. """
  107. retName = str(name).strip()
  108. # check if name is fully qualified
  109. if '@' in retName:
  110. retName, mapset = retName.split('@')
  111. else:
  112. mapset = None
  113. for c in retName:
  114. # c = toascii(c)
  115. if not (c >= 'A' and c <= 'Z') and \
  116. not (c >= 'a' and c <= 'z') and \
  117. not (c >= '0' and c <= '9'):
  118. c = '_'
  119. if not (retName[0] >= 'A' and retName[0] <= 'Z') and \
  120. not (retName[0] >= 'a' and retName[0] <= 'z'):
  121. retName = 'x' + retName[1:]
  122. if mapset:
  123. retName = retName + '@' + mapset
  124. return retName
  125. def ListOfCatsToRange(cats):
  126. """Convert list of category number to range(s)
  127. Used for example for d.vect cats=[range]
  128. @param cats category list
  129. @return category range string
  130. @return '' on error
  131. """
  132. catstr = ''
  133. try:
  134. cats = map(int, cats)
  135. except:
  136. return catstr
  137. i = 0
  138. while i < len(cats):
  139. next = 0
  140. j = i + 1
  141. while j < len(cats):
  142. if cats[i + next] == cats[j] - 1:
  143. next += 1
  144. else:
  145. break
  146. j += 1
  147. if next > 1:
  148. catstr += '%d-%d,' % (cats[i], cats[i + next])
  149. i += next + 1
  150. else:
  151. catstr += '%d,' % (cats[i])
  152. i += 1
  153. return catstr.strip(',')
  154. def ListOfMapsets(all=False):
  155. """Get list of available/accessible mapsets
  156. @param all if True get list of all mapsets
  157. @return list of mapsets
  158. """
  159. mapsets = []
  160. ### FIXME
  161. # problem using Command here (see preferences.py)
  162. # cmd = gcmd.Command(['g.mapsets', '-l'])
  163. if all:
  164. cmd = subprocess.Popen(['g.mapsets' + globalvar.EXT_BIN, '-l'],
  165. stdout=subprocess.PIPE)
  166. try:
  167. # for mset in cmd.ReadStdOutput()[0].split(' '):
  168. for line in cmd.stdout.readlines():
  169. for mset in line.strip('%s' % os.linesep).split(' '):
  170. if len(mset) == 0:
  171. continue
  172. mapsets.append(mset)
  173. except:
  174. raise gcmd.CmdError(_('Unable to get list of available mapsets.'))
  175. else:
  176. # cmd = gcmd.Command(['g.mapsets', '-p'])
  177. cmd = subprocess.Popen(['g.mapsets' + globalvar.EXT_BIN, '-p'],
  178. stdout=subprocess.PIPE)
  179. try:
  180. # for mset in cmd.ReadStdOutput()[0].split(' '):
  181. for line in cmd.stdout.readlines():
  182. for mset in line.strip('%s' % os.linesep).split(' '):
  183. if len(mset) == 0:
  184. continue
  185. mapsets.append(mset)
  186. except:
  187. raise gcmd.CmdError(_('Unable to get list of accessible mapsets.'))
  188. ListSortLower(mapsets)
  189. return mapsets
  190. def ListSortLower(list):
  191. """Sort list items (not case-sensitive)"""
  192. list.sort(cmp=lambda x, y: cmp(x.lower(), y.lower()))
  193. def GetVectorNumberOfLayers(vector):
  194. """Get list of vector layers"""
  195. cmdlist = ['v.category',
  196. 'input=%s' % vector,
  197. 'option=report']
  198. layers = []
  199. for line in gcmd.Command(cmdlist, rerr=None).ReadStdOutput():
  200. if not 'Layer' in line:
  201. continue
  202. value = line.split(':')[1].strip()
  203. if '/' in value: # value/name
  204. layers.append(value.split('/')[0])
  205. else:
  206. layers.append(value)
  207. return layers
  208. def Deg2DMS(lon, lat):
  209. """Convert deg value to dms string
  210. @param lat latitude
  211. @param lon longitude
  212. @return DMS string
  213. @return empty string on error
  214. """
  215. try:
  216. flat = float(lat)
  217. flon = float(lon)
  218. except ValueError:
  219. return ''
  220. # fix longitude
  221. while flon > 180.0:
  222. flon -= 360.0
  223. while flon < -180.0:
  224. flon += 360.0
  225. # hemisphere
  226. if flat < 0.0:
  227. flat = abs(flat)
  228. hlat = 'S'
  229. else:
  230. hlat = 'N'
  231. if flon < 0.0:
  232. hlon = 'W'
  233. flon = abs(flon)
  234. else:
  235. hlon = 'E'
  236. slat = __ll_parts(flat)
  237. slon = __ll_parts(flon)
  238. return slon + hlon + '; ' + slat + hlat
  239. def __ll_parts(value):
  240. """Converts deg to d:m:s string"""
  241. if value == 0.0:
  242. return '00:00:00.0000'
  243. d = int(int(value))
  244. m = int((value - d) * 60)
  245. s = ((value - d) * 60 - m) * 60
  246. if m < 0:
  247. m = '00'
  248. elif m < 10:
  249. m = '0' + str(m)
  250. else:
  251. m = str(m)
  252. if s < 0:
  253. s = '00.0000'
  254. elif s < 10.0:
  255. s = '0%.4f' % s
  256. else:
  257. s = '%.4f' % s
  258. return str(d) + ':' + m + ':' + s
  259. def reexec_with_pythonw():
  260. """Re-execute Python on Mac OS"""
  261. if sys.platform == 'darwin' and \
  262. not sys.executable.endswith('MacOS/Python'):
  263. print >> sys.stderr, 're-executing using pythonw'
  264. os.execvp('pythonw', ['pythonw', __file__] + sys.argv[1:])