utils.py 20 KB

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