def setUpClass(cls): start_app() from processing.core.Processing import Processing Processing.initialize() cls.cleanup_paths = [] assert Grass7Utils.installedVersion()
def processOutputs(alg, parameters, context, feedback): outputName = alg.parameterAsString(parameters, 'output', context) createOpt = alg.parameterAsString(parameters, alg.GRASS_RASTER_FORMAT_OPT, context) metaOpt = alg.parameterAsString(parameters, alg.GRASS_RASTER_FORMAT_META, context) for channel in ['red', 'green', 'blue']: fileName = alg.parameterAsOutputLayer(parameters, '{}output'.format(channel), context) grassName = '{}_{}'.format(outputName, channel) outFormat = Grass7Utils.getRasterFormatFromFilename(fileName) alg.exportRasterLayer(grassName, fileName, True, outFormat, createOpt, metaOpt)
def processOutputs(alg, parameters, context): createOpt = alg.parameterAsString(parameters, alg.GRASS_RASTER_FORMAT_OPT, context) metaOpt = alg.parameterAsString(parameters, alg.GRASS_RASTER_FORMAT_META, context) # We need to export the raster with all its bands and its color table fileName = alg.parameterAsOutputLayer(parameters, 'output', context) outFormat = Grass7Utils.getRasterFormatFromFilename(fileName) grassName = alg.exportedLayers['map'] alg.exportRasterLayer(grassName, fileName, True, outFormat, createOpt, metaOpt)
def setUpClass(cls): start_app() from processing.core.Processing import Processing Processing.initialize() cls.cleanup_paths = [] cls.temp_dir = tempfile.mkdtemp() cls.cleanup_paths.append(cls.temp_dir) assert Grass7Utils.installedVersion()
def testGrass(self): '''Test GRASS is installed QGIS-89 (2)''' folder = ProcessingConfig.getSetting(Grass7Utils.GRASS_FOLDER) try: ProcessingConfig.removeSetting(Grass7Utils.GRASS_FOLDER) except KeyError: pass msg = Grass7Utils.checkGrassIsInstalled() self.assertIsNone(msg) ProcessingConfig.setSettingValue(Grass7Utils.GRASS_FOLDER, folder)
def exportSigFile(alg, group, subgroup, dest, sigDir='sig'): """ Export a signature file from internal GRASSDB to final destination """ shortSigFile = os.path.basename(dest) interSig = os.path.join(Grass7Utils.grassMapsetFolder(), 'PERMANENT', 'group', group, 'subgroup', subgroup, sigDir, shortSigFile) moveFile(alg, interSig, dest) return interSig
def importSigFile(alg, group, subgroup, src, sigDir='sig'): """ Import a signature file into an internal GRASSDB folder """ shortSigFile = os.path.basename(src) interSig = os.path.join(Grass7Utils.grassMapsetFolder(), 'PERMANENT', 'group', group, 'subgroup', subgroup, sigDir, shortSigFile) copyFile(alg, src, interSig) return shortSigFile
def processOutputs(alg, parameters, context, feedback): createOpt = alg.parameterAsString(parameters, alg.GRASS_RASTER_FORMAT_OPT, context) metaOpt = alg.parameterAsString(parameters, alg.GRASS_RASTER_FORMAT_META, context) # Export the results from correctedoutput grassName = 'correctedoutput{}'.format(alg.uniqueSuffix) fileName = alg.parameterAsOutputLayer( parameters, 'routput', context) outFormat = Grass7Utils.getRasterFormatFromFilename(fileName) alg.exportRasterLayer(grassName, fileName, True, outFormat, createOpt, metaOpt)
def processOutputs(alg, parameters, context, feedback): createOpt = alg.parameterAsString(parameters, alg.GRASS_RASTER_FORMAT_OPT, context) metaOpt = alg.parameterAsString(parameters, alg.GRASS_RASTER_FORMAT_META, context) # Export each color raster colors = ['red', 'green', 'blue'] for color in colors: fileName = os.path.normpath( alg.parameterAsOutputLayer(parameters, 'output_{}'.format(color), context)) outFormat = Grass7Utils.getRasterFormatFromFilename(fileName) alg.exportRasterLayer('blended.{}'.format(color[0]), fileName, True, outFormat, createOpt, metaOpt)
def processOutputs(alg, parameters, context): createOpt = alg.parameterAsString(parameters, alg.GRASS_RASTER_FORMAT_OPT, context) metaOpt = alg.parameterAsString(parameters, alg.GRASS_RASTER_FORMAT_META, context) outputDir = alg.parameterAsString(parameters, 'output_dir', context) outputParam = alg.parameterAsString(parameters, 'output', context) outputs = outputParam.split(',') # We need to export each of the output for output in outputs: fileName = os.path.join(outputDir, output) outFormat = Grass7Utils.getRasterFormatFromFilename(fileName) alg.exportRasterLayer(output, fileName, True, outFormat, createOpt, metaOpt)
def processOutputs(alg, parameters, context, feedback): createOpt = alg.parameterAsString(parameters, alg.GRASS_RASTER_FORMAT_OPT, context) metaOpt = alg.parameterAsString(parameters, alg.GRASS_RASTER_FORMAT_META, context) # Export all rasters with their color tables (and their bands) rasters = alg.parameterAsLayerList(parameters, 'map', context) outputDir = alg.parameterAsString(parameters, 'output_dir', context) for idx, raster in enumerate(rasters): rasterName = 'map_{}'.format(idx) fileName = os.path.join(outputDir, rasterName) outFormat = Grass7Utils.getRasterFormatFromFilename(fileName) alg.exportRasterLayer(alg.exportedLayers[rasterName], fileName, True, outFormat, createOpt, metaOpt)
def processOutputs(alg, parameters, context, feedback): createOpt = alg.parameterAsString(parameters, alg.GRASS_RASTER_FORMAT_OPT, context) metaOpt = alg.parameterAsString(parameters, alg.GRASS_RASTER_FORMAT_META, context) outputDir = alg.parameterAsString(parameters, 'output_dir', context) outputParam = alg.parameterAsString(parameters, 'output', context) outputs = outputParam.split(',') # We need to export each of the output for output in outputs: fileName = os.path.join(outputDir, output) outFormat = Grass7Utils.getRasterFormatFromFilename(fileName) alg.exportRasterLayer(output, fileName, True, outFormat, createOpt, metaOpt)
def exportInputRasters(alg, parameters, context, rasterDic): """ Export input rasters Use a dict to make input/output link: { 'inputName1': 'outputName1', 'inputName2': 'outputName2'} """ createOpt = alg.parameterAsString(parameters, alg.GRASS_RASTER_FORMAT_OPT, context) metaOpt = alg.parameterAsString(parameters, alg.GRASS_RASTER_FORMAT_META, context) # Get inputs and outputs for inputName, outputName in rasterDic.items(): fileName = os.path.normpath( alg.parameterAsOutputLayer(parameters, outputName, context)) grassName = alg.exportedLayers[inputName] outFormat = Grass7Utils.getRasterFormatFromFilename(fileName) alg.exportRasterLayer(grassName, fileName, True, outFormat, createOpt, metaOpt)
def processOutputs(alg, parameters, context, feedback): # We take all the outputs and we export them to the output directory outputDir = alg.parameterAsString(parameters, 'output_dir', context) output = alg.parameterAsString(parameters, 'output', context) outfile = alg.parameterAsString(parameters, 'outfile', context) outs = [] if output: outs = output.split(',') elif outfile: # Handle file manually to find the name of the layers with open(outfile) as f: for line in f: if '|' in line: outs.append(line.split('|')[0]) createOpt = alg.parameterAsString(parameters, alg.GRASS_RASTER_FORMAT_OPT, context) metaOpt = alg.parameterAsString(parameters, alg.GRASS_RASTER_FORMAT_META, context) for out in outs: # We need to export the raster with all its bands and its color table fileName = os.path.join(outputDir, out) outFormat = Grass7Utils.getRasterFormatFromFilename(fileName) alg.exportRasterLayer(out, fileName, True, outFormat, createOpt, metaOpt)
def qgis_session_info(self): # import re # from processing.algs.saga.SagaAlgorithmProvider import SagaAlgorithmProvider # from processing.algs.saga import SagaUtils # from processing.algs.grass.GrassUtils import GrassUtils # from processing.algs.grass7.Grass7Utils import Grass7Utils # from processing.algs.otb.OTBAlgorithmProvider import OTBAlgorithmProvider # from processing.algs.otb.OTBUtils import getInstalledVersion # from processing.algs.taudem.TauDEMUtils import TauDEMUtils # from osgeo import gdal # from processing.tools.system import isWindows, isMac # QGIS version qgis = QGis.QGIS_VERSION # GRASS versions # grassPath returns "" if called under Linux and if there is no GRASS # installation GrassUtils.checkGrassIsInstalled() g6 = GrassUtils.isGrassInstalled if g6 is True and isWindows(): g6 = GrassUtils.grassPath() # extract everything followed by grass-, i.e. extract the version number g6 = re.findall("grass-(.*)", g6) if g6 is True and isMac(): g6 = GrassUtils.grassPath()[0:21] g6 = os.listdir(g6) delim = ';' g6 = delim.join(g6) g6 = re.findall('[0-9].[0-9].[0-9]', g6) Grass7Utils.checkGrass7IsInstalled() g7 = Grass7Utils.isGrass7Installed if g7 is True and isWindows(): g7 = Grass7Utils.grassPath() g7 = re.findall('grass-(.*)', g7) if g7 is True and isMac(): g7 = Grass7Utils.grassPath()[0:21] g7 = os.listdir(g7) delim = ';' g7 = delim.join(g7) #g7 = re.findall(';(grass[0-9].);', g7) g7 = re.findall('[0-9].[0-9].[0-9]', g7) # installed SAGA version usable with QGIS saga = SagaUtils.getSagaInstalledVersion() # supported SAGA versions try: # supportedVersions were deleted from SagaAlgorithmProvider since # QGIS 2.18.10. At least this is the case with custom applications... my_dict = SagaAlgorithmProvider.supportedVersions saga_versions = my_dict.keys() saga_versions.sort() except: # with QGIS 2.18.10 only SAGA 2.3.0 and 2.3.1 is suppported # well, observe next QGIS releases and try to avoid the hard-coding! saga_versions = [""] # GDAL gdal_v = gdal.VersionInfo('VERSION_NUM') gdal_v = '.'.join([gdal_v[0], gdal_v[2], gdal_v[4]]) ## this is good to have for the future, but so far, I would not report ## these software versions since we don't know if they actually work ## with QGIS (without additional functions such as run_taudem...) ## OTB versions # otb = getInstalledVersion() # otb = OTBUtils.getInstalledVersion() ## TauDEM versions (currently not in use because no function to extract ## Taudem version in 'TauDEMUtils') # TauDEMUtils.taudemMultifilePath() # finally, put it all into a named dictionary keys = ["qgis_version", "gdal", "grass6", "grass7", "saga",\ "supported_saga_versions"] values = [qgis, gdal_v, g6, g7, saga, saga_versions] info = dict(zip(keys, values)) return info
def run(self): """Run method that performs all the real work""" # Create the dialog with elements (after translation) and keep reference # Only create GUI ONCE in callback, so that it will only load when the plugin is started if self.first_start == True: self.first_start = False self.dlg = DissolveToolDialog() self.dlg.pushButton.clicked.connect(self.select_output_vector) self.dlg.pushButton_2.clicked.connect(self.select_output_gaps) self.dlg.pushButton_3.clicked.connect(self.select_grass_addon) # Fetch the currently loaded layers layers = QgsProject.instance().layerTreeRoot().children() # Clear the contents of the comboBox from previous runs self.dlg.comboBox.clear() # Populate the comboBox with names of all the loaded layers self.dlg.comboBox.addItems([layer.name() for layer in layers]) # Clear the contents of the comboBox from previous runs self.dlg.comboBox_2.clear() # Populate the comboBox with names of all the loaded layers self.dlg.comboBox_2.addItems([layer.name() for layer in layers]) mingapsize = "10000000" self.dlg.lineEdit_4.setText(mingapsize) discol = "DISS_CENTR" self.dlg.lineEdit_5.setText(discol) # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: # Do something useful here - delete the line containing pass and # substitute with your code. feedback = QgsProcessingFeedback() # old partner regions selectedLayerIndex = self.dlg.comboBox.currentIndex() partner_regions_old = layers[selectedLayerIndex].layer( ).dataProvider().dataSourceUri() partner_regions_old = partner_regions_old[:partner_regions_old. rfind('|')] # partner region to add selectedLayerIndex = self.dlg.comboBox_2.currentIndex() partner_region_add = layers[selectedLayerIndex].layer( ).dataProvider().dataSourceUri() partner_region_add = partner_region_add[:partner_region_add. rfind('|')] self.iface.messageBar().pushMessage( "Info", "Partner region to add is in " + partner_region_add, level=Qgis.Info, duration=3) outputvector = self.dlg.lineEdit.text() remaining_gaps = self.dlg.lineEdit_2.text() mingapsize = self.dlg.lineEdit_4.text() discol = self.dlg.lineEdit_5.text() grasscommand = Grass7Utils.grassBin() if not grasscommand: self.iface.messageBar().pushMessage("Error", "GRASS GIS not found", level=Qgis.Critical, duration=3) # install the GRASS addon v.ecmwf.adregions grassaddonpath = self.dlg.lineEdit_3.text() if grassaddonpath: gcommands = ( "g.extension extension=v.ecmwf.addregion url='%s'" % grassaddonpath) Grass7Utils.executeGrass([gcommands], feedback) gcommands = ( "v.ecmwf.addregion partner_regions=\"%s\" new_partner=\"%s\" output=\"%s\"" % (partner_regions_old, partner_region_add, outputvector)) if discol: gcommands = gcommands + (" column=%s " % discol) if mingapsize and int(mingapsize) > 0: gcommands = gcommands + (" mingapsize=%s" % mingapsize) if remaining_gaps: gcommands = gcommands + (" gaps=\"%s\"" % remaining_gaps) print("GRASS command:") print("%s" % gcommands) Grass7Utils.executeGrass([gcommands], feedback) self.iface.messageBar().pushMessage("Success", "Output vector written at " + outputvector, level=Qgis.Success, duration=3)
def qgis_session_info(self): # import re # from processing.algs.saga.SagaAlgorithmProvider import SagaAlgorithmProvider # from processing.algs.saga import SagaUtils # from processing.algs.grass.GrassUtils import GrassUtils # from processing.algs.grass7.Grass7Utils import Grass7Utils # from processing.algs.otb.OTBAlgorithmProvider import OTBAlgorithmProvider # from processing.algs.otb.OTBUtils import getInstalledVersion # from processing.algs.taudem.TauDEMUtils import TauDEMUtils # from osgeo import gdal # from processing.tools.system import isWindows, isMac # QGIS version qgis = QGis.QGIS_VERSION # GRASS versions # grassPath returns "" if called under Linux and if there is no GRASS # installation GrassUtils.checkGrassIsInstalled() g6 = GrassUtils.isGrassInstalled if g6 is True and isWindows(): g6 = GrassUtils.grassPath() # extract everything followed by grass-, i.e. extract the version number g6 = re.findall("grass-(.*)", g6) if g6 is True and isMac(): g6 = GrassUtils.grassPath()[0:21] g6 = os.listdir(g6) delim = ';' g6 = delim.join(g6) g6 = re.findall('[0-9].[0-9].[0-9]', g6) Grass7Utils.checkGrass7IsInstalled() g7 = Grass7Utils.isGrass7Installed if g7 is True and isWindows(): g7 = Grass7Utils.grassPath() g7 = re.findall('grass-(.*)', g7) if g7 is True and isMac(): g7 = Grass7Utils.grassPath()[0:21] g7 = os.listdir(g7) delim = ';' g7 = delim.join(g7) #g7 = re.findall(';(grass[0-9].);', g7) g7 = re.findall('[0-9].[0-9].[0-9]', g7) # installed SAGA version usable with QGIS saga = SagaUtils.getSagaInstalledVersion() # supported SAGA versions my_dict = SagaAlgorithmProvider.supportedVersions saga_versions = my_dict.keys() saga_versions.sort() # GDAL gdal_v = gdal.VersionInfo('VERSION_NUM') gdal_v = '.'.join([gdal_v[0], gdal_v[2], gdal_v[4]]) ## this is good to have for the future, but so far, I would not report ## these software versions since we don't know if they actually work ## with QGIS (without additional functions such as run_taudem...) ## OTB versions # otb = getInstalledVersion() # otb = OTBUtils.getInstalledVersion() ## TauDEM versions (currently not in use because no function to extract ## Taudem version in 'TauDEMUtils') # TauDEMUtils.taudemMultifilePath() # finally, put it all into a named dictionary keys = ["qgis_version", "gdal", "grass6", "grass7", "saga",\ "supported_saga_versions"] values = [qgis, gdal_v, g6, g7, saga, saga_versions] info = dict(zip(keys, values)) return info
def processOutputs(alg, parameters, context, feedback): crs = alg.parameterAsCrs(parameters, 'sourceproj', context) wkt_file_name = Grass7Utils.exportCrsWktToFile(crs) alg.commands.insert(0, 'g.proj -c wkt="{}"'.format(wkt_file_name))
from PyQt5.QtCore import QVariant import ogr import subprocess import pandas as pd from processing.tools import dataobjects from os import path import line_profiler profile = line_profiler.LineProfiler() # Pour faire marcher GRASS en StandAlone script # https://gis.stackexchange.com/questions/296502/pyqgis-scripts-outside-of-qgis-gui-running-processing-algorithms-from-grass-prov from processing.algs.grass7.Grass7Utils import Grass7Utils Grass7Utils.checkGrassIsInstalled() # Chemin ou QGIS est installer QgsApplication.setPrefixPath(r"C:\Logiciels\OSGeo4W\bin", True) # Créer une reference à QgsApplication, # Mettre le 2eme argument a faux pour desativer l'interface graphique de QGIS qgs = QgsApplication([], False) # initialiser QGIS qgs.initQgis() # Initialiser les outils qgis Processing.initialize()