utils.py 34 KB

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