utils.py 21 KB

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