utils.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224
  1. """
  2. @package core.utils
  3. @brief Misc utilities for wxGUI
  4. (C) 2007-2015 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 shlex
  16. import re
  17. import inspect
  18. import six
  19. from grass.script import core as grass
  20. from grass.script import task as gtask
  21. from grass.exceptions import OpenError
  22. from core.gcmd import RunCommand
  23. from core.debug import Debug
  24. from core.globalvar import ETCDIR, wxPythonPhoenix, _
  25. def cmp(a, b):
  26. """cmp function"""
  27. return ((a > b) - (a < b))
  28. def normalize_whitespace(text):
  29. """Remove redundant whitespace from a string"""
  30. return (' ').join(text.split())
  31. def split(s):
  32. """Platform spefic shlex.split"""
  33. try:
  34. if sys.platform == "win32":
  35. return shlex.split(s.replace('\\', r'\\'))
  36. else:
  37. return shlex.split(s)
  38. except ValueError as e:
  39. sys.stderr.write(_("Syntax error: %s") % e)
  40. return []
  41. def GetTempfile(pref=None):
  42. """Creates GRASS temporary file using defined prefix.
  43. .. todo::
  44. Fix path on MS Windows/MSYS
  45. :param pref: prefer the given path
  46. :return: Path to file name (string) or None
  47. """
  48. ret = RunCommand('g.tempfile',
  49. read=True,
  50. pid=os.getpid())
  51. tempfile = ret.splitlines()[0].strip()
  52. # FIXME
  53. # ugly hack for MSYS (MS Windows)
  54. if platform.system() == 'Windows':
  55. tempfile = tempfile.replace("/", "\\")
  56. try:
  57. path, file = os.path.split(tempfile)
  58. if pref:
  59. return os.path.join(pref, file)
  60. else:
  61. return tempfile
  62. except:
  63. return None
  64. def GetLayerNameFromCmd(dcmd, fullyQualified=False, param=None,
  65. layerType=None):
  66. """Get map name from GRASS command
  67. Parameter dcmd can be modified when first parameter is not
  68. defined.
  69. :param dcmd: GRASS command (given as list)
  70. :param fullyQualified: change map name to be fully qualified
  71. :param param: params directory
  72. :param str layerType: check also layer type ('raster', 'vector',
  73. 'raster_3d', ...)
  74. :return: tuple (name, found)
  75. """
  76. mapname = ''
  77. found = True
  78. if len(dcmd) < 1:
  79. return mapname, False
  80. if 'd.grid' == dcmd[0]:
  81. mapname = 'grid'
  82. elif 'd.geodesic' in dcmd[0]:
  83. mapname = 'geodesic'
  84. elif 'd.rhumbline' in dcmd[0]:
  85. mapname = 'rhumb'
  86. elif 'd.graph' in dcmd[0]:
  87. mapname = 'graph'
  88. else:
  89. params = list()
  90. for idx in range(len(dcmd)):
  91. try:
  92. p, v = dcmd[idx].split('=', 1)
  93. except ValueError:
  94. continue
  95. if p == param:
  96. params = [(idx, p, v)]
  97. break
  98. # this does not use types, just some (incomplete subset of?) names
  99. if p in ('map', 'input', 'layer',
  100. 'red', 'blue', 'green',
  101. 'hue', 'saturation', 'intensity',
  102. 'shade', 'labels'):
  103. params.append((idx, p, v))
  104. if len(params) < 1:
  105. if len(dcmd) > 1:
  106. i = 1
  107. while i < len(dcmd):
  108. if '=' not in dcmd[i] and not dcmd[i].startswith('-'):
  109. task = gtask.parse_interface(dcmd[0])
  110. # this expects the first parameter to be the right one
  111. p = task.get_options()['params'][0].get('name', '')
  112. params.append((i, p, dcmd[i]))
  113. break
  114. i += 1
  115. else:
  116. return mapname, False
  117. if len(params) < 1:
  118. return mapname, False
  119. # need to add mapset for all maps
  120. mapsets = {}
  121. for i, p, v in params:
  122. if p == 'layer':
  123. continue
  124. mapname = v
  125. mapset = ''
  126. if fullyQualified and '@' not in mapname:
  127. if layerType in ('raster', 'vector',
  128. 'raster_3d', 'rgb', 'his'):
  129. try:
  130. if layerType in ('raster', 'rgb', 'his'):
  131. findType = 'cell'
  132. elif layerType == 'raster_3d':
  133. findType = 'grid3'
  134. else:
  135. findType = layerType
  136. mapset = grass.find_file(
  137. mapname, element=findType)['mapset']
  138. except AttributeError: # not found
  139. return '', False
  140. if not mapset:
  141. found = False
  142. else:
  143. mapset = '' # grass.gisenv()['MAPSET']
  144. mapsets[i] = mapset
  145. # update dcmd
  146. for i, p, v in params:
  147. if p == 'layer':
  148. continue
  149. dcmd[i] = p + '=' + v
  150. if i in mapsets and mapsets[i]:
  151. dcmd[i] += '@' + mapsets[i]
  152. maps = list()
  153. ogr = False
  154. for i, p, v in params:
  155. if v.lower().rfind('@ogr') > -1:
  156. ogr = True
  157. if p == 'layer' and not ogr:
  158. continue
  159. maps.append(dcmd[i].split('=', 1)[1])
  160. mapname = '\n'.join(maps)
  161. return mapname, found
  162. def GetValidLayerName(name):
  163. """Make layer name SQL compliant, based on G_str_to_sql()
  164. .. todo::
  165. Better use directly Ctypes to reuse venerable libgis C fns...
  166. """
  167. retName = name.strip()
  168. # check if name is fully qualified
  169. if '@' in retName:
  170. retName, mapset = retName.split('@')
  171. else:
  172. mapset = None
  173. cIdx = 0
  174. retNameList = list(retName)
  175. for c in retNameList:
  176. if not (c >= 'A' and c <= 'Z') and \
  177. not (c >= 'a' and c <= 'z') and \
  178. not (c >= '0' and c <= '9'):
  179. retNameList[cIdx] = '_'
  180. cIdx += 1
  181. retName = ''.join(retNameList)
  182. if not (retName[0] >= 'A' and retName[0] <= 'Z') and \
  183. not (retName[0] >= 'a' and retName[0] <= 'z'):
  184. retName = 'x' + retName[1:]
  185. if mapset:
  186. retName = retName + '@' + mapset
  187. return retName
  188. def ListOfCatsToRange(cats):
  189. """Convert list of category number to range(s)
  190. Used for example for d.vect cats=[range]
  191. :param cats: category list
  192. :return: category range string
  193. :return: '' on error
  194. """
  195. catstr = ''
  196. try:
  197. cats = list(map(int, cats))
  198. except:
  199. return catstr
  200. i = 0
  201. while i < len(cats):
  202. next = 0
  203. j = i + 1
  204. while j < len(cats):
  205. if cats[i + next] == cats[j] - 1:
  206. next += 1
  207. else:
  208. break
  209. j += 1
  210. if next > 1:
  211. catstr += '%d-%d,' % (cats[i], cats[i + next])
  212. i += next + 1
  213. else:
  214. catstr += '%d,' % (cats[i])
  215. i += 1
  216. return catstr.strip(',')
  217. def ListOfMapsets(get='ordered'):
  218. """Get list of available/accessible mapsets
  219. :param str get: method ('all', 'accessible', 'ordered')
  220. :return: list of mapsets
  221. :return: None on error
  222. """
  223. mapsets = []
  224. if get == 'all' or get == 'ordered':
  225. ret = RunCommand('g.mapsets',
  226. read=True,
  227. quiet=True,
  228. flags='l',
  229. sep='newline')
  230. if ret:
  231. mapsets = ret.splitlines()
  232. ListSortLower(mapsets)
  233. else:
  234. return None
  235. if get == 'accessible' or get == 'ordered':
  236. ret = RunCommand('g.mapsets',
  237. read=True,
  238. quiet=True,
  239. flags='p',
  240. sep='newline')
  241. if ret:
  242. if get == 'accessible':
  243. mapsets = ret.splitlines()
  244. else:
  245. mapsets_accessible = ret.splitlines()
  246. for mapset in mapsets_accessible:
  247. mapsets.remove(mapset)
  248. mapsets = mapsets_accessible + mapsets
  249. else:
  250. return None
  251. return mapsets
  252. def ListSortLower(list):
  253. """Sort list items (not case-sensitive)"""
  254. list.sort(key=lambda x: x.lower())
  255. def GetVectorNumberOfLayers(vector):
  256. """Get list of all vector layers"""
  257. layers = list()
  258. if not vector:
  259. return layers
  260. fullname = grass.find_file(name=vector, element='vector')['fullname']
  261. if not fullname:
  262. Debug.msg(
  263. 5,
  264. "utils.GetVectorNumberOfLayers(): vector map '%s' not found" %
  265. vector)
  266. return layers
  267. ret, out, msg = RunCommand('v.category',
  268. getErrorMsg=True,
  269. read=True,
  270. input=fullname,
  271. option='layers')
  272. if ret != 0:
  273. sys.stderr.write(
  274. _("Vector map <%(map)s>: %(msg)s\n") %
  275. {'map': fullname, 'msg': msg})
  276. return layers
  277. else:
  278. Debug.msg(1, "GetVectorNumberOfLayers(): ret %s" % ret)
  279. for layer in out.splitlines():
  280. layers.append(layer)
  281. Debug.msg(3, "utils.GetVectorNumberOfLayers(): vector=%s -> %s" %
  282. (fullname, ','.join(layers)))
  283. return layers
  284. def Deg2DMS(lon, lat, string=True, hemisphere=True, precision=3):
  285. """Convert deg value to dms string
  286. :param lon: longitude (x)
  287. :param lat: latitude (y)
  288. :param string: True to return string otherwise tuple
  289. :param hemisphere: print hemisphere
  290. :param precision: seconds precision
  291. :return: DMS string or tuple of values
  292. :return: empty string on error
  293. """
  294. try:
  295. flat = float(lat)
  296. flon = float(lon)
  297. except ValueError:
  298. if string:
  299. return ''
  300. else:
  301. return None
  302. # fix longitude
  303. while flon > 180.0:
  304. flon -= 360.0
  305. while flon < -180.0:
  306. flon += 360.0
  307. # hemisphere
  308. if hemisphere:
  309. if flat < 0.0:
  310. flat = abs(flat)
  311. hlat = 'S'
  312. else:
  313. hlat = 'N'
  314. if flon < 0.0:
  315. hlon = 'W'
  316. flon = abs(flon)
  317. else:
  318. hlon = 'E'
  319. else:
  320. flat = abs(flat)
  321. flon = abs(flon)
  322. hlon = ''
  323. hlat = ''
  324. slat = __ll_parts(flat, precision=precision)
  325. slon = __ll_parts(flon, precision=precision)
  326. if string:
  327. return slon + hlon + '; ' + slat + hlat
  328. return (slon + hlon, slat + hlat)
  329. def DMS2Deg(lon, lat):
  330. """Convert dms value to deg
  331. :param lon: longitude (x)
  332. :param lat: latitude (y)
  333. :return: tuple of converted values
  334. :return: ValueError on error
  335. """
  336. x = __ll_parts(lon, reverse=True)
  337. y = __ll_parts(lat, reverse=True)
  338. return (x, y)
  339. def __ll_parts(value, reverse=False, precision=3):
  340. """Converts deg to d:m:s string
  341. :param value: value to be converted
  342. :param reverse: True to convert from d:m:s to deg
  343. :param precision: seconds precision (ignored if reverse is True)
  344. :return: converted value (string/float)
  345. :return: ValueError on error (reverse == True)
  346. """
  347. if not reverse:
  348. if value == 0.0:
  349. return '%s%.*f' % ('00:00:0', precision, 0.0)
  350. d = int(int(value))
  351. m = int((value - d) * 60)
  352. s = ((value - d) * 60 - m) * 60
  353. if m < 0:
  354. m = '00'
  355. elif m < 10:
  356. m = '0' + str(m)
  357. else:
  358. m = str(m)
  359. if s < 0:
  360. s = '00.0000'
  361. elif s < 10.0:
  362. s = '0%.*f' % (precision, s)
  363. else:
  364. s = '%.*f' % (precision, s)
  365. return str(d) + ':' + m + ':' + s
  366. else: # -> reverse
  367. try:
  368. d, m, s = value.split(':')
  369. hs = s[-1]
  370. s = s[:-1]
  371. except ValueError:
  372. try:
  373. d, m = value.split(':')
  374. hs = m[-1]
  375. m = m[:-1]
  376. s = '0.0'
  377. except ValueError:
  378. try:
  379. d = value
  380. hs = d[-1]
  381. d = d[:-1]
  382. m = '0'
  383. s = '0.0'
  384. except ValueError:
  385. raise ValueError
  386. if hs not in ('N', 'S', 'E', 'W'):
  387. raise ValueError
  388. coef = 1.0
  389. if hs in ('S', 'W'):
  390. coef = -1.0
  391. fm = int(m) / 60.0
  392. fs = float(s) / (60 * 60)
  393. return coef * (float(d) + fm + fs)
  394. def GetCmdString(cmd):
  395. """Get GRASS command as string.
  396. :param cmd: GRASS command given as tuple
  397. :return: command string
  398. """
  399. return ' '.join(gtask.cmdtuple_to_list(cmd))
  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. Raise OpenError on failure.
  411. :return: dictionary of EPSG code
  412. """
  413. epsgCodeDict = dict()
  414. try:
  415. try:
  416. f = open(path, "r")
  417. except IOError:
  418. raise OpenError(_("failed to open '{0}'").format(path))
  419. code = None
  420. for line in f.readlines():
  421. line = line.strip()
  422. if len(line) < 1 or line.startswith('<metadata>'):
  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 as e:
  431. raise OpenError('{0}'.format(e))
  432. if code is not None:
  433. epsgCodeDict[code] = (descr, params)
  434. code = None
  435. f.close()
  436. except Exception as e:
  437. raise OpenError('{0}'.format(e))
  438. return epsgCodeDict
  439. def ReprojectCoordinates(coord, projOut, projIn=None, flags=''):
  440. """Reproject coordinates
  441. :param coord: coordinates given as tuple
  442. :param projOut: output projection
  443. :param projIn: input projection (use location projection settings)
  444. :return: reprojected coordinates (returned as tuple)
  445. """
  446. coors = RunCommand('m.proj',
  447. flags=flags,
  448. input='-',
  449. proj_in=projIn,
  450. proj_out=projOut,
  451. sep=';',
  452. stdin='%f;%f' % (coord[0], coord[1]),
  453. read=True)
  454. if coors:
  455. coors = coors.split(';')
  456. e = coors[0]
  457. n = coors[1]
  458. try:
  459. proj = projOut.split(' ')[0].split('=')[1]
  460. except IndexError:
  461. proj = ''
  462. if proj in ('ll', 'latlong', 'longlat') and 'd' not in flags:
  463. return (proj, (e, n))
  464. else:
  465. try:
  466. return (proj, (float(e), float(n)))
  467. except ValueError:
  468. return (None, None)
  469. return (None, None)
  470. def GetListOfLocations(dbase):
  471. """Get list of GRASS locations in given dbase
  472. :param dbase: GRASS database path
  473. :return: list of locations (sorted)
  474. """
  475. listOfLocations = list()
  476. try:
  477. for location in glob.glob(os.path.join(dbase, "*")):
  478. try:
  479. if os.path.join(
  480. location, "PERMANENT") in glob.glob(
  481. os.path.join(location, "*")):
  482. listOfLocations.append(os.path.basename(location))
  483. except:
  484. pass
  485. except (UnicodeEncodeError, UnicodeDecodeError) as 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 = RunCommand('g.mapset',
  499. read=True,
  500. flags='l',
  501. location=location,
  502. dbase=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 os.path.isfile(
  510. 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 = RunCommand('r.colors',
  517. read=True,
  518. flags='l')
  519. if not ret:
  520. return list()
  521. return ret.splitlines()
  522. def _getGDALFormats():
  523. """Get dictionary of avaialble GDAL drivers"""
  524. try:
  525. ret = grass.read_command('r.in.gdal',
  526. quiet=True,
  527. flags='f')
  528. except:
  529. ret = None
  530. return _parseFormats(ret), _parseFormats(ret, writableOnly=True)
  531. def _getOGRFormats():
  532. """Get dictionary of avaialble OGR drivers"""
  533. try:
  534. ret = grass.read_command('v.in.ogr',
  535. quiet=True,
  536. flags='f')
  537. except:
  538. ret = None
  539. return _parseFormats(ret), _parseFormats(ret, writableOnly=True)
  540. def _parseFormats(output, writableOnly=False):
  541. """Parse r.in.gdal/v.in.ogr -f output"""
  542. formats = {'file': list(),
  543. 'database': list(),
  544. 'protocol': list()
  545. }
  546. if not output:
  547. return formats
  548. patt = None
  549. if writableOnly:
  550. patt = re.compile('\(rw\+?\)$', re.IGNORECASE)
  551. for line in output.splitlines():
  552. key, name = map(lambda x: x.strip(), line.strip().rsplit(':', -1))
  553. if writableOnly and not patt.search(key):
  554. continue
  555. if name in ('Memory', 'Virtual Raster', 'In Memory Raster'):
  556. continue
  557. if name in ('PostgreSQL', 'SQLite',
  558. 'ODBC', 'ESRI Personal GeoDatabase',
  559. 'Rasterlite',
  560. 'PostGIS WKT Raster driver',
  561. 'PostGIS Raster driver',
  562. 'CouchDB',
  563. 'MSSQLSpatial',
  564. 'FileGDB'):
  565. formats['database'].append(name)
  566. elif name in ('GeoJSON',
  567. 'OGC Web Coverage Service',
  568. 'OGC Web Map Service',
  569. 'WFS',
  570. 'GeoRSS',
  571. 'HTTP Fetching Wrapper'):
  572. formats['protocol'].append(name)
  573. else:
  574. formats['file'].append(name)
  575. for items in six.itervalues(formats):
  576. items.sort()
  577. return formats
  578. formats = None
  579. def GetFormats(writableOnly=False):
  580. """Get GDAL/OGR formats"""
  581. global formats
  582. if not formats:
  583. gdalAll, gdalWritable = _getGDALFormats()
  584. ogrAll, ogrWritable = _getOGRFormats()
  585. formats = {
  586. 'all': {
  587. 'gdal': gdalAll,
  588. 'ogr': ogrAll,
  589. },
  590. 'writable': {
  591. 'gdal': gdalWritable,
  592. 'ogr': ogrWritable,
  593. },
  594. }
  595. if writableOnly:
  596. return formats['writable']
  597. return formats['all']
  598. rasterFormatExtension = {
  599. 'GeoTIFF': 'tif',
  600. 'Erdas Imagine Images (.img)': 'img',
  601. 'Ground-based SAR Applications Testbed File Format (.gff)': 'gff',
  602. 'Arc/Info Binary Grid': 'adf',
  603. 'Portable Network Graphics': 'png',
  604. 'JPEG JFIF': 'jpg',
  605. 'Japanese DEM (.mem)': 'mem',
  606. 'Graphics Interchange Format (.gif)': 'gif',
  607. 'X11 PixMap Format': 'xpm',
  608. 'MS Windows Device Independent Bitmap': 'bmp',
  609. 'SPOT DIMAP': 'dim',
  610. 'RadarSat 2 XML Product': 'xml',
  611. 'EarthWatch .TIL': 'til',
  612. 'ERMapper .ers Labelled': 'ers',
  613. 'ERMapper Compressed Wavelets': 'ecw',
  614. 'GRIdded Binary (.grb)': 'grb',
  615. 'EUMETSAT Archive native (.nat)': 'nat',
  616. 'Idrisi Raster A.1': 'rst',
  617. 'Golden Software ASCII Grid (.grd)': 'grd',
  618. 'Golden Software Binary Grid (.grd)': 'grd',
  619. 'Golden Software 7 Binary Grid (.grd)': 'grd',
  620. 'R Object Data Store': 'r',
  621. 'USGS DOQ (Old Style)': 'doq',
  622. 'USGS DOQ (New Style)': 'doq',
  623. 'ENVI .hdr Labelled': 'hdr',
  624. 'ESRI .hdr Labelled': 'hdr',
  625. 'Generic Binary (.hdr Labelled)': 'hdr',
  626. 'PCI .aux Labelled': 'aux',
  627. 'EOSAT FAST Format': 'fst',
  628. 'VTP .bt (Binary Terrain) 1.3 Format': 'bt',
  629. 'FARSITE v.4 Landscape File (.lcp)': 'lcp',
  630. 'Swedish Grid RIK (.rik)': 'rik',
  631. 'USGS Optional ASCII DEM (and CDED)': 'dem',
  632. 'Northwood Numeric Grid Format .grd/.tab': '',
  633. 'Northwood Classified Grid Format .grc/.tab': '',
  634. 'ARC Digitized Raster Graphics': 'arc',
  635. 'Magellan topo (.blx)': 'blx',
  636. 'SAGA GIS Binary Grid (.sdat)': 'sdat'
  637. }
  638. vectorFormatExtension = {
  639. 'ESRI Shapefile': 'shp',
  640. 'UK .NTF': 'ntf',
  641. 'SDTS': 'ddf',
  642. 'DGN': 'dgn',
  643. 'VRT': 'vrt',
  644. 'REC': 'rec',
  645. 'BNA': 'bna',
  646. 'CSV': 'csv',
  647. 'GML': 'gml',
  648. 'GPX': 'gpx',
  649. 'KML': 'kml',
  650. 'GMT': 'gmt',
  651. 'PGeo': 'mdb',
  652. 'XPlane': 'dat',
  653. 'AVCBin': 'adf',
  654. 'AVCE00': 'e00',
  655. 'DXF': 'dxf',
  656. 'Geoconcept': 'gxt',
  657. 'GeoRSS': 'xml',
  658. 'GPSTrackMaker': 'gtm',
  659. 'VFK': 'vfk',
  660. 'SVG': 'svg',
  661. }
  662. def GetSettingsPath():
  663. """Get full path to the settings directory
  664. """
  665. try:
  666. verFd = open(os.path.join(ETCDIR, "VERSIONNUMBER"))
  667. version = int(verFd.readlines()[0].split(' ')[0].split('.')[0])
  668. except (IOError, ValueError, TypeError, IndexError) as e:
  669. sys.exit(
  670. _("ERROR: Unable to determine GRASS version. Details: %s") %
  671. e)
  672. verFd.close()
  673. # keep location of settings files rc and wx in sync with lib/init/grass.py
  674. if sys.platform == 'win32':
  675. return os.path.join(os.getenv('APPDATA'), 'GRASS%d' % version)
  676. return os.path.join(os.getenv('HOME'), '.grass%d' % version)
  677. def StoreEnvVariable(key, value=None, envFile=None):
  678. """Store environmental variable
  679. If value is not given (is None) then environmental variable is
  680. unset.
  681. :param key: env key
  682. :param value: env value
  683. :param envFile: path to the environmental file (None for default location)
  684. """
  685. windows = sys.platform == 'win32'
  686. if not envFile:
  687. gVersion = grass.version()['version'].split('.', 1)[0]
  688. if not windows:
  689. envFile = os.path.join(
  690. os.getenv('HOME'), '.grass%s' %
  691. gVersion, 'bashrc')
  692. else:
  693. envFile = os.path.join(
  694. os.getenv('APPDATA'), 'GRASS%s' %
  695. gVersion, 'env.bat')
  696. # read env file
  697. environ = dict()
  698. lineSkipped = list()
  699. if os.path.exists(envFile):
  700. try:
  701. fd = open(envFile)
  702. except IOError as e:
  703. sys.stderr.write(_("Unable to open file '%s'\n") % envFile)
  704. return
  705. for line in fd.readlines():
  706. line = line.rstrip(os.linesep)
  707. try:
  708. k, v = map(
  709. lambda x: x.strip(), line.split(
  710. ' ', 1)[1].split(
  711. '=', 1))
  712. except Exception as e:
  713. sys.stderr.write(_("%s: line skipped - unable to parse '%s'\n"
  714. "Reason: %s\n") % (envFile, line, e))
  715. lineSkipped.append(line)
  716. continue
  717. if k in environ:
  718. sys.stderr.write(_("Duplicated key: %s\n") % k)
  719. environ[k] = v
  720. fd.close()
  721. # update environmental variables
  722. if value is None:
  723. if key in environ:
  724. del environ[key]
  725. else:
  726. environ[key] = value
  727. # write update env file
  728. try:
  729. fd = open(envFile, 'w')
  730. except IOError as e:
  731. sys.stderr.write(_("Unable to create file '%s'\n") % envFile)
  732. return
  733. if windows:
  734. expCmd = 'set'
  735. else:
  736. expCmd = 'export'
  737. for key, value in six.iteritems(environ):
  738. fd.write('%s %s=%s\n' % (expCmd, key, value))
  739. # write also skipped lines
  740. for line in lineSkipped:
  741. fd.write(line + os.linesep)
  742. fd.close()
  743. def SetAddOnPath(addonPath=None, key='PATH'):
  744. """Set default AddOn path
  745. :param addonPath: path to addons (None for default)
  746. :param key: env key - 'PATH' or 'BASE'
  747. """
  748. gVersion = grass.version()['version'].split('.', 1)[0]
  749. # update env file
  750. if not addonPath:
  751. if sys.platform != 'win32':
  752. addonPath = os.path.join(os.path.join(os.getenv('HOME'),
  753. '.grass%s' % gVersion,
  754. 'addons'))
  755. else:
  756. addonPath = os.path.join(os.path.join(os.getenv('APPDATA'),
  757. 'GRASS%s' % gVersion,
  758. 'addons'))
  759. StoreEnvVariable(key='GRASS_ADDON_' + key, value=addonPath)
  760. os.environ['GRASS_ADDON_' + key] = addonPath
  761. # update path
  762. if addonPath not in os.environ['PATH']:
  763. os.environ['PATH'] = addonPath + os.pathsep + os.environ['PATH']
  764. # predefined colors and their names
  765. # must be in sync with lib/gis/color_str.c
  766. str2rgb = {'aqua': (100, 128, 255),
  767. 'black': (0, 0, 0),
  768. 'blue': (0, 0, 255),
  769. 'brown': (180, 77, 25),
  770. 'cyan': (0, 255, 255),
  771. 'gray': (128, 128, 128),
  772. 'grey': (128, 128, 128),
  773. 'green': (0, 255, 0),
  774. 'indigo': (0, 128, 255),
  775. 'magenta': (255, 0, 255),
  776. 'orange': (255, 128, 0),
  777. 'red': (255, 0, 0),
  778. 'violet': (128, 0, 255),
  779. 'purple': (128, 0, 255),
  780. 'white': (255, 255, 255),
  781. 'yellow': (255, 255, 0)}
  782. rgb2str = {}
  783. for (s, r) in str2rgb.items():
  784. rgb2str[r] = s
  785. # ensure that gray value has 'gray' string and not 'grey'
  786. rgb2str[str2rgb['gray']] = 'gray'
  787. # purple is defined as nickname for violet in lib/gis
  788. # (although Wikipedia says that purple is (128, 0, 128))
  789. # we will prefer the defined color, not nickname
  790. rgb2str[str2rgb['violet']] = 'violet'
  791. def color_resolve(color):
  792. if len(color) > 0 and color[0] in "0123456789":
  793. rgb = tuple(map(int, color.split(':')))
  794. label = color
  795. else:
  796. # Convert color names to RGB
  797. try:
  798. rgb = str2rgb[color]
  799. label = color
  800. except KeyError:
  801. rgb = (200, 200, 200)
  802. label = _('Select Color')
  803. return (rgb, label)
  804. command2ltype = {'d.rast': 'raster',
  805. 'd.rast3d': 'raster_3d',
  806. 'd.rgb': 'rgb',
  807. 'd.his': 'his',
  808. 'd.shade': 'shaded',
  809. 'd.legend': 'rastleg',
  810. 'd.rast.arrow': 'rastarrow',
  811. 'd.rast.num': 'rastnum',
  812. 'd.rast.leg': 'maplegend',
  813. 'd.vect': 'vector',
  814. 'd.vect.thematic': 'thememap',
  815. 'd.vect.chart': 'themechart',
  816. 'd.grid': 'grid',
  817. 'd.geodesic': 'geodesic',
  818. 'd.rhumbline': 'rhumb',
  819. 'd.labels': 'labels',
  820. 'd.barscale': 'barscale',
  821. 'd.redraw': 'redraw',
  822. 'd.wms': 'wms',
  823. 'd.histogram': 'histogram',
  824. 'd.colortable': 'colortable',
  825. 'd.graph': 'graph',
  826. 'd.out.file': 'export',
  827. 'd.to.rast': 'torast',
  828. 'd.text': 'text',
  829. 'd.northarrow': 'northarrow',
  830. 'd.polar': 'polar',
  831. 'd.legend.vect': 'vectleg'
  832. }
  833. ltype2command = {}
  834. for (cmd, ltype) in command2ltype.items():
  835. ltype2command[ltype] = cmd
  836. def GetGEventAttribsForHandler(method, event):
  837. """Get attributes from event, which can be used by handler method.
  838. Be aware of event class attributes.
  839. :param method: handler method (including self arg)
  840. :param event: event
  841. :return: (valid kwargs for method,
  842. list of method's args without default value
  843. which were not found among event attributes)
  844. """
  845. args_spec = inspect.getargspec(method)
  846. args = args_spec[0]
  847. defaults = []
  848. if args_spec[3]:
  849. defaults = args_spec[3]
  850. # number of arguments without def value
  851. req_args = len(args) - 1 - len(defaults)
  852. kwargs = {}
  853. missing_args = []
  854. for i, a in enumerate(args):
  855. if hasattr(event, a):
  856. kwargs[a] = getattr(event, a)
  857. elif i < req_args:
  858. missing_args.append(a)
  859. return kwargs, missing_args
  860. def PilImageToWxImage(pilImage, copyAlpha=True):
  861. """Convert PIL image to wx.Image
  862. Based on http://wiki.wxpython.org/WorkingWithImages
  863. """
  864. from gui_core.wrap import EmptyImage
  865. hasAlpha = pilImage.mode[-1] == 'A'
  866. if copyAlpha and hasAlpha: # Make sure there is an alpha layer copy.
  867. wxImage = EmptyImage(*pilImage.size)
  868. pilImageCopyRGBA = pilImage.copy()
  869. pilImageCopyRGB = pilImageCopyRGBA.convert('RGB') # RGBA --> RGB
  870. fn = getattr(
  871. pilImageCopyRGB,
  872. "tobytes",
  873. getattr(
  874. pilImageCopyRGB,
  875. "tostring"))
  876. pilImageRgbData = fn()
  877. wxImage.SetData(pilImageRgbData)
  878. fn = getattr(
  879. pilImageCopyRGBA,
  880. "tobytes",
  881. getattr(
  882. pilImageCopyRGBA,
  883. "tostring"))
  884. # Create layer and insert alpha values.
  885. if wxPythonPhoenix:
  886. wxImage.SetAlpha(fn()[3::4])
  887. else:
  888. wxImage.SetAlphaData(fn()[3::4])
  889. else: # The resulting image will not have alpha.
  890. wxImage = EmptyImage(*pilImage.size)
  891. pilImageCopy = pilImage.copy()
  892. # Discard any alpha from the PIL image.
  893. pilImageCopyRGB = pilImageCopy.convert('RGB')
  894. fn = getattr(
  895. pilImageCopyRGB,
  896. "tobytes",
  897. getattr(
  898. pilImageCopyRGB,
  899. "tostring"))
  900. pilImageRgbData = fn()
  901. wxImage.SetData(pilImageRgbData)
  902. return wxImage
  903. def autoCropImageFromFile(filename):
  904. """Loads image from file and crops it automatically.
  905. If PIL is not installed, it does not crop it.
  906. :param filename: path to file
  907. :return: wx.Image instance
  908. """
  909. try:
  910. from PIL import Image
  911. pilImage = Image.open(filename)
  912. imageBox = pilImage.getbbox()
  913. cropped = pilImage.crop(imageBox)
  914. return PilImageToWxImage(cropped, copyAlpha=True)
  915. except ImportError:
  916. import wx
  917. return wx.Image(filename)
  918. def isInRegion(regionA, regionB):
  919. """Tests if 'regionA' is inside of 'regionB'.
  920. For example, region A is a display region and region B is some reference
  921. region, e.g., a computational region.
  922. >>> displayRegion = {'n': 223900, 's': 217190, 'w': 630780, 'e': 640690}
  923. >>> compRegion = {'n': 228500, 's': 215000, 'w': 630000, 'e': 645000}
  924. >>> isInRegion(displayRegion, compRegion)
  925. True
  926. >>> displayRegion = {'n':226020, 's': 212610, 'w': 626510, 'e': 646330}
  927. >>> isInRegion(displayRegion, compRegion)
  928. False
  929. :param regionA: input region A as dictionary
  930. :param regionB: input region B as dictionary
  931. :return: True if region A is inside of region B
  932. :return: False othewise
  933. """
  934. if regionA['s'] >= regionB['s'] and \
  935. regionA['n'] <= regionB['n'] and \
  936. regionA['w'] >= regionB['w'] and \
  937. regionA['e'] <= regionB['e']:
  938. return True
  939. return False
  940. def do_doctest_gettext_workaround():
  941. """Setups environment for doing a doctest with gettext usage.
  942. When using gettext with dynamically defined underscore function
  943. (`_("For translation")`), doctest does not work properly. One option is to
  944. use `import as` instead of dynamically defined underscore function but this
  945. would require change all modules which are used by tested module. This
  946. should be considered for the future. The second option is to define dummy
  947. underscore function and one other function which creates the right
  948. environment to satisfy all. This is done by this function.
  949. """
  950. def new_displayhook(string):
  951. """A replacement for default `sys.displayhook`"""
  952. if string is not None:
  953. sys.stdout.write("%r\n" % (string,))
  954. def new_translator(string):
  955. """A fake gettext underscore function."""
  956. return string
  957. sys.displayhook = new_displayhook
  958. import __builtin__
  959. __builtin__._ = new_translator
  960. def doc_test():
  961. """Tests the module using doctest
  962. :return: a number of failed tests
  963. """
  964. import doctest
  965. do_doctest_gettext_workaround()
  966. return doctest.testmod().failed
  967. def registerPid(pid):
  968. """Register process id as GUI_PID GRASS variable
  969. :param: pid process id
  970. """
  971. env = grass.gisenv()
  972. guiPid = []
  973. if 'GUI_PID' in env:
  974. guiPid = env['GUI_PID'].split(',')
  975. guiPid.append(str(pid))
  976. grass.run_command('g.gisenv', set='GUI_PID={0}'.format(','.join(guiPid)))
  977. def unregisterPid(pid):
  978. """Unregister process id from GUI_PID GRASS variable
  979. :param: pid process id
  980. """
  981. env = grass.gisenv()
  982. if 'GUI_PID' not in env:
  983. return
  984. guiPid = env['GUI_PID'].split(',')
  985. pid = str(os.getpid())
  986. if pid in guiPid:
  987. guiPid.remove(pid)
  988. grass.run_command(
  989. 'g.gisenv',
  990. set='GUI_PID={0}'.format(
  991. ','.join(guiPid)))
  992. if __name__ == '__main__':
  993. sys.exit(doc_test())