utils.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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, string = True):
  213. """!Convert deg value to dms string
  214. @param lon longitude (x)
  215. @param lat latitude (y)
  216. @param string True to return string otherwise tuple
  217. @return DMS string or tuple of values
  218. @return empty string on error
  219. """
  220. try:
  221. flat = float(lat)
  222. flon = float(lon)
  223. except ValueError:
  224. if string:
  225. return ''
  226. else:
  227. return None
  228. # fix longitude
  229. while flon > 180.0:
  230. flon -= 360.0
  231. while flon < -180.0:
  232. flon += 360.0
  233. # hemisphere
  234. if flat < 0.0:
  235. flat = abs(flat)
  236. hlat = 'S'
  237. else:
  238. hlat = 'N'
  239. if flon < 0.0:
  240. hlon = 'W'
  241. flon = abs(flon)
  242. else:
  243. hlon = 'E'
  244. slat = __ll_parts(flat)
  245. slon = __ll_parts(flon)
  246. if string:
  247. return slon + hlon + '; ' + slat + hlat
  248. return (slon + hlon, slat + hlat)
  249. def DMS2Deg(lon, lat):
  250. """!Convert dms value to deg
  251. @param lon longitude (x)
  252. @param lat latitude (y)
  253. @return tuple of converted values
  254. @return ValueError on error
  255. """
  256. x = __ll_parts(lon, reverse = True)
  257. y = __ll_parts(lat, reverse = True)
  258. return (x, y)
  259. def __ll_parts(value, reverse = False):
  260. """!Converts deg to d:m:s string
  261. @param value value to be converted
  262. @param reverse True to convert from d:m:s to deg
  263. @return converted value (string/float)
  264. @return ValueError on error (reverse == True)
  265. """
  266. if not reverse:
  267. if value == 0.0:
  268. return '00:00:00.0000'
  269. d = int(int(value))
  270. m = int((value - d) * 60)
  271. s = ((value - d) * 60 - m) * 60
  272. if m < 0:
  273. m = '00'
  274. elif m < 10:
  275. m = '0' + str(m)
  276. else:
  277. m = str(m)
  278. if s < 0:
  279. s = '00.0000'
  280. elif s < 10.0:
  281. s = '0%.4f' % s
  282. else:
  283. s = '%.4f' % s
  284. return str(d) + ':' + m + ':' + s
  285. else: # -> reverse
  286. try:
  287. d, m, s = value.split(':')
  288. hs = s[-1]
  289. s = s[:-1]
  290. except ValueError:
  291. try:
  292. d, m = value.split(':')
  293. hs = m[-1]
  294. m = m[:-1]
  295. s = '0.0'
  296. except ValueError:
  297. try:
  298. d = value
  299. hs = d[-1]
  300. d = d[:-1]
  301. m = '0'
  302. s = '0.0'
  303. except ValueError:
  304. raise ValueError
  305. if hs not in ('N', 'S', 'E', 'W'):
  306. raise ValueError
  307. coef = 1.0
  308. if hs in ('S', 'W'):
  309. coef = -1.0
  310. fm = int(m) / 60.0
  311. fs = float(s) / (60 * 60)
  312. return coef * (float(d) + fm + fs)
  313. def GetCmdString(cmd):
  314. """
  315. Get GRASS command as string.
  316. @param cmd GRASS command given as tuple
  317. @return command string
  318. """
  319. scmd = ''
  320. if not cmd:
  321. return ''
  322. scmd = cmd[0]
  323. for k, v in cmd[1].iteritems():
  324. scmd += ' %s=%s' % (k, v)
  325. return scmd
  326. def CmdToTuple(cmd):
  327. """!Convert command list to tuple for gcmd.RunCommand()"""
  328. if len(cmd) < 1:
  329. return None
  330. dcmd = {}
  331. for item in cmd[1:]:
  332. if '=' in item:
  333. key, value = item.split('=', 1)
  334. dcmd[str(key)] = str(value)
  335. else: # -> flags
  336. if not dcmd.has_key('flags'):
  337. dcmd['flags'] = ''
  338. dcmd['flags'] += item.replace('-', '')
  339. return (cmd[0],
  340. dcmd)
  341. def PathJoin(*args):
  342. """!Check path created by os.path.join"""
  343. path = os.path.join(*args)
  344. if platform.system() == 'Windows' and \
  345. '/' in path:
  346. return path[1].upper() + ':\\' + path[3:].replace('/', '\\')
  347. return path
  348. def reexec_with_pythonw():
  349. """!Re-execute Python on Mac OS"""
  350. if sys.platform == 'darwin' and \
  351. not sys.executable.endswith('MacOS/Python'):
  352. print >> sys.stderr, 're-executing using pythonw'
  353. os.execvp('pythonw', ['pythonw', __file__] + sys.argv[1:])
  354. def ReadEpsgCodes(path):
  355. """!Read EPSG code from the file
  356. @param path full path to the file with EPSG codes
  357. @return dictionary of EPSG code
  358. @return string on error
  359. """
  360. epsgCodeDict = dict()
  361. try:
  362. f = open(path, "r")
  363. i = 0
  364. code = None
  365. for line in f.readlines():
  366. line = line.strip()
  367. if len(line) < 1:
  368. continue
  369. if line[0] == '#':
  370. descr = line[1:].strip()
  371. elif line[0] == '<':
  372. code, params = line.split(" ", 1)
  373. code = int(code.replace('<', '').replace('>', ''))
  374. if code is not None:
  375. epsgCodeDict[code] = (descr, params)
  376. code = None
  377. i += 1
  378. f.close()
  379. except StandardError, e:
  380. return str(e)
  381. return epsgCodeDict
  382. def ReprojectCoordinates(coord, projOut, projIn = None, flags = ''):
  383. """!Reproject coordinates
  384. @param coord coordinates given as tuple
  385. @param projOut output projection
  386. @param projIn input projection (use location projection settings)
  387. @return reprojected coordinates (returned as tuple)
  388. """
  389. if not projIn:
  390. projIn = gcmd.RunCommand('g.proj',
  391. flags = 'jf',
  392. read = True).rstrip('\n')
  393. coors = gcmd.RunCommand('m.proj',
  394. flags = flags,
  395. input = '-',
  396. proj_in = projIn,
  397. proj_out = projOut,
  398. fs = ';',
  399. stdin = '%f;%f' % (coord[0], coord[1]),
  400. read = True)
  401. if coors:
  402. coors = coors.split(';')
  403. e = coors[0]
  404. n = coors[1]
  405. try:
  406. proj = projOut.split(' ')[0].split('=')[1]
  407. except IndexError:
  408. proj = ''
  409. if proj in ('ll', 'latlong', 'longlat') and 'd' not in flags:
  410. return (proj, (e, n))
  411. else:
  412. return (proj, (float(e), float(n)))
  413. return (None, None)