utils.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753
  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(parent, 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. parent = parent,
  233. flags = 'g',
  234. read = True,
  235. map = fullname,
  236. fs = ';')
  237. if not ret:
  238. return layers
  239. for line in ret.splitlines():
  240. try:
  241. layer = line.split(';')[0]
  242. if '/' in layer:
  243. layer = layer.split('/')[0]
  244. layers.append(layer)
  245. except IndexError:
  246. pass
  247. Debug.msg(3, "utils.GetVectorNumberOfLayers(): vector=%s -> %s" % \
  248. (fullname, ','.join(layers)))
  249. return layers
  250. def Deg2DMS(lon, lat, string = True, hemisphere = True, precision = 3):
  251. """!Convert deg value to dms string
  252. @param lon longitude (x)
  253. @param lat latitude (y)
  254. @param string True to return string otherwise tuple
  255. @param hemisphere print hemisphere
  256. @param precision seconds precision
  257. @return DMS string or tuple of values
  258. @return empty string on error
  259. """
  260. try:
  261. flat = float(lat)
  262. flon = float(lon)
  263. except ValueError:
  264. if string:
  265. return ''
  266. else:
  267. return None
  268. # fix longitude
  269. while flon > 180.0:
  270. flon -= 360.0
  271. while flon < -180.0:
  272. flon += 360.0
  273. # hemisphere
  274. if hemisphere:
  275. if flat < 0.0:
  276. flat = abs(flat)
  277. hlat = 'S'
  278. else:
  279. hlat = 'N'
  280. if flon < 0.0:
  281. hlon = 'W'
  282. flon = abs(flon)
  283. else:
  284. hlon = 'E'
  285. else:
  286. flat = abs(flat)
  287. flon = abs(flon)
  288. hlon = ''
  289. hlat = ''
  290. slat = __ll_parts(flat, precision = precision)
  291. slon = __ll_parts(flon, precision = precision)
  292. if string:
  293. return slon + hlon + '; ' + slat + hlat
  294. return (slon + hlon, slat + hlat)
  295. def DMS2Deg(lon, lat):
  296. """!Convert dms value to deg
  297. @param lon longitude (x)
  298. @param lat latitude (y)
  299. @return tuple of converted values
  300. @return ValueError on error
  301. """
  302. x = __ll_parts(lon, reverse = True)
  303. y = __ll_parts(lat, reverse = True)
  304. return (x, y)
  305. def __ll_parts(value, reverse = False, precision = 3):
  306. """!Converts deg to d:m:s string
  307. @param value value to be converted
  308. @param reverse True to convert from d:m:s to deg
  309. @param precision seconds precision (ignored if reverse is True)
  310. @return converted value (string/float)
  311. @return ValueError on error (reverse == True)
  312. """
  313. if not reverse:
  314. if value == 0.0:
  315. return '%s%.*f' % ('00:00:0', precision, 0.0)
  316. d = int(int(value))
  317. m = int((value - d) * 60)
  318. s = ((value - d) * 60 - m) * 60
  319. if m < 0:
  320. m = '00'
  321. elif m < 10:
  322. m = '0' + str(m)
  323. else:
  324. m = str(m)
  325. if s < 0:
  326. s = '00.0000'
  327. elif s < 10.0:
  328. s = '0%.*f' % (precision, s)
  329. else:
  330. s = '%.*f' % (precision, s)
  331. return str(d) + ':' + m + ':' + s
  332. else: # -> reverse
  333. try:
  334. d, m, s = value.split(':')
  335. hs = s[-1]
  336. s = s[:-1]
  337. except ValueError:
  338. try:
  339. d, m = value.split(':')
  340. hs = m[-1]
  341. m = m[:-1]
  342. s = '0.0'
  343. except ValueError:
  344. try:
  345. d = value
  346. hs = d[-1]
  347. d = d[:-1]
  348. m = '0'
  349. s = '0.0'
  350. except ValueError:
  351. raise ValueError
  352. if hs not in ('N', 'S', 'E', 'W'):
  353. raise ValueError
  354. coef = 1.0
  355. if hs in ('S', 'W'):
  356. coef = -1.0
  357. fm = int(m) / 60.0
  358. fs = float(s) / (60 * 60)
  359. return coef * (float(d) + fm + fs)
  360. def GetCmdString(cmd):
  361. """
  362. Get GRASS command as string.
  363. @param cmd GRASS command given as dictionary
  364. @return command string
  365. """
  366. scmd = ''
  367. if not cmd:
  368. return scmd
  369. scmd = cmd[0]
  370. if 'flags' in cmd[1]:
  371. for flag in cmd[1]['flags']:
  372. scmd += ' -' + flag
  373. for flag in ('verbose', 'quiet', 'overwrite'):
  374. if flag in cmd[1] and cmd[1][flag] is True:
  375. scmd += ' --' + flag
  376. for k, v in cmd[1].iteritems():
  377. if k in ('flags', 'verbose', 'quiet', 'overwrite'):
  378. continue
  379. scmd += ' %s=%s' % (k, v)
  380. return scmd
  381. def CmdToTuple(cmd):
  382. """!Convert command list to tuple for gcmd.RunCommand()"""
  383. if len(cmd) < 1:
  384. return None
  385. dcmd = {}
  386. for item in cmd[1:]:
  387. if '=' in item: # params
  388. key, value = item.split('=', 1)
  389. dcmd[str(key)] = str(value)
  390. elif item[:2] == '--': # long flags
  391. flag = item[2:]
  392. if flag in ('verbose', 'quiet', 'overwrite'):
  393. dcmd[str(flag)] = True
  394. else: # -> flags
  395. if 'flags' not in dcmd:
  396. dcmd['flags'] = ''
  397. dcmd['flags'] += item.replace('-', '')
  398. return (cmd[0],
  399. dcmd)
  400. def PathJoin(*args):
  401. """!Check path created by os.path.join"""
  402. path = os.path.join(*args)
  403. if platform.system() == 'Windows' and \
  404. '/' in path:
  405. return path[1].upper() + ':\\' + path[3:].replace('/', '\\')
  406. return path
  407. def ReadEpsgCodes(path):
  408. """!Read EPSG code from the file
  409. @param path full path to the file with EPSG codes
  410. @return dictionary of EPSG code
  411. @return string on error
  412. """
  413. epsgCodeDict = dict()
  414. try:
  415. try:
  416. f = open(path, "r")
  417. except IOError:
  418. return _("failed to open '%s'" % path)
  419. i = 0
  420. code = None
  421. for line in f.readlines():
  422. line = line.strip()
  423. if len(line) < 1:
  424. continue
  425. if line[0] == '#':
  426. descr = line[1:].strip()
  427. elif line[0] == '<':
  428. code, params = line.split(" ", 1)
  429. try:
  430. code = int(code.replace('<', '').replace('>', ''))
  431. except ValueError:
  432. return e
  433. if code is not None:
  434. epsgCodeDict[code] = (descr, params)
  435. code = None
  436. i += 1
  437. f.close()
  438. except StandardError, e:
  439. return e
  440. return epsgCodeDict
  441. def ReprojectCoordinates(coord, projOut, projIn = None, flags = ''):
  442. """!Reproject coordinates
  443. @param coord coordinates given as tuple
  444. @param projOut output projection
  445. @param projIn input projection (use location projection settings)
  446. @return reprojected coordinates (returned as tuple)
  447. """
  448. coors = gcmd.RunCommand('m.proj',
  449. flags = flags,
  450. input = '-',
  451. proj_input = projIn,
  452. proj_output = projOut,
  453. fs = ';',
  454. stdin = '%f;%f' % (coord[0], coord[1]),
  455. read = True)
  456. if coors:
  457. coors = coors.split(';')
  458. e = coors[0]
  459. n = coors[1]
  460. try:
  461. proj = projOut.split(' ')[0].split('=')[1]
  462. except IndexError:
  463. proj = ''
  464. if proj in ('ll', 'latlong', 'longlat') and 'd' not in flags:
  465. return (proj, (e, n))
  466. else:
  467. try:
  468. return (proj, (float(e), float(n)))
  469. except ValueError:
  470. return (None, None)
  471. return (None, None)
  472. def GetListOfLocations(dbase):
  473. """!Get list of GRASS locations in given dbase
  474. @param dbase GRASS database path
  475. @return list of locations (sorted)
  476. """
  477. listOfLocations = list()
  478. try:
  479. for location in glob.glob(os.path.join(dbase, "*")):
  480. try:
  481. if os.path.join(location, "PERMANENT") in glob.glob(os.path.join(location, "*")):
  482. listOfLocations.append(os.path.basename(location))
  483. except:
  484. pass
  485. except UnicodeEncodeError, e:
  486. raise e
  487. ListSortLower(listOfLocations)
  488. return listOfLocations
  489. def GetListOfMapsets(dbase, location, selectable = False):
  490. """!Get list of mapsets in given GRASS location
  491. @param dbase GRASS database path
  492. @param location GRASS location
  493. @param selectable True to get list of selectable mapsets, otherwise all
  494. @return list of mapsets - sorted (PERMANENT first)
  495. """
  496. listOfMapsets = list()
  497. if selectable:
  498. ret = gcmd.RunCommand('g.mapset',
  499. read = True,
  500. flags = 'l',
  501. location = location,
  502. gisdbase = dbase)
  503. if not ret:
  504. return listOfMapsets
  505. for line in ret.rstrip().splitlines():
  506. listOfMapsets += line.split(' ')
  507. else:
  508. for mapset in glob.glob(os.path.join(dbase, location, "*")):
  509. if os.path.isdir(mapset) and \
  510. os.path.isfile(os.path.join(dbase, location, mapset, "WIND")):
  511. listOfMapsets.append(os.path.basename(mapset))
  512. ListSortLower(listOfMapsets)
  513. return listOfMapsets
  514. def GetColorTables():
  515. """!Get list of color tables"""
  516. ret = gcmd.RunCommand('r.colors',
  517. read = True,
  518. flags = 'l')
  519. if not ret:
  520. return list()
  521. return ret.splitlines()
  522. def DecodeString(string):
  523. """!Return decoded string
  524. String is decoded as unicode, on failure
  525. are used system locales.
  526. @param string string to be decoded
  527. @return decoded string
  528. """
  529. try:
  530. return string.decode('utf-8')
  531. except LookupError:
  532. enc = locale.getdefaultlocale()[1]
  533. if enc:
  534. return string.decode(enc)
  535. return string
  536. def EncodeString(string):
  537. """!Return encoded string using system locales
  538. @param string string to be encoded
  539. @return encoded string
  540. """
  541. enc = locale.getdefaultlocale()[1]
  542. if enc:
  543. return string.encode(enc)
  544. return string
  545. def UnicodeString(string):
  546. """!Return unicode string
  547. @param string string to be converted
  548. @return unicode string
  549. """
  550. if isinstance(string, unicode):
  551. return string
  552. enc = locale.getdefaultlocale()[1]
  553. if enc:
  554. return unicode(string, enc)
  555. return string
  556. def _getGDALFormats():
  557. """!Get dictionary of avaialble GDAL drivers"""
  558. ret = grass.read_command('r.in.gdal',
  559. quiet = True,
  560. flags = 'f')
  561. return _parseFormats(ret)
  562. def _getOGRFormats():
  563. """!Get dictionary of avaialble OGR drivers"""
  564. ret = grass.read_command('v.in.ogr',
  565. quiet = True,
  566. flags = 'f')
  567. return _parseFormats(ret)
  568. def _parseFormats(output):
  569. """!Parse r.in.gdal/v.in.ogr -f output"""
  570. formats = { 'file' : list(),
  571. 'database' : list(),
  572. 'protocol' : list()
  573. }
  574. if not output:
  575. return formats
  576. for line in output.splitlines():
  577. format = line.strip().rsplit(':', -1)[1].strip()
  578. if format in ('Memory', 'Virtual Raster', 'In Memory Raster'):
  579. continue
  580. if format in ('PostgreSQL', 'SQLite',
  581. 'ODBC', 'ESRI Personal GeoDatabase',
  582. 'Rasterlite',
  583. 'PostGIS WKT Raster driver'):
  584. formats['database'].append(format)
  585. elif format in ('GeoJSON',
  586. 'OGC Web Coverage Service',
  587. 'OGC Web Map Service',
  588. 'HTTP Fetching Wrapper'):
  589. formats['protocol'].append(format)
  590. else:
  591. formats['file'].append(format)
  592. for items in formats.itervalues():
  593. items.sort()
  594. return formats
  595. formats = None
  596. def GetFormats():
  597. """!Get GDAL/OGR formats"""
  598. global formats
  599. if not formats:
  600. formats = {
  601. 'gdal' : _getGDALFormats(),
  602. 'ogr' : _getOGRFormats()
  603. }
  604. return formats