utils.py 19 KB

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