utils.py 19 KB

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