utils.py 20 KB

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