unicode_literals) import imp import sys import os from pprint import pprint from fnmatch import fnmatch import numpy as np from grass.pygrass.utils import set_path from grass.pygrass.messages import get_msgr from grass.pygrass.vector import Vector from grass.pygrass.modules import Module from grass.script.core import parser, overwrite set_path('v.class.ml') from training_extraction import extract_training from sqlite2npy import save2npy from npy2table import export_results DECMP = {} def load_decompositions(): """Import decompositions and update dictionary which stores them""" from sklearn.decomposition import (PCA, KernelPCA, ProbabilisticPCA, RandomizedPCA, FastICA, TruncatedSVD) from sklearn.lda import LDA DECMP.update({
def get_session(options): """Based on a dictionary and available backends create a remote session""" requested_backend = options['backend'] if requested_backend: backends = [requested_backend] else: # on win there is minimal chance of ssh but try anyway # pexpect only upon request, it is specific and insufficiently tested backends = ['paramiko', 'simple'] session = None ensure_nones(options, ['port', 'password']) to_ints(options, ['port']) # TODO: provide a flag (or default) for reading the file or params # from some standardized location or variable (so we have shorter # command lines) config_name = options['config'] if config_name: gscript.debug("Config file supplied for login") check_config_file(config_name) with open(config_name, 'r') as config_file: config = config_file.read() # split using whitespace # (supposing no spaces in user name and password) values = config.split() if len(values) == 2: gscript.verbose(_("Using values for login from config file")) options['user'] = values[0] options['password'] = values[1] else: gscript.fatal(_("The config file <%s> is not well-formed." " It should contain user name and password" " separated by whitespace" " (newlines, spaces or tabs)" % config_name)) # get access to wrappers from grass.pygrass.utils import set_path set_path('g.remote') for backend in backends: if backend == 'paramiko': try: from friendlyssh import Connection session = Connection( username=options['user'], host=options['server'], password=options['password'], port=options['port']) gscript.verbose(_("Using Paramiko backend")) break except ImportError as error: gscript.verbose(_("Tried Paramiko backend but" " it is not available (%s)" % error)) continue elif backend == 'simple': try: from simplessh import SshConnection as Connection # TODO: support password and port (or warn they are missing) session = Connection( user=options['user'], host=options['server']) gscript.verbose(_("Using simple (ssh and scp) backend")) break except ImportError as error: gscript.verbose(_("Tried simple (ssh and scp) backend but" " it is not available (%s)" % error)) continue elif backend == 'pexpect': try: from pexpectssh import SshSession as Connection # TODO: support port (or warn it's missing) session = Connection( user=options['user'], host=options['server'], logfile='gcloudsshiface.log', verbose=1, password=options['password']) gscript.verbose(_("Using Pexpect (with ssh and scp) backend")) break except ImportError as error: gscript.verbose(_("Tried Pexpect (ssh, scp and pexpect)" " backend but it is not available" " (%s)" % error)) continue elif backend == 'local': try: from localsession import LocalConnection as Connection session = Connection() gscript.verbose(_("Using local host backend")) break except ImportError as error: gscript.verbose(_("Tried local host" " backend but it is not available" " (%s)" % error)) continue if session is None: hint = _("Please install Paramiko Python package" " or ssh and scp tools.") verbose_message = _("Use --verbose flag to get more information.") if sys.platform.startswith('win'): platform_hint = _("Note that the ssh is generally not available" " for MS Windows. Paramiko should be accessible" " through python pip but you have to make it" " available to GRASS GIS (or OSGeo4W) Python.") else: platform_hint = _("All should be in the software repositories." " If Paramiko is not in the repository use pip.") gscript.fatal(_( "No backend available. {general_hint} {platform_hint}" " {verbose}").format( general_hint=hint, platform_hint=platform_hint, verbose=verbose_message)) return session
from owslib.iso import * except: sys.exit( 'owslib library is missing. Check requirements on the manual page < https://grasswiki.osgeo.org/wiki/ISO/INSPIRE_Metadata_Support >' ) try: from jinja2 import Environment, FileSystemLoader except: sys.exit( 'jinja2 library is missing. Check requirements on the manual page < https://grasswiki.osgeo.org/wiki/ISO/INSPIRE_Metadata_Support >' ) from grass.script import core as grass from grass.pygrass.utils import set_path set_path(modulename='wx.metadata', dirname='mdlib') from lxml import etree import StringIO import uuid import mdutil # metadata lib from grass.pygrass.modules import Module from grass.script import parse_key_val from subprocess import PIPE from datetime import date, datetime class GrassMD(): ''' @var self.map: name of choosen map by user
#% keyword: precipitation #% keyword: microwave #% keyword: link #%end VERSION = 1.3 import sys import os import tempfile import time import grass.script as grass from grass.pygrass.utils import set_path set_path(modulename='g.gui.mwprecip', dirname='etc') from grass.script.setup import set_gui_path set_gui_path() from mw_util import * from mw3 import * from core.gcmd import GMessage, GError from gui_core import gselect from core.gthread import gThread from gui_core.widgets import ColorTablesComboBox, PictureComboBox from core import globalvar from core.utils import GetColorTables import wx.lib.scrolledpanel as scrolled import logging
#%end import sys from sys import exit, maxsize from math import sqrt from math import exp from random import randint try: from grass.script import core as grass except ImportError: raise error.EnvError("r.agent.aco:", "Please run inside GRASS.") from grass.pygrass.utils import set_path set_path('r.agent', 'libagent', '..') from libagent import error, grassland, anthill def setmaps(site, cost, wastecosts, inphero, outphero, wastephero): """ Set the user maps in place """ if site: if -1 == site.find('@'): site = site + '@' + grass.gisenv()['MAPSET'] # set sitemap and site list world.sites = world.playground.parsevectorlayer( anthill.Anthill.SITE, site, -1, True) if not world.sites: raise error.DataError("r.agent.aco:",
#%end import sys from sys import exit, maxsize from math import sqrt from math import exp from random import randint try: from grass.script import core as grass except ImportError: raise error.EnvError("r.agent.rand:", "Please run inside GRASS.") from grass.pygrass.utils import set_path set_path("r.agent", "libagent", "..") from libagent import error, grassland, world def setmaps(cost, output): """ Set the user maps in place """ if cost: if -1 == cost.find("@"): cost = cost + "@" + grass.gisenv()["MAPSET"] # set cost/penalty layer world.playground.setgrasslayer("COST", cost, True) else: raise error.DataError("r.agent.rand:", "The cost map is mandatory.") if output:
from grass.pygrass.utils import set_path set_path('r.learn.ml') from raster import RasterStack stack = RasterStack(rasters=[ "lsat5_1987_10", "lsat5_1987_20", "lsat5_1987_30", "lsat5_1987_40", "lsat5_1987_50", "lsat5_1987_70" ]) stack = RasterStack(rasters=maplist) stack.lsat5_1987_10 maplist2 = deepcopy(maplist) maplist2 = [i.split('@')[0] for i in maplist2] stack = RasterStack(rasters=maplist2) stack.lsat5_1987_10 X, y, crd = stack.extract_points(vect_name='landclass96_roi', fields=['value', 'cat']) df = stack.extract_points(vect_name='landclass96_roi', field='value', as_df=True) df = stack.extract_pixels(response='landclass96_roi', as_df=True) X, y, crd = stack.extract_pixels(response='landclass96_roi') stack.head() stack.tail() data = stack.read()
import numpy as np from grass.pygrass.messages import get_msgr from grass.pygrass.utils import set_path from grass.pygrass.vector import VectorTopo from grass.script import core as gcore try: from scipy.optimize import fsolve except ImportError: gcore.warning('You should install scipy to use this module: ' 'pip install scipy') try: # set python path to the shared r.green libraries set_path('r.green', 'libhydro', '..') set_path('r.green', 'libgreen', os.path.join('..', '..')) from libgreen.utils import cleanup from libhydro.plant import power2energy from libhydro.optimal import conv_segpoints except ImportError: try: set_path('r.green', 'libhydro', os.path.join('..', 'etc', 'r.green')) set_path('r.green', 'libgreen', os.path.join('..', 'etc', 'r.green')) from libgreen.utils import cleanup from libhydro.plant import power2energy from libhydro.optimal import conv_segpoints except ImportError: gcore.warning('libgreen and libhydro not in the python path!') DEBUG = False
from __future__ import print_function import multiprocessing as mltp import time import sys from grass.script.core import parser from grass.pygrass.modules import Module from grass.pygrass.modules.grid import GridModule from grass.pygrass.modules.grid.grid import copy_rasters from grass.pygrass.modules.grid.split import split_region_tiles from grass.pygrass.gis import Location from grass.pygrass.utils import set_path set_path("i.segment.hierarchical") from isegpatch import rpatch_map DEBUG = False class SegModule(GridModule): """Extend the GridModule class, modifying the patch method.""" def __init__(self, *args, **kwargs): self.memory = kwargs["memory"] super(SegModule, self).__init__(*args, **kwargs) def patch(self): """Patch the final results.""" # make all mapset in the location visible loc = Location()
from __future__ import absolute_import, division, print_function, unicode_literals from importlib.machinery import SourceFileLoader import sys import os from pprint import pprint from fnmatch import fnmatch import numpy as np from grass.pygrass.utils import set_path from grass.pygrass.messages import get_msgr from grass.pygrass.vector import Vector from grass.pygrass.modules import Module from grass.script.core import parser, overwrite set_path("v.class.ml") from training_extraction import extract_training from sqlite2npy import save2npy from npy2table import export_results DECMP = {} def load_decompositions(): """Import decompositions and update dictionary which stores them""" from sklearn.decomposition import ( PCA, KernelPCA, ProbabilisticPCA, RandomizedPCA,
import numpy as np from grass.pygrass.messages import get_msgr from grass.pygrass.utils import set_path from grass.pygrass.vector import VectorTopo from grass.script import core as gcore try: from scipy.optimize import fsolve except ImportError: gcore.warning("You should install scipy to use this module: " "pip install scipy") try: # set python path to the shared r.green libraries set_path("r.green", "libhydro", "..") set_path("r.green", "libgreen", os.path.join("..", "..")) from libgreen.utils import cleanup from libhydro.plant import power2energy from libhydro.optimal import conv_segpoints except ImportError: try: set_path("r.green", "libhydro", os.path.join("..", "etc", "r.green")) set_path("r.green", "libgreen", os.path.join("..", "etc", "r.green")) from libgreen.utils import cleanup from libhydro.plant import power2energy from libhydro.optimal import conv_segpoints except ImportError: gcore.warning("libgreen and libhydro not in the python path!") DEBUG = False
# % keyword: precipitation # % keyword: microwave # % keyword: link # %end VERSION = 1.3 import sys import os import tempfile import time import grass.script as grass from grass.pygrass.utils import set_path set_path(modulename="g.gui.mwprecip", dirname="etc") from grass.script.setup import set_gui_path set_gui_path() from mw_util import * from mw3 import * from core.gcmd import GMessage, GError from gui_core import gselect from core.gthread import gThread from gui_core.widgets import ColorTablesComboBox, PictureComboBox from core import globalvar from core.utils import GetColorTables import wx.lib.scrolledpanel as scrolled import logging
#!/usr/bin/env python VERSION = 1.3 import sys import os import tempfile import time import grass.script as grass from grass.pygrass.utils import set_path set_path(modulename='g.gui.mwprecip') from grass.script.setup import set_gui_path set_gui_path() from mw_util import * from mw3 import * from core.gcmd import GMessage, GError from gui_core import gselect from core.gthread import gThread from gui_core.widgets import ColorTablesComboBox, PictureComboBox from core import globalvar from core.utils import GetColorTables import wx.lib.scrolledpanel as scrolled import tempfile import logging class DBconn(wx.ScrolledWindow): def __init__(self, parent, settings={}): wx.ScrolledWindow.__init__(self, parent, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.HSCROLL | wx.VSCROLL)