utils.py 33 KB

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