utils.py 34 KB

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