utils.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  1. """!
  2. @package core.utils
  3. @brief Misc utilities for wxGUI
  4. (C) 2007-2009, 2011 by the GRASS Development Team
  5. This program is free software under the GNU General Public License
  6. (>=v2). Read the file COPYING that comes with GRASS for details.
  7. @author Martin Landa <landa.martin gmail.com>
  8. @author Jachym Cepicky
  9. """
  10. import os
  11. import sys
  12. import platform
  13. import string
  14. import glob
  15. import shlex
  16. import re
  17. from core.globalvar import ETCDIR
  18. sys.path.append(os.path.join(ETCDIR, "python"))
  19. from grass.script import core as grass
  20. from grass.script import task as gtask
  21. from core.gcmd import RunCommand
  22. from core.debug import Debug
  23. def normalize_whitespace(text):
  24. """!Remove redundant whitespace from a string"""
  25. return string.join(string.split(text), ' ')
  26. def split(s):
  27. """!Platform spefic shlex.split"""
  28. if sys.version_info >= (2, 6):
  29. return shlex.split(s, posix = (sys.platform != "win32"))
  30. elif sys.platform == "win32":
  31. return shlex.split(s.replace('\\', r'\\'))
  32. else:
  33. return shlex.split(s)
  34. def GetTempfile(pref=None):
  35. """!Creates GRASS temporary file using defined prefix.
  36. @todo Fix path on MS Windows/MSYS
  37. @param pref prefer the given path
  38. @return Path to file name (string) or None
  39. """
  40. ret = RunCommand('g.tempfile',
  41. read = True,
  42. pid = os.getpid())
  43. tempfile = ret.splitlines()[0].strip()
  44. # FIXME
  45. # ugly hack for MSYS (MS Windows)
  46. if platform.system() == 'Windows':
  47. tempfile = tempfile.replace("/", "\\")
  48. try:
  49. path, file = os.path.split(tempfile)
  50. if pref:
  51. return os.path.join(pref, file)
  52. else:
  53. return tempfile
  54. except:
  55. return None
  56. def GetLayerNameFromCmd(dcmd, fullyQualified = False, param = None,
  57. layerType = None):
  58. """!Get map name from GRASS command
  59. Parameter dcmd can be modified when first parameter is not
  60. defined.
  61. @param dcmd GRASS command (given as list)
  62. @param fullyQualified change map name to be fully qualified
  63. @param param params directory
  64. @param layerType check also layer type ('raster', 'vector', '3d-raster', ...)
  65. @return tuple (name, found)
  66. """
  67. mapname = ''
  68. found = True
  69. if len(dcmd) < 1:
  70. return mapname, False
  71. if 'd.grid' == dcmd[0]:
  72. mapname = 'grid'
  73. elif 'd.geodesic' in dcmd[0]:
  74. mapname = 'geodesic'
  75. elif 'd.rhumbline' in dcmd[0]:
  76. mapname = 'rhumb'
  77. else:
  78. params = list()
  79. for idx in range(len(dcmd)):
  80. try:
  81. p, v = dcmd[idx].split('=', 1)
  82. except ValueError:
  83. continue
  84. if p == param:
  85. params = [(idx, p, v)]
  86. break
  87. if p in ('map', 'input', 'layer',
  88. 'red', 'blue', 'green',
  89. 'h_map', 's_map', 'i_map',
  90. 'reliefmap', 'labels'):
  91. params.append((idx, p, v))
  92. if len(params) < 1:
  93. if len(dcmd) > 1 and '=' not in dcmd[1]:
  94. task = gtask.parse_interface(dcmd[0])
  95. p = task.get_options()['params'][0].get('name', '')
  96. params.append((1, p, dcmd[1]))
  97. else:
  98. return mapname, False
  99. mapname = params[0][2]
  100. mapset = ''
  101. if fullyQualified and '@' not in mapname:
  102. if layerType in ('raster', 'vector', '3d-raster', 'rgb', 'his'):
  103. try:
  104. if layerType in ('raster', 'rgb', 'his'):
  105. findType = 'cell'
  106. else:
  107. findType = layerType
  108. mapset = grass.find_file(mapname, element = findType)['mapset']
  109. except AttributeError, e: # not found
  110. return '', False
  111. if not mapset:
  112. found = False
  113. else:
  114. mapset = grass.gisenv()['MAPSET']
  115. # update dcmd
  116. for i, p, v in params:
  117. if p == 'layer':
  118. continue
  119. dcmd[i] = p + '=' + v
  120. if mapset:
  121. dcmd[i] += '@' + mapset
  122. maps = list()
  123. ogr = False
  124. for i, p, v in params:
  125. if v.lower().rfind('@ogr') > -1:
  126. ogr = True
  127. if p == 'layer' and not ogr:
  128. continue
  129. maps.append(dcmd[i].split('=', 1)[1])
  130. mapname = '\n'.join(maps)
  131. return mapname, found
  132. def GetValidLayerName(name):
  133. """!Make layer name SQL compliant, based on G_str_to_sql()
  134. @todo: Better use directly GRASS Python SWIG...
  135. """
  136. retName = str(name).strip()
  137. # check if name is fully qualified
  138. if '@' in retName:
  139. retName, mapset = retName.split('@')
  140. else:
  141. mapset = None
  142. cIdx = 0
  143. retNameList = list(retName)
  144. for c in retNameList:
  145. if not (c >= 'A' and c <= 'Z') and \
  146. not (c >= 'a' and c <= 'z') and \
  147. not (c >= '0' and c <= '9'):
  148. retNameList[cIdx] = '_'
  149. cIdx += 1
  150. retName = ''.join(retNameList)
  151. if not (retName[0] >= 'A' and retName[0] <= 'Z') and \
  152. not (retName[0] >= 'a' and retName[0] <= 'z'):
  153. retName = 'x' + retName[1:]
  154. if mapset:
  155. retName = retName + '@' + mapset
  156. return retName
  157. def ListOfCatsToRange(cats):
  158. """!Convert list of category number to range(s)
  159. Used for example for d.vect cats=[range]
  160. @param cats category list
  161. @return category range string
  162. @return '' on error
  163. """
  164. catstr = ''
  165. try:
  166. cats = map(int, cats)
  167. except:
  168. return catstr
  169. i = 0
  170. while i < len(cats):
  171. next = 0
  172. j = i + 1
  173. while j < len(cats):
  174. if cats[i + next] == cats[j] - 1:
  175. next += 1
  176. else:
  177. break
  178. j += 1
  179. if next > 1:
  180. catstr += '%d-%d,' % (cats[i], cats[i + next])
  181. i += next + 1
  182. else:
  183. catstr += '%d,' % (cats[i])
  184. i += 1
  185. return catstr.strip(',')
  186. def ListOfMapsets(get = 'ordered'):
  187. """!Get list of available/accessible mapsets
  188. @param get method ('all', 'accessible', 'ordered')
  189. @return list of mapsets
  190. @return None on error
  191. """
  192. mapsets = []
  193. if get == 'all' or get == 'ordered':
  194. ret = RunCommand('g.mapsets',
  195. read = True,
  196. quiet = True,
  197. flags = 'l',
  198. fs = 'newline')
  199. if ret:
  200. mapsets = ret.splitlines()
  201. ListSortLower(mapsets)
  202. else:
  203. return None
  204. if get == 'accessible' or get == 'ordered':
  205. ret = RunCommand('g.mapsets',
  206. read = True,
  207. quiet = True,
  208. flags = 'p',
  209. fs = 'newline')
  210. if ret:
  211. if get == 'accessible':
  212. mapsets = ret.splitlines()
  213. else:
  214. mapsets_accessible = ret.splitlines()
  215. for mapset in mapsets_accessible:
  216. mapsets.remove(mapset)
  217. mapsets = mapsets_accessible + mapsets
  218. else:
  219. return None
  220. return mapsets
  221. def ListSortLower(list):
  222. """!Sort list items (not case-sensitive)"""
  223. list.sort(cmp=lambda x, y: cmp(x.lower(), y.lower()))
  224. def GetVectorNumberOfLayers(parent, vector):
  225. """!Get list of vector layers"""
  226. layers = list()
  227. if not vector:
  228. return layers
  229. fullname = grass.find_file(name = vector, element = 'vector')['fullname']
  230. if not fullname:
  231. Debug.msg(5, "utils.GetVectorNumberOfLayers(): vector map '%s' not found" % vector)
  232. return layers
  233. ret, out, msg = RunCommand('v.db.connect',
  234. getErrorMsg = True,
  235. read = True,
  236. flags = 'g',
  237. map = fullname,
  238. fs = ';')
  239. if ret != 0:
  240. sys.stderr.write(_("Vector map <%(map)s>: %(msg)s\n") % { 'map' : fullname, 'msg' : msg })
  241. return layers
  242. else:
  243. Debug.msg(1, "GetVectorNumberOfLayers(): ret %s" % ret)
  244. for line in ret.splitlines():
  245. try:
  246. layer = line.split(';')[0]
  247. if '/' in layer:
  248. layer = layer.split('/')[0]
  249. layers.append(layer)
  250. except IndexError:
  251. pass
  252. Debug.msg(3, "utils.GetVectorNumberOfLayers(): vector=%s -> %s" % \
  253. (fullname, ','.join(layers)))
  254. return layers
  255. def Deg2DMS(lon, lat, string = True, hemisphere = True, precision = 3):
  256. """!Convert deg value to dms string
  257. @param lon longitude (x)
  258. @param lat latitude (y)
  259. @param string True to return string otherwise tuple
  260. @param hemisphere print hemisphere
  261. @param precision seconds precision
  262. @return DMS string or tuple of values
  263. @return empty string on error
  264. """
  265. try:
  266. flat = float(lat)
  267. flon = float(lon)
  268. except ValueError:
  269. if string:
  270. return ''
  271. else:
  272. return None
  273. # fix longitude
  274. while flon > 180.0:
  275. flon -= 360.0
  276. while flon < -180.0:
  277. flon += 360.0
  278. # hemisphere
  279. if hemisphere:
  280. if flat < 0.0:
  281. flat = abs(flat)
  282. hlat = 'S'
  283. else:
  284. hlat = 'N'
  285. if flon < 0.0:
  286. hlon = 'W'
  287. flon = abs(flon)
  288. else:
  289. hlon = 'E'
  290. else:
  291. flat = abs(flat)
  292. flon = abs(flon)
  293. hlon = ''
  294. hlat = ''
  295. slat = __ll_parts(flat, precision = precision)
  296. slon = __ll_parts(flon, precision = precision)
  297. if string:
  298. return slon + hlon + '; ' + slat + hlat
  299. return (slon + hlon, slat + hlat)
  300. def DMS2Deg(lon, lat):
  301. """!Convert dms value to deg
  302. @param lon longitude (x)
  303. @param lat latitude (y)
  304. @return tuple of converted values
  305. @return ValueError on error
  306. """
  307. x = __ll_parts(lon, reverse = True)
  308. y = __ll_parts(lat, reverse = True)
  309. return (x, y)
  310. def __ll_parts(value, reverse = False, precision = 3):
  311. """!Converts deg to d:m:s string
  312. @param value value to be converted
  313. @param reverse True to convert from d:m:s to deg
  314. @param precision seconds precision (ignored if reverse is True)
  315. @return converted value (string/float)
  316. @return ValueError on error (reverse == True)
  317. """
  318. if not reverse:
  319. if value == 0.0:
  320. return '%s%.*f' % ('00:00:0', precision, 0.0)
  321. d = int(int(value))
  322. m = int((value - d) * 60)
  323. s = ((value - d) * 60 - m) * 60
  324. if m < 0:
  325. m = '00'
  326. elif m < 10:
  327. m = '0' + str(m)
  328. else:
  329. m = str(m)
  330. if s < 0:
  331. s = '00.0000'
  332. elif s < 10.0:
  333. s = '0%.*f' % (precision, s)
  334. else:
  335. s = '%.*f' % (precision, s)
  336. return str(d) + ':' + m + ':' + s
  337. else: # -> reverse
  338. try:
  339. d, m, s = value.split(':')
  340. hs = s[-1]
  341. s = s[:-1]
  342. except ValueError:
  343. try:
  344. d, m = value.split(':')
  345. hs = m[-1]
  346. m = m[:-1]
  347. s = '0.0'
  348. except ValueError:
  349. try:
  350. d = value
  351. hs = d[-1]
  352. d = d[:-1]
  353. m = '0'
  354. s = '0.0'
  355. except ValueError:
  356. raise ValueError
  357. if hs not in ('N', 'S', 'E', 'W'):
  358. raise ValueError
  359. coef = 1.0
  360. if hs in ('S', 'W'):
  361. coef = -1.0
  362. fm = int(m) / 60.0
  363. fs = float(s) / (60 * 60)
  364. return coef * (float(d) + fm + fs)
  365. def GetCmdString(cmd):
  366. """
  367. Get GRASS command as string.
  368. @param cmd GRASS command given as dictionary
  369. @return command string
  370. """
  371. scmd = ''
  372. if not cmd:
  373. return scmd
  374. scmd = cmd[0]
  375. if 'flags' in cmd[1]:
  376. for flag in cmd[1]['flags']:
  377. scmd += ' -' + flag
  378. for flag in ('verbose', 'quiet', 'overwrite'):
  379. if flag in cmd[1] and cmd[1][flag] is True:
  380. scmd += ' --' + flag
  381. for k, v in cmd[1].iteritems():
  382. if k in ('flags', 'verbose', 'quiet', 'overwrite'):
  383. continue
  384. scmd += ' %s=%s' % (k, v)
  385. return scmd
  386. def CmdToTuple(cmd):
  387. """!Convert command list to tuple for gcmd.RunCommand()"""
  388. if len(cmd) < 1:
  389. return None
  390. dcmd = {}
  391. for item in cmd[1:]:
  392. if '=' in item: # params
  393. key, value = item.split('=', 1)
  394. dcmd[str(key)] = str(value).replace('"', '')
  395. elif item[:2] == '--': # long flags
  396. flag = item[2:]
  397. if flag in ('verbose', 'quiet', 'overwrite'):
  398. dcmd[str(flag)] = True
  399. else: # -> flags
  400. if 'flags' not in dcmd:
  401. dcmd['flags'] = ''
  402. dcmd['flags'] += item.replace('-', '')
  403. return (cmd[0],
  404. dcmd)
  405. def PathJoin(*args):
  406. """!Check path created by os.path.join"""
  407. path = os.path.join(*args)
  408. if platform.system() == 'Windows' and \
  409. '/' in path:
  410. return path[1].upper() + ':\\' + path[3:].replace('/', '\\')
  411. return path
  412. def ReadEpsgCodes(path):
  413. """!Read EPSG code from the file
  414. @param path full path to the file with EPSG codes
  415. @return dictionary of EPSG code
  416. @return string on error
  417. """
  418. epsgCodeDict = dict()
  419. try:
  420. try:
  421. f = open(path, "r")
  422. except IOError:
  423. return _("failed to open '%s'" % path)
  424. i = 0
  425. code = None
  426. for line in f.readlines():
  427. line = line.strip()
  428. if len(line) < 1:
  429. continue
  430. if line[0] == '#':
  431. descr = line[1:].strip()
  432. elif line[0] == '<':
  433. code, params = line.split(" ", 1)
  434. try:
  435. code = int(code.replace('<', '').replace('>', ''))
  436. except ValueError:
  437. return e
  438. if code is not None:
  439. epsgCodeDict[code] = (descr, params)
  440. code = None
  441. i += 1
  442. f.close()
  443. except StandardError, e:
  444. return e
  445. return epsgCodeDict
  446. def ReprojectCoordinates(coord, projOut, projIn = None, flags = ''):
  447. """!Reproject coordinates
  448. @param coord coordinates given as tuple
  449. @param projOut output projection
  450. @param projIn input projection (use location projection settings)
  451. @return reprojected coordinates (returned as tuple)
  452. """
  453. coors = RunCommand('m.proj',
  454. flags = flags,
  455. input = '-',
  456. proj_input = projIn,
  457. proj_output = projOut,
  458. fs = ';',
  459. stdin = '%f;%f' % (coord[0], coord[1]),
  460. read = True)
  461. if coors:
  462. coors = coors.split(';')
  463. e = coors[0]
  464. n = coors[1]
  465. try:
  466. proj = projOut.split(' ')[0].split('=')[1]
  467. except IndexError:
  468. proj = ''
  469. if proj in ('ll', 'latlong', 'longlat') and 'd' not in flags:
  470. return (proj, (e, n))
  471. else:
  472. try:
  473. return (proj, (float(e), float(n)))
  474. except ValueError:
  475. return (None, None)
  476. return (None, None)
  477. def GetListOfLocations(dbase):
  478. """!Get list of GRASS locations in given dbase
  479. @param dbase GRASS database path
  480. @return list of locations (sorted)
  481. """
  482. listOfLocations = list()
  483. try:
  484. for location in glob.glob(os.path.join(dbase, "*")):
  485. try:
  486. if os.path.join(location, "PERMANENT") in glob.glob(os.path.join(location, "*")):
  487. listOfLocations.append(os.path.basename(location))
  488. except:
  489. pass
  490. except UnicodeEncodeError, e:
  491. raise e
  492. ListSortLower(listOfLocations)
  493. return listOfLocations
  494. def GetListOfMapsets(dbase, location, selectable = False):
  495. """!Get list of mapsets in given GRASS location
  496. @param dbase GRASS database path
  497. @param location GRASS location
  498. @param selectable True to get list of selectable mapsets, otherwise all
  499. @return list of mapsets - sorted (PERMANENT first)
  500. """
  501. listOfMapsets = list()
  502. if selectable:
  503. ret = RunCommand('g.mapset',
  504. read = True,
  505. flags = 'l',
  506. location = location,
  507. gisdbase = dbase)
  508. if not ret:
  509. return listOfMapsets
  510. for line in ret.rstrip().splitlines():
  511. listOfMapsets += line.split(' ')
  512. else:
  513. for mapset in glob.glob(os.path.join(dbase, location, "*")):
  514. if os.path.isdir(mapset) and \
  515. os.path.isfile(os.path.join(dbase, location, mapset, "WIND")):
  516. listOfMapsets.append(os.path.basename(mapset))
  517. ListSortLower(listOfMapsets)
  518. return listOfMapsets
  519. def GetColorTables():
  520. """!Get list of color tables"""
  521. ret = RunCommand('r.colors',
  522. read = True,
  523. flags = 'l')
  524. if not ret:
  525. return list()
  526. return ret.splitlines()
  527. def _getGDALFormats():
  528. """!Get dictionary of avaialble GDAL drivers"""
  529. ret = grass.read_command('r.in.gdal',
  530. quiet = True,
  531. flags = 'f')
  532. return _parseFormats(ret), _parseFormats(ret, writableOnly = True)
  533. def _getOGRFormats():
  534. """!Get dictionary of avaialble OGR drivers"""
  535. ret = grass.read_command('v.in.ogr',
  536. quiet = True,
  537. flags = 'f')
  538. return _parseFormats(ret), _parseFormats(ret, writableOnly = True)
  539. def _parseFormats(output, writableOnly = False):
  540. """!Parse r.in.gdal/v.in.ogr -f output"""
  541. formats = { 'file' : list(),
  542. 'database' : list(),
  543. 'protocol' : list()
  544. }
  545. if not output:
  546. return formats
  547. patt = None
  548. if writableOnly:
  549. patt = re.compile('\(rw\+?\)$', re.IGNORECASE)
  550. for line in output.splitlines():
  551. key, name = map(lambda x: x.strip(), line.strip().rsplit(':', -1))
  552. if writableOnly and not patt.search(key):
  553. continue
  554. if name in ('Memory', 'Virtual Raster', 'In Memory Raster'):
  555. continue
  556. if name in ('PostgreSQL', 'SQLite',
  557. 'ODBC', 'ESRI Personal GeoDatabase',
  558. 'Rasterlite',
  559. 'PostGIS WKT Raster driver'):
  560. formats['database'].append(name)
  561. elif name in ('GeoJSON',
  562. 'OGC Web Coverage Service',
  563. 'OGC Web Map Service',
  564. 'HTTP Fetching Wrapper'):
  565. formats['protocol'].append(name)
  566. else:
  567. formats['file'].append(name)
  568. for items in formats.itervalues():
  569. items.sort()
  570. return formats
  571. formats = None
  572. def GetFormats(writableOnly = False):
  573. """!Get GDAL/OGR formats"""
  574. global formats
  575. if not formats:
  576. gdalAll, gdalWritable = _getGDALFormats()
  577. ogrAll, ogrWritable = _getOGRFormats()
  578. formats = {
  579. 'all' : {
  580. 'gdal' : gdalAll,
  581. 'ogr' : ogrAll,
  582. },
  583. 'writable' : {
  584. 'gdal' : gdalWritable,
  585. 'ogr' : ogrWritable,
  586. },
  587. }
  588. if writableOnly:
  589. return formats['writable']
  590. return formats['all']
  591. def GetSettingsPath():
  592. """!Get full path to the settings directory
  593. """
  594. try:
  595. verFd = open(os.path.join(ETCDIR, "VERSIONNUMBER"))
  596. version = int(verFd.readlines()[0].split(' ')[0].split('.')[0])
  597. except (IOError, ValueError, TypeError, IndexError), e:
  598. sys.exit(_("ERROR: Unable to determine GRASS version. Details: %s") % e)
  599. verFd.close()
  600. # keep location of settings files rc and wx in sync with lib/init/grass.py
  601. if sys.platform == 'win32':
  602. return os.path.join(os.getenv('APPDATA'), 'grass%d' % version)
  603. return os.path.join(os.getenv('HOME'), '.grass%d' % version)