utils.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  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 re
  18. import globalvar
  19. sys.path.append(os.path.join(globalvar.ETCDIR, "python"))
  20. from grass.script import core as grass
  21. from grass.script import task as gtask
  22. import gcmd
  23. from debug import Debug
  24. def normalize_whitespace(text):
  25. """!Remove redundant whitespace from a string"""
  26. return string.join(string.split(text), ' ')
  27. def split(s):
  28. """!Platform spefic shlex.split"""
  29. if sys.version_info >= (2, 6):
  30. return shlex.split(s, posix = (sys.platform != "win32"))
  31. elif sys.platform == "win32":
  32. return shlex.split(s.replace('\\', r'\\'))
  33. else:
  34. return shlex.split(s)
  35. def GetTempfile(pref=None):
  36. """!Creates GRASS temporary file using defined prefix.
  37. @todo Fix path on MS Windows/MSYS
  38. @param pref prefer the given path
  39. @return Path to file name (string) or None
  40. """
  41. import gcmd
  42. ret = gcmd.RunCommand('g.tempfile',
  43. read = True,
  44. pid = os.getpid())
  45. tempfile = ret.splitlines()[0].strip()
  46. # FIXME
  47. # ugly hack for MSYS (MS Windows)
  48. if platform.system() == 'Windows':
  49. tempfile = tempfile.replace("/", "\\")
  50. try:
  51. path, file = os.path.split(tempfile)
  52. if pref:
  53. return os.path.join(pref, file)
  54. else:
  55. return tempfile
  56. except:
  57. return None
  58. def GetLayerNameFromCmd(dcmd, fullyQualified = False, param = None,
  59. layerType = None):
  60. """!Get map name from GRASS command
  61. Parameter dcmd can be modified when first parameter is not
  62. defined.
  63. @param dcmd GRASS command (given as list)
  64. @param fullyQualified change map name to be fully qualified
  65. @param param params directory
  66. @param layerType check also layer type ('raster', 'vector', '3d-raster', ...)
  67. @return tuple (name, found)
  68. """
  69. mapname = ''
  70. found = True
  71. if len(dcmd) < 1:
  72. return mapname, False
  73. if 'd.grid' == dcmd[0]:
  74. mapname = 'grid'
  75. elif 'd.geodesic' in dcmd[0]:
  76. mapname = 'geodesic'
  77. elif 'd.rhumbline' in dcmd[0]:
  78. mapname = 'rhumb'
  79. else:
  80. params = list()
  81. for idx in range(len(dcmd)):
  82. try:
  83. p, v = dcmd[idx].split('=', 1)
  84. except ValueError:
  85. continue
  86. if p == param:
  87. params = [(idx, p, v)]
  88. break
  89. if p in ('map', 'input', 'layer',
  90. 'red', 'blue', 'green',
  91. 'h_map', 's_map', 'i_map',
  92. 'reliefmap', 'labels'):
  93. params.append((idx, p, v))
  94. if len(params) < 1:
  95. if len(dcmd) > 1 and '=' not in dcmd[1]:
  96. task = gtask.parse_interface(dcmd[0])
  97. p = task.get_options()['params'][0].get('name', '')
  98. params.append((1, p, dcmd[1]))
  99. else:
  100. return mapname, False
  101. mapname = params[0][2]
  102. mapset = ''
  103. if fullyQualified and '@' not in mapname:
  104. if layerType in ('raster', 'vector', '3d-raster', 'rgb', 'his'):
  105. try:
  106. if layerType in ('raster', 'rgb', 'his'):
  107. findType = 'cell'
  108. else:
  109. findType = layerType
  110. mapset = grass.find_file(mapname, element = findType)['mapset']
  111. except AttributeError, e: # not found
  112. return '', False
  113. if not mapset:
  114. found = False
  115. else:
  116. mapset = grass.gisenv()['MAPSET']
  117. # update dcmd
  118. for i, p, v in params:
  119. if p == 'layer':
  120. continue
  121. dcmd[i] = p + '=' + v
  122. if mapset:
  123. dcmd[i] += '@' + mapset
  124. maps = list()
  125. ogr = False
  126. for i, p, v in params:
  127. if v.lower().rfind('@ogr') > -1:
  128. ogr = True
  129. if p == 'layer' and not ogr:
  130. continue
  131. maps.append(dcmd[i].split('=', 1)[1])
  132. mapname = '\n'.join(maps)
  133. return mapname, found
  134. def GetValidLayerName(name):
  135. """!Make layer name SQL compliant, based on G_str_to_sql()
  136. @todo: Better use directly GRASS Python SWIG...
  137. """
  138. retName = str(name).strip()
  139. # check if name is fully qualified
  140. if '@' in retName:
  141. retName, mapset = retName.split('@')
  142. else:
  143. mapset = None
  144. cIdx = 0
  145. retNameList = list(retName)
  146. for c in retNameList:
  147. if not (c >= 'A' and c <= 'Z') and \
  148. not (c >= 'a' and c <= 'z') and \
  149. not (c >= '0' and c <= '9'):
  150. retNameList[cIdx] = '_'
  151. cIdx += 1
  152. retName = ''.join(retNameList)
  153. if not (retName[0] >= 'A' and retName[0] <= 'Z') and \
  154. not (retName[0] >= 'a' and retName[0] <= 'z'):
  155. retName = 'x' + retName[1:]
  156. if mapset:
  157. retName = retName + '@' + mapset
  158. return retName
  159. def ListOfCatsToRange(cats):
  160. """!Convert list of category number to range(s)
  161. Used for example for d.vect cats=[range]
  162. @param cats category list
  163. @return category range string
  164. @return '' on error
  165. """
  166. catstr = ''
  167. try:
  168. cats = map(int, cats)
  169. except:
  170. return catstr
  171. i = 0
  172. while i < len(cats):
  173. next = 0
  174. j = i + 1
  175. while j < len(cats):
  176. if cats[i + next] == cats[j] - 1:
  177. next += 1
  178. else:
  179. break
  180. j += 1
  181. if next > 1:
  182. catstr += '%d-%d,' % (cats[i], cats[i + next])
  183. i += next + 1
  184. else:
  185. catstr += '%d,' % (cats[i])
  186. i += 1
  187. return catstr.strip(',')
  188. def ListOfMapsets(get = 'ordered'):
  189. """!Get list of available/accessible mapsets
  190. @param get method ('all', 'accessible', 'ordered')
  191. @return list of mapsets
  192. @return None on error
  193. """
  194. mapsets = []
  195. if get == 'all' or get == 'ordered':
  196. ret = gcmd.RunCommand('g.mapsets',
  197. read = True,
  198. quiet = True,
  199. flags = 'l',
  200. fs = 'newline')
  201. if ret:
  202. mapsets = ret.splitlines()
  203. ListSortLower(mapsets)
  204. else:
  205. return None
  206. if get == 'accessible' or get == 'ordered':
  207. ret = gcmd.RunCommand('g.mapsets',
  208. read = True,
  209. quiet = True,
  210. flags = 'p',
  211. fs = 'newline')
  212. if ret:
  213. if get == 'accessible':
  214. mapsets = ret.splitlines()
  215. else:
  216. mapsets_accessible = ret.splitlines()
  217. for mapset in mapsets_accessible:
  218. mapsets.remove(mapset)
  219. mapsets = mapsets_accessible + mapsets
  220. else:
  221. return None
  222. return mapsets
  223. def ListSortLower(list):
  224. """!Sort list items (not case-sensitive)"""
  225. list.sort(cmp=lambda x, y: cmp(x.lower(), y.lower()))
  226. def GetVectorNumberOfLayers(parent, vector):
  227. """!Get list of vector layers"""
  228. layers = list()
  229. if not vector:
  230. return layers
  231. fullname = grass.find_file(name = vector, element = 'vector')['fullname']
  232. if not fullname:
  233. Debug.msg(5, "utils.GetVectorNumberOfLayers(): vector map '%s' not found" % vector)
  234. return layers
  235. ret, out, msg = gcmd.RunCommand('v.db.connect',
  236. getErrorMsg = True,
  237. read = True,
  238. flags = 'g',
  239. map = fullname,
  240. fs = ';')
  241. if ret != 0:
  242. sys.stderr.write(_("Vector map <%(map)s>: %(msg)s\n") % { 'map' : fullname, 'msg' : msg })
  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. """!Decode string using system encoding
  531. @param string string to be decoded
  532. @return decoded string
  533. """
  534. if not string:
  535. return string
  536. enc = locale.getdefaultlocale()[1]
  537. if enc:
  538. Debug.msg(5, "DecodeString(): enc=%s" % enc)
  539. return string.decode(enc)
  540. return string
  541. def EncodeString(string):
  542. """!Return encoded string using system locales
  543. @param string string to be encoded
  544. @return encoded string
  545. """
  546. if not string:
  547. return string
  548. enc = locale.getdefaultlocale()[1]
  549. if enc:
  550. Debug.msg(5, "EncodeString(): enc=%s" % enc)
  551. return string.encode(enc)
  552. return string
  553. def _getGDALFormats():
  554. """!Get dictionary of avaialble GDAL drivers"""
  555. ret = grass.read_command('r.in.gdal',
  556. quiet = True,
  557. flags = 'f')
  558. return _parseFormats(ret), _parseFormats(ret, writableOnly = True)
  559. def _getOGRFormats():
  560. """!Get dictionary of avaialble OGR drivers"""
  561. ret = grass.read_command('v.in.ogr',
  562. quiet = True,
  563. flags = 'f')
  564. return _parseFormats(ret), _parseFormats(ret, writableOnly = True)
  565. def _parseFormats(output, writableOnly = False):
  566. """!Parse r.in.gdal/v.in.ogr -f output"""
  567. formats = { 'file' : list(),
  568. 'database' : list(),
  569. 'protocol' : list()
  570. }
  571. if not output:
  572. return formats
  573. patt = None
  574. if writableOnly:
  575. patt = re.compile('\(rw\+?\)$', re.IGNORECASE)
  576. for line in output.splitlines():
  577. key, name = map(lambda x: x.strip(), line.strip().rsplit(':', -1))
  578. if writableOnly and not patt.search(key):
  579. continue
  580. if name in ('Memory', 'Virtual Raster', 'In Memory Raster'):
  581. continue
  582. if name in ('PostgreSQL', 'SQLite',
  583. 'ODBC', 'ESRI Personal GeoDatabase',
  584. 'Rasterlite',
  585. 'PostGIS WKT Raster driver'):
  586. formats['database'].append(name)
  587. elif name in ('GeoJSON',
  588. 'OGC Web Coverage Service',
  589. 'OGC Web Map Service',
  590. 'HTTP Fetching Wrapper'):
  591. formats['protocol'].append(name)
  592. else:
  593. formats['file'].append(name)
  594. for items in formats.itervalues():
  595. items.sort()
  596. return formats
  597. formats = None
  598. def GetFormats(writableOnly = False):
  599. """!Get GDAL/OGR formats"""
  600. global formats
  601. if not formats:
  602. gdalAll, gdalWritable = _getGDALFormats()
  603. ogrAll, ogrWritable = _getOGRFormats()
  604. formats = {
  605. 'all' : {
  606. 'gdal' : gdalAll,
  607. 'ogr' : ogrAll,
  608. },
  609. 'writable' : {
  610. 'gdal' : gdalWritable,
  611. 'ogr' : ogrWritable,
  612. },
  613. }
  614. if writableOnly:
  615. return formats['writable']
  616. return formats['all']
  617. def GetSettingsPath():
  618. """!Get full path to the settings directory
  619. """
  620. try:
  621. verFd = open(os.path.join(globalvar.ETCDIR, "VERSIONNUMBER"))
  622. version = int(verFd.readlines()[0].split(' ')[0].split('.')[0])
  623. except (IOError, ValueError, TypeError, IndexError), e:
  624. sys.exit(_("ERROR: Unable to determine GRASS version. Details: %s") % e)
  625. verFd.close()
  626. # keep location of settings files rc and wx in sync with lib/init/grass.py
  627. if sys.platform == 'win32':
  628. return os.path.join(os.getenv('APPDATA'), 'grass%d' % version)
  629. return os.path.join(os.getenv('HOME'), '.grass%d' % version)