utils.py 34 KB

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