utils.py 36 KB

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