utils.py 8.7 KB

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