def initializeSettings(self):
     AlgorithmProvider.initializeSettings(self)
     if ProcessingUtils.isWindows() or ProcessingUtils.isMac():
         ProcessingConfig.addSetting(Setting(self.getDescription(), GrassUtils.GRASS_FOLDER, "GRASS folder", GrassUtils.grassPath()))
         ProcessingConfig.addSetting(Setting(self.getDescription(), GrassUtils.GRASS_WIN_SHELL, "Msys folder", GrassUtils.grassWinShell()))
     ProcessingConfig.addSetting(Setting(self.getDescription(), GrassUtils.GRASS_LOG_COMMANDS, "Log execution commands", False))
     ProcessingConfig.addSetting(Setting(self.getDescription(), GrassUtils.GRASS_LOG_CONSOLE, "Log console output", False))
Beispiel #2
0
 def otbPath():
     folder = ProcessingConfig.getSetting(OTBUtils.OTB_FOLDER)
     if folder == None:
         folder = ""
         #try to configure the path automatically
         if ProcessingUtils.isMac():
             testfolder = os.path.join(str(QgsApplication.prefixPath()), "bin")
             if os.path.exists(os.path.join(testfolder, "otbcli")):
                 folder = testfolder
             else:
                 testfolder = "/usr/local/bin"
                 if os.path.exists(os.path.join(testfolder, "otbcli")):
                     folder = testfolder
         elif ProcessingUtils.isWindows():
             testfolder = os.path.dirname(str(QgsApplication.prefixPath()))
             testfolder = os.path.dirname(testfolder)
             testfolder = os.path.join(testfolder,  "bin")
             path = os.path.join(testfolder, "otbcli.bat")
             if os.path.exists(path):
                 folder = testfolder
         else:
             testfolder = "/usr/bin"
             if os.path.exists(os.path.join(testfolder, "otbcli")):
                 folder = testfolder
     return folder
 def unload(self):
     AlgorithmProvider.unload(self)
     if ProcessingUtils.isWindows() or ProcessingUtils.isMac():
         ProcessingConfig.removeSetting(GrassUtils.GRASS_FOLDER)
         ProcessingConfig.removeSetting(GrassUtils.GRASS_WIN_SHELL)
     ProcessingConfig.removeSetting(GrassUtils.GRASS_LOG_COMMANDS)
     ProcessingConfig.removeSetting(GrassUtils.GRASS_LOG_CONSOLE)
Beispiel #4
0
 def otbLibPath():
     folder = ProcessingConfig.getSetting(OTBUtils.OTB_LIB_FOLDER)
     if folder == None:
         folder = ""
         #try to configure the path automatically
         if ProcessingUtils.isMac():
             testfolder = os.path.join(str(QgsApplication.prefixPath()),
                                       "lib/otb/applications")
             if os.path.exists(testfolder):
                 folder = testfolder
             else:
                 testfolder = "/usr/local/lib/otb/applications"
                 if os.path.exists(testfolder):
                     folder = testfolder
         elif ProcessingUtils.isWindows():
             testfolder = os.path.dirname(str(QgsApplication.prefixPath()))
             testfolder = os.path.join(testfolder, "orfeotoolbox")
             testfolder = os.path.join(testfolder, "applications")
             if os.path.exists(testfolder):
                 folder = testfolder
         else:
             testfolder = "/usr/lib/otb/applications"
             if os.path.exists(testfolder):
                 folder = testfolder
     return folder
Beispiel #5
0
 def otbPath():
     folder = ProcessingConfig.getSetting(OTBUtils.OTB_FOLDER)
     if folder == None:
         folder = ""
         #try to configure the path automatically
         if ProcessingUtils.isMac():
             testfolder = os.path.join(str(QgsApplication.prefixPath()),
                                       "bin")
             if os.path.exists(os.path.join(testfolder, "otbcli")):
                 folder = testfolder
             else:
                 testfolder = "/usr/local/bin"
                 if os.path.exists(os.path.join(testfolder, "otbcli")):
                     folder = testfolder
         elif ProcessingUtils.isWindows():
             testfolder = os.path.dirname(str(QgsApplication.prefixPath()))
             testfolder = os.path.dirname(testfolder)
             testfolder = os.path.join(testfolder, "bin")
             path = os.path.join(testfolder, "otbcli.bat")
             if os.path.exists(path):
                 folder = testfolder
         else:
             testfolder = "/usr/bin"
             if os.path.exists(os.path.join(testfolder, "otbcli")):
                 folder = testfolder
     return folder
 def unload(self):
     AlgorithmProvider.unload(self)
     if ProcessingUtils.isWindows() or ProcessingUtils.isMac():
         ProcessingConfig.removeSetting(GrassUtils.GRASS_FOLDER)
         ProcessingConfig.removeSetting(GrassUtils.GRASS_WIN_SHELL)
     ProcessingConfig.removeSetting(GrassUtils.GRASS_LOG_COMMANDS)
     ProcessingConfig.removeSetting(GrassUtils.GRASS_LOG_CONSOLE)
Beispiel #7
0
 def exportRasterLayer(self, layer):
     destFilename = ProcessingUtils.getTempFilenameInTempFolder(os.path.basename(layer)[0:5] + ".sgrd")
     self.exportedLayers[layer]= destFilename
     saga208 = ProcessingConfig.getSetting(SagaUtils.SAGA_208)
     if ProcessingUtils.isWindows() or ProcessingUtils.isMac() or not saga208:
         return "io_gdal 0 -GRIDS \"" + destFilename + "\" -FILES \"" + layer+"\""
     else:
         return "libio_gdal 0 -GRIDS \"" + destFilename + "\" -FILES \"" + layer + "\""
Beispiel #8
0
 def exportRasterLayer(self, layer):
     destFilename = ProcessingUtils.getTempFilenameInTempFolder(
         os.path.basename(layer)[0:5] + ".sgrd")
     self.exportedLayers[layer] = destFilename
     saga208 = ProcessingConfig.getSetting(SagaUtils.SAGA_208)
     if ProcessingUtils.isWindows() or ProcessingUtils.isMac(
     ) or not saga208:
         return "io_gdal 0 -GRIDS \"" + destFilename + "\" -FILES \"" + layer + "\""
     else:
         return "libio_gdal 0 -GRIDS \"" + destFilename + "\" -FILES \"" + layer + "\""
Beispiel #9
0
    def mpiexecPath():
        folder = ProcessingConfig.getSetting(TauDEMUtils.MPIEXEC_FOLDER)
        if folder == None:
            folder = ""

        if ProcessingUtils.isMac():
            testfolder = os.path.join(QgsApplication.prefixPath(), "bin")
            if os.path.exists(os.path.join(testfolder, "mpiexec")):
                folder = testfolder
            else:
                testfolder = "/usr/local/bin"
                if os.path.exists(os.path.join(testfolder, "mpiexec")):
                    folder = testfolder
        return folder
Beispiel #10
0
    def taudemPath():
        folder = ProcessingConfig.getSetting(TauDEMUtils.TAUDEM_FOLDER)
        if folder == None:
            folder = ""

        if ProcessingUtils.isMac():
            testfolder = os.path.join(QgsApplication.prefixPath(), "bin")
            if os.path.exists(os.path.join(testfolder, "slopearea")):
                folder = testfolder
            else:
                testfolder = "/usr/local/bin"
                if os.path.exists(os.path.join(testfolder, "slopearea")):
                    folder = testfolder
        return folder
Beispiel #11
0
    def mpiexecPath():
        folder = ProcessingConfig.getSetting(TauDEMUtils.MPIEXEC_FOLDER)
        if folder == None:
            folder = ""

        if ProcessingUtils.isMac():
            testfolder = os.path.join(QgsApplication.prefixPath(), "bin")
            if os.path.exists(os.path.join(testfolder, "mpiexec")):
                folder = testfolder
            else:
                testfolder = "/usr/local/bin"
                if os.path.exists(os.path.join(testfolder, "mpiexec")):
                    folder = testfolder
        return folder
Beispiel #12
0
    def taudemPath():
        folder = ProcessingConfig.getSetting(TauDEMUtils.TAUDEM_FOLDER)
        if folder == None:
            folder = ""

        if ProcessingUtils.isMac():
            testfolder = os.path.join(QgsApplication.prefixPath(), "bin")
            if os.path.exists(os.path.join(testfolder, "slopearea")):
                folder = testfolder
            else:
                testfolder = "/usr/local/bin"
                if os.path.exists(os.path.join(testfolder, "slopearea")):
                    folder = testfolder
        return folder
 def initializeSettings(self):
     AlgorithmProvider.initializeSettings(self)
     if ProcessingUtils.isWindows() or ProcessingUtils.isMac():
         ProcessingConfig.addSetting(
             Setting(self.getDescription(), GrassUtils.GRASS_FOLDER,
                     "GRASS folder", GrassUtils.grassPath()))
         ProcessingConfig.addSetting(
             Setting(self.getDescription(), GrassUtils.GRASS_WIN_SHELL,
                     "Msys folder", GrassUtils.grassWinShell()))
     ProcessingConfig.addSetting(
         Setting(self.getDescription(), GrassUtils.GRASS_LOG_COMMANDS,
                 "Log execution commands", False))
     ProcessingConfig.addSetting(
         Setting(self.getDescription(), GrassUtils.GRASS_LOG_CONSOLE,
                 "Log console output", False))
Beispiel #14
0
 def exportRasterLayer(self, source):
     layer = QGisLayers.getObjectFromUri(source, False)
     if layer:
         filename = str(layer.name())
     else:
         filename = source.rstrip(".sgrd")
     validChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789:"
     filename = ''.join(c for c in filename if c in validChars)
     if len(filename) == 0:
         filename = "layer"
     destFilename = ProcessingUtils.getTempFilenameInTempFolder(filename + ".sgrd")
     self.exportedLayers[source]= destFilename
     saga208 = ProcessingConfig.getSetting(SagaUtils.SAGA_208)
     if ProcessingUtils.isWindows() or ProcessingUtils.isMac() or not saga208:
         return "io_gdal 0 -GRIDS \"" + destFilename + "\" -FILES \"" + source+"\""
     else:
         return "libio_gdal 0 -GRIDS \"" + destFilename + "\" -FILES \"" + source + "\""
Beispiel #15
0
    def createSagaBatchJobFileFromSagaCommands(commands):

        fout = open(SagaUtils.sagaBatchJobFilename(), "w")
        if ProcessingUtils.isWindows():
            fout.write("set SAGA=" + SagaUtils.sagaPath() + "\n")
            fout.write("set SAGA_MLB=" + SagaUtils.sagaPath() + os.sep + "modules" + "\n")
            fout.write("PATH=PATH;%SAGA%;%SAGA_MLB%\n")
        elif ProcessingUtils.isMac():
            fout.write("export SAGA_MLB=" + SagaUtils.sagaPath() + "/../lib/saga\n")
            fout.write("export PATH=" + SagaUtils.sagaPath() + ":$PATH\n")
        else:
            pass
        for command in commands:
            fout.write("saga_cmd " + command.encode("utf8") + "\n")

        fout.write("exit")
        fout.close()
Beispiel #16
0
    def createSagaBatchJobFileFromSagaCommands(commands):

        fout = open(SagaUtils.sagaBatchJobFilename(), "w")
        if ProcessingUtils.isWindows():
            fout.write("set SAGA=" + SagaUtils.sagaPath() + "\n");
            fout.write("set SAGA_MLB=" + SagaUtils.sagaPath() + os.sep + "modules" + "\n");
            fout.write("PATH=PATH;%SAGA%;%SAGA_MLB%\n");
        elif ProcessingUtils.isMac():
            fout.write("export SAGA_MLB=" + SagaUtils.sagaPath() + "/../lib/saga\n");
            fout.write("export PATH=" + SagaUtils.sagaPath() + ":$PATH\n");
        else:
            pass
        for command in commands:
            fout.write("saga_cmd " + command.encode("utf8") + "\n")

        fout.write("exit")
        fout.close()
Beispiel #17
0
    def prepareGrassExecution(commands):
        if ProcessingUtils.isWindows():
            GrassUtils.createGrassScript(commands)
            command = ["cmd.exe", "/C ", GrassUtils.grassScriptFilename()]
        else:
            gisrc =  ProcessingUtils.userFolder() + os.sep + "processing.gisrc"
            os.putenv("GISRC", gisrc)
            os.putenv("GRASS_MESSAGE_FORMAT", "gui")
            os.putenv("GRASS_BATCH_JOB", GrassUtils.grassBatchJobFilename())
            GrassUtils.createGrassBatchJobFileFromGrassCommands(commands)
            os.chmod(GrassUtils.grassBatchJobFilename(), stat.S_IEXEC | stat.S_IREAD | stat.S_IWRITE)
            if ProcessingUtils.isMac():
                command = GrassUtils.grassPath() + os.sep + "grass.sh " + GrassUtils.grassMapsetFolder() + "/PERMANENT"
            else:
                command = "grass64 " + GrassUtils.grassMapsetFolder() + "/PERMANENT"

        return command
Beispiel #18
0
 def resampleRasterLayer(self,layer):
     '''this is supposed to be run after having exported all raster layers'''
     if layer in self.exportedLayers.keys():
         inputFilename = self.exportedLayers[layer]
     else:
         inputFilename = layer
     destFilename = ProcessingUtils.getTempFilename("sgrd")
     self.exportedLayers[layer]= destFilename
     saga208 = ProcessingConfig.getSetting(SagaUtils.SAGA_208)
     if ProcessingUtils.isWindows() or ProcessingUtils.isMac() or not saga208:
         s = "grid_tools \"Resampling\" -INPUT \"" + inputFilename + "\" -TARGET 0 -SCALE_UP_METHOD 4 -SCALE_DOWN_METHOD 4 -USER_XMIN " +\
             str(self.xmin) + " -USER_XMAX " + str(self.xmax) + " -USER_YMIN " + str(self.ymin) + " -USER_YMAX "  + str(self.ymax) +\
             " -USER_SIZE " + str(self.cellsize) + " -USER_GRID \"" + destFilename + "\""
     else:
         s = "libgrid_tools \"Resampling\" -INPUT \"" + inputFilename + "\" -TARGET 0 -SCALE_UP_METHOD 4 -SCALE_DOWN_METHOD 4 -USER_XMIN " +\
             str(self.xmin) + " -USER_XMAX " + str(self.xmax) + " -USER_YMIN " + str(self.ymin) + " -USER_YMAX "  + str(self.ymax) +\
             " -USER_SIZE " + str(self.cellsize) + " -USER_GRID \"" + destFilename + "\""
     return s
Beispiel #19
0
 def sagaPath():
     folder = ProcessingConfig.getSetting(SagaUtils.SAGA_FOLDER)
     if folder == None:
         folder = ""
         # try to auto-configure the folder
         if ProcessingUtils.isMac():
             testfolder = os.path.join(str(QgsApplication.prefixPath()), "bin")
             if os.path.exists(os.path.join(testfolder, "saga_cmd")):
                 folder = testfolder
             else:
                 testfolder = "/usr/local/bin"
                 if os.path.exists(os.path.join(testfolder, "saga_cmd")):
                     folder = testfolder
         elif ProcessingUtils.isWindows():
             testfolder = os.path.dirname(str(QgsApplication.prefixPath()))
             testfolder = os.path.join(testfolder, "saga")
             if os.path.exists(os.path.join(testfolder, "saga_cmd.exe")):
                 folder = testfolder
     return folder
Beispiel #20
0
 def sagaPath():
     folder = ProcessingConfig.getSetting(SagaUtils.SAGA_FOLDER)
     if folder == None:
         folder =""
         #try to auto-configure the folder
         if ProcessingUtils.isMac():
             testfolder = os.path.join(str(QgsApplication.prefixPath()), "bin")
             if os.path.exists(os.path.join(testfolder, "saga_cmd")):
                 folder = testfolder
             else:
                 testfolder = "/usr/local/bin"
                 if os.path.exists(os.path.join(testfolder, "saga_cmd")):
                     folder = testfolder
         elif ProcessingUtils.isWindows():
             testfolder = os.path.dirname(str(QgsApplication.prefixPath()))
             testfolder = os.path.join(testfolder,  "saga")
             if os.path.exists(os.path.join(testfolder, "saga_cmd.exe")):
                 folder = testfolder
     return folder
Beispiel #21
0
 def exportRasterLayer(self, source):
     layer = QGisLayers.getObjectFromUri(source, False)
     if layer:
         filename = str(layer.name())
     else:
         filename = source.rstrip(".sgrd")
     validChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789:"
     filename = ''.join(c for c in filename if c in validChars)
     if len(filename) == 0:
         filename = "layer"
     destFilename = ProcessingUtils.getTempFilenameInTempFolder(filename +
                                                                ".sgrd")
     self.exportedLayers[source] = destFilename
     saga208 = ProcessingConfig.getSetting(SagaUtils.SAGA_208)
     if ProcessingUtils.isWindows() or ProcessingUtils.isMac(
     ) or not saga208:
         return "io_gdal 0 -GRIDS \"" + destFilename + "\" -FILES \"" + source + "\""
     else:
         return "libio_gdal 0 -GRIDS \"" + destFilename + "\" -FILES \"" + source + "\""
Beispiel #22
0
 def resampleRasterLayer(self, layer):
     '''this is supposed to be run after having exported all raster layers'''
     if layer in self.exportedLayers.keys():
         inputFilename = self.exportedLayers[layer]
     else:
         inputFilename = layer
     destFilename = ProcessingUtils.getTempFilename("sgrd")
     self.exportedLayers[layer] = destFilename
     saga208 = ProcessingConfig.getSetting(SagaUtils.SAGA_208)
     if ProcessingUtils.isWindows() or ProcessingUtils.isMac(
     ) or not saga208:
         s = "grid_tools \"Resampling\" -INPUT \"" + inputFilename + "\" -TARGET 0 -SCALE_UP_METHOD 4 -SCALE_DOWN_METHOD 4 -USER_XMIN " +\
             str(self.xmin) + " -USER_XMAX " + str(self.xmax) + " -USER_YMIN " + str(self.ymin) + " -USER_YMAX "  + str(self.ymax) +\
             " -USER_SIZE " + str(self.cellsize) + " -USER_GRID \"" + destFilename + "\""
     else:
         s = "libgrid_tools \"Resampling\" -INPUT \"" + inputFilename + "\" -TARGET 0 -SCALE_UP_METHOD 4 -SCALE_DOWN_METHOD 4 -USER_XMIN " +\
             str(self.xmin) + " -USER_XMAX " + str(self.xmax) + " -USER_YMIN " + str(self.ymin) + " -USER_YMAX "  + str(self.ymax) +\
             " -USER_SIZE " + str(self.cellsize) + " -USER_GRID \"" + destFilename + "\""
     return s
Beispiel #23
0
    def grassPath():
        if not ProcessingUtils.isWindows() and not ProcessingUtils.isMac():
            return ""

        folder = ProcessingConfig.getSetting(GrassUtils.GRASS_FOLDER)
        if folder == None:
            if ProcessingUtils.isWindows():
                testfolder = os.path.dirname(str(QgsApplication.prefixPath()))
                testfolder = os.path.join(testfolder,  "grass")
                if os.path.isdir(testfolder):
                    for subfolder in os.listdir(testfolder):
                        if subfolder.startswith("grass"):
                            folder = os.path.join(testfolder, subfolder)
                            break
            else:
                folder = os.path.join(str(QgsApplication.prefixPath()), "grass")
                if not os.path.isdir(folder):
                    folder = "/Applications/GRASS-6.4.app/Contents/MacOS"

        return folder
Beispiel #24
0
    def prepareGrassExecution(commands):
        if ProcessingUtils.isWindows():
            GrassUtils.createGrassScript(commands)
            command = ["cmd.exe", "/C ", GrassUtils.grassScriptFilename()]
        else:
            gisrc = ProcessingUtils.userFolder() + os.sep + "processing.gisrc"
            os.putenv("GISRC", gisrc)
            os.putenv("GRASS_MESSAGE_FORMAT", "gui")
            os.putenv("GRASS_BATCH_JOB", GrassUtils.grassBatchJobFilename())
            GrassUtils.createGrassBatchJobFileFromGrassCommands(commands)
            os.chmod(GrassUtils.grassBatchJobFilename(),
                     stat.S_IEXEC | stat.S_IREAD | stat.S_IWRITE)
            if ProcessingUtils.isMac():
                command = GrassUtils.grassPath(
                ) + os.sep + "grass.sh " + GrassUtils.grassMapsetFolder(
                ) + "/PERMANENT"
            else:
                command = "grass64 " + GrassUtils.grassMapsetFolder(
                ) + "/PERMANENT"

        return command
Beispiel #25
0
    def grassPath():
        if not ProcessingUtils.isWindows() and not ProcessingUtils.isMac():
            return ""

        folder = ProcessingConfig.getSetting(GrassUtils.GRASS_FOLDER)
        if folder == None:
            if ProcessingUtils.isWindows():
                testfolder = os.path.dirname(str(QgsApplication.prefixPath()))
                testfolder = os.path.join(testfolder, "grass")
                if os.path.isdir(testfolder):
                    for subfolder in os.listdir(testfolder):
                        if subfolder.startswith("grass"):
                            folder = os.path.join(testfolder, subfolder)
                            break
            else:
                folder = os.path.join(str(QgsApplication.prefixPath()),
                                      "grass")
                if not os.path.isdir(folder):
                    folder = "/Applications/GRASS-6.4.app/Contents/MacOS"

        return folder
Beispiel #26
0
 def otbLibPath():
     folder = ProcessingConfig.getSetting(OTBUtils.OTB_LIB_FOLDER)
     if folder == None:
         folder =""
         #try to configure the path automatically
         if ProcessingUtils.isMac():
             testfolder = os.path.join(str(QgsApplication.prefixPath()), "lib/otb/applications")
             if os.path.exists(testfolder):
                 folder = testfolder
             else:
                 testfolder = "/usr/local/lib/otb/applications"
                 if os.path.exists(testfolder):
                     folder = testfolder
         elif ProcessingUtils.isWindows():
             testfolder = os.path.dirname(str(QgsApplication.prefixPath()))
             testfolder = os.path.join(testfolder,  "orfeotoolbox")
             testfolder = os.path.join(testfolder,  "applications")
             if os.path.exists(testfolder):
                 folder = testfolder
         else:
             testfolder = "/usr/lib/otb/applications"
             if os.path.exists(testfolder):
                 folder = testfolder
     return folder
Beispiel #27
0
    def processAlgorithm(self, progress):
        if ProcessingUtils.isWindows():
            path = SagaUtils.sagaPath()
            if path == "":
                raise GeoAlgorithmExecutionException("SAGA folder is not configured.\nPlease configure it before running SAGA algorithms.")
        commands = list()
        self.exportedLayers = {}

        self.preProcessInputs()

        #1: Export rasters to sgrd and vectors to shp
        #   Tables must be in dbf format. We check that.
        if self.resample:
            self.calculateResamplingExtent()
        for param in self.parameters:
            if isinstance(param, ParameterRaster):
                if param.value == None:
                    continue
                value = param.value
                if not value.endswith("sgrd"):
                    commands.append(self.exportRasterLayer(value))
                if self.resample:
                    commands.append(self.resampleRasterLayer(value));
            if isinstance(param, ParameterVector):
                if param.value == None:
                    continue
                layer = QGisLayers.getObjectFromUri(param.value, False)
                if layer:
                    filename = LayerExporter.exportVectorLayer(layer)
                    self.exportedLayers[param.value]=filename
                elif not param.value.endswith("shp"):
                    raise GeoAlgorithmExecutionException("Unsupported file format")
            if isinstance(param, ParameterTable):
                if param.value == None:
                    continue
                table = QGisLayers.getObjectFromUri(param.value, False)
                if table:
                    filename = LayerExporter.exportTable(table)
                    self.exportedLayers[param.value]=filename
                elif not param.value.endswith("shp"):
                        raise GeoAlgorithmExecutionException("Unsupported file format")
            if isinstance(param, ParameterMultipleInput):
                if param.value == None:
                    continue
                layers = param.value.split(";")
                if layers == None or len(layers) == 0:
                    continue
                if param.datatype == ParameterMultipleInput.TYPE_RASTER:
                    for layerfile in layers:
                        if not layerfile.endswith("sgrd"):
                            commands.append(self.exportRasterLayer(layerfile))
                        if self.resample:
                            commands.append(self.resampleRasterLayer(layerfile));
                elif param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY:
                    for layerfile in layers:
                        layer = QGisLayers.getObjectFromUri(layerfile, False)
                        if layer:
                            filename = LayerExporter.exportVectorLayer(layer)
                            self.exportedLayers[layerfile]=filename
                        elif (not layerfile.endswith("shp")):
                            raise GeoAlgorithmExecutionException("Unsupported file format")

        #2: set parameters and outputs
        saga208 = ProcessingConfig.getSetting(SagaUtils.SAGA_208)
        if ProcessingUtils.isWindows() or ProcessingUtils.isMac() or not saga208:
            command = self.undecoratedGroup  + " \"" + self.cmdname + "\""
        else:
            command = "lib" + self.undecoratedGroup  + " \"" + self.cmdname + "\""

        if self.hardcodedStrings:
            for s in self.hardcodedStrings:
                command += " " + s

        for param in self.parameters:
            if param.value is None:
                continue
            if isinstance(param, (ParameterRaster, ParameterVector, ParameterTable)):
                value = param.value
                if value in self.exportedLayers.keys():
                    command += (" -" + param.name + " \"" + self.exportedLayers[value] + "\"")
                else:
                    command += (" -" + param.name + " \"" + value + "\"")
            elif isinstance(param, ParameterMultipleInput):
                s = param.value
                for layer in self.exportedLayers.keys():
                    s = s.replace(layer, self.exportedLayers[layer])
                command += (" -" + param.name + " \"" + s + "\"");
            elif isinstance(param, ParameterBoolean):
                if param.value:
                    command+=(" -" + param.name);
            elif isinstance(param, ParameterFixedTable):
                tempTableFile  = ProcessingUtils.getTempFilename("txt")
                f = open(tempTableFile, "w")
                f.write('\t'.join([col for col in param.cols]) + "\n")
                values = param.value.split(",")
                for i in range(0, len(values), 3):
                    s = values[i] + "\t" + values[i+1] + "\t" + values[i+2] + "\n"
                    f.write(s)
                f.close()
                command+=( " -" + param.name + " \"" + tempTableFile + "\"")
            elif isinstance(param, ParameterExtent):
                #'we have to substract/add half cell size, since saga is center based, not corner based
                halfcell = self.getOutputCellsize() / 2
                offset = [halfcell, -halfcell, halfcell, -halfcell]
                values = param.value.split(",")
                for i in range(4):
                    command+=(" -" + self.extentParamNames[i] + " " + str(float(values[i]) + offset[i]));
            elif isinstance(param, (ParameterNumber, ParameterSelection)):
                command+=(" -" + param.name + " " + str(param.value));
            else:
                command+=(" -" + param.name + " \"" + str(param.value) + "\"");

        for out in self.outputs:
            if isinstance(out, OutputRaster):
                filename = out.getCompatibleFileName(self)
                filename = ProcessingUtils.tempFolder() + os.sep + os.path.basename(filename) + ".sgrd"
                command+=(" -" + out.name + " \"" + filename + "\"");
            if isinstance(out, OutputVector):
                filename = out.getCompatibleFileName(self)
                command+=(" -" + out.name + " \"" + filename + "\"");
            if isinstance(out, OutputTable):
                filename = out.getCompatibleFileName(self)
                command+=(" -" + out.name + " \"" + filename + "\"");

        commands.append(command)

        #3:Export resulting raster layers
        for out in self.outputs:
            if isinstance(out, OutputRaster):
                filename = out.getCompatibleFileName(self)
                filename2 = ProcessingUtils.tempFolder() + os.sep + os.path.basename(filename) + ".sgrd"
                formatIndex = 1 if saga208 else 4
                if ProcessingUtils.isWindows() or ProcessingUtils.isMac() or not saga208:
                    commands.append("io_gdal 1 -GRIDS \"" + filename2 + "\" -FORMAT " + str(formatIndex) +" -TYPE 0 -FILE \"" + filename + "\"");
                else:
                    commands.append("libio_gdal 1 -GRIDS \"" + filename2 + "\" -FORMAT 1 -TYPE 0 -FILE \"" + filename + "\"");


        #4 Run SAGA
        commands = self.editCommands(commands)
        SagaUtils.createSagaBatchJobFileFromSagaCommands(commands)
        loglines = []
        loglines.append("SAGA execution commands")
        for line in commands:
            progress.setCommand(line)
            loglines.append(line)
        if ProcessingConfig.getSetting(SagaUtils.SAGA_LOG_COMMANDS):
            ProcessingLog.addToLog(ProcessingLog.LOG_INFO, loglines)
        SagaUtils.executeSaga(progress);
Beispiel #28
0
    def processAlgorithm(self, progress):
        if ProcessingUtils.isWindows():
            path = SagaUtils.sagaPath()
            if path == "":
                raise GeoAlgorithmExecutionException(
                    "SAGA folder is not configured.\nPlease configure it before running SAGA algorithms."
                )
        commands = list()
        self.exportedLayers = {}

        self.preProcessInputs()

        #1: Export rasters to sgrd and vectors to shp
        #   Tables must be in dbf format. We check that.
        if self.resample:
            self.calculateResamplingExtent()
        for param in self.parameters:
            if isinstance(param, ParameterRaster):
                if param.value == None:
                    continue
                value = param.value
                if not value.endswith("sgrd"):
                    commands.append(self.exportRasterLayer(value))
                if self.resample:
                    commands.append(self.resampleRasterLayer(value))
            if isinstance(param, ParameterVector):
                if param.value == None:
                    continue
                layer = QGisLayers.getObjectFromUri(param.value, False)
                if layer:
                    filename = LayerExporter.exportVectorLayer(layer)
                    self.exportedLayers[param.value] = filename
                elif not param.value.endswith("shp"):
                    raise GeoAlgorithmExecutionException(
                        "Unsupported file format")
            if isinstance(param, ParameterTable):
                if param.value == None:
                    continue
                table = QGisLayers.getObjectFromUri(param.value, False)
                if table:
                    filename = LayerExporter.exportTable(table)
                    self.exportedLayers[param.value] = filename
                elif not param.value.endswith("shp"):
                    raise GeoAlgorithmExecutionException(
                        "Unsupported file format")
            if isinstance(param, ParameterMultipleInput):
                if param.value == None:
                    continue
                layers = param.value.split(";")
                if layers == None or len(layers) == 0:
                    continue
                if param.datatype == ParameterMultipleInput.TYPE_RASTER:
                    for layerfile in layers:
                        if not layerfile.endswith("sgrd"):
                            commands.append(self.exportRasterLayer(layerfile))
                        if self.resample:
                            commands.append(
                                self.resampleRasterLayer(layerfile))
                elif param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY:
                    for layerfile in layers:
                        layer = QGisLayers.getObjectFromUri(layerfile, False)
                        if layer:
                            filename = LayerExporter.exportVectorLayer(layer)
                            self.exportedLayers[layerfile] = filename
                        elif (not layerfile.endswith("shp")):
                            raise GeoAlgorithmExecutionException(
                                "Unsupported file format")

        #2: set parameters and outputs
        saga208 = ProcessingConfig.getSetting(SagaUtils.SAGA_208)
        if ProcessingUtils.isWindows() or ProcessingUtils.isMac(
        ) or not saga208:
            command = self.undecoratedGroup + " \"" + self.cmdname + "\""
        else:
            command = "lib" + self.undecoratedGroup + " \"" + self.cmdname + "\""

        if self.hardcodedStrings:
            for s in self.hardcodedStrings:
                command += " " + s

        for param in self.parameters:
            if param.value is None:
                continue
            if isinstance(param,
                          (ParameterRaster, ParameterVector, ParameterTable)):
                value = param.value
                if value in self.exportedLayers.keys():
                    command += (" -" + param.name + " \"" +
                                self.exportedLayers[value] + "\"")
                else:
                    command += (" -" + param.name + " \"" + value + "\"")
            elif isinstance(param, ParameterMultipleInput):
                s = param.value
                for layer in self.exportedLayers.keys():
                    s = s.replace(layer, self.exportedLayers[layer])
                command += (" -" + param.name + " \"" + s + "\"")
            elif isinstance(param, ParameterBoolean):
                if param.value:
                    command += (" -" + param.name)
            elif isinstance(param, ParameterFixedTable):
                tempTableFile = ProcessingUtils.getTempFilename("txt")
                f = open(tempTableFile, "w")
                f.write('\t'.join([col for col in param.cols]) + "\n")
                values = param.value.split(",")
                for i in range(0, len(values), 3):
                    s = values[i] + "\t" + values[i +
                                                  1] + "\t" + values[i +
                                                                     2] + "\n"
                    f.write(s)
                f.close()
                command += (" -" + param.name + " \"" + tempTableFile + "\"")
            elif isinstance(param, ParameterExtent):
                #'we have to substract/add half cell size, since saga is center based, not corner based
                halfcell = self.getOutputCellsize() / 2
                offset = [halfcell, -halfcell, halfcell, -halfcell]
                values = param.value.split(",")
                for i in range(4):
                    command += (" -" + self.extentParamNames[i] + " " +
                                str(float(values[i]) + offset[i]))
            elif isinstance(param, (ParameterNumber, ParameterSelection)):
                command += (" -" + param.name + " " + str(param.value))
            else:
                command += (" -" + param.name + " \"" + str(param.value) +
                            "\"")

        for out in self.outputs:
            if isinstance(out, OutputRaster):
                filename = out.getCompatibleFileName(self)
                filename = ProcessingUtils.tempFolder(
                ) + os.sep + os.path.basename(filename) + ".sgrd"
                command += (" -" + out.name + " \"" + filename + "\"")
            if isinstance(out, OutputVector):
                filename = out.getCompatibleFileName(self)
                command += (" -" + out.name + " \"" + filename + "\"")
            if isinstance(out, OutputTable):
                filename = out.getCompatibleFileName(self)
                command += (" -" + out.name + " \"" + filename + "\"")

        commands.append(command)

        #3:Export resulting raster layers
        for out in self.outputs:
            if isinstance(out, OutputRaster):
                filename = out.getCompatibleFileName(self)
                filename2 = ProcessingUtils.tempFolder(
                ) + os.sep + os.path.basename(filename) + ".sgrd"
                formatIndex = 1 if saga208 else 4
                if ProcessingUtils.isWindows() or ProcessingUtils.isMac(
                ) or not saga208:
                    commands.append("io_gdal 1 -GRIDS \"" + filename2 +
                                    "\" -FORMAT " + str(formatIndex) +
                                    " -TYPE 0 -FILE \"" + filename + "\"")
                else:
                    commands.append("libio_gdal 1 -GRIDS \"" + filename2 +
                                    "\" -FORMAT 1 -TYPE 0 -FILE \"" +
                                    filename + "\"")

        #4 Run SAGA
        commands = self.editCommands(commands)
        SagaUtils.createSagaBatchJobFileFromSagaCommands(commands)
        loglines = []
        loglines.append("SAGA execution commands")
        for line in commands:
            progress.setCommand(line)
            loglines.append(line)
        if ProcessingConfig.getSetting(SagaUtils.SAGA_LOG_COMMANDS):
            ProcessingLog.addToLog(ProcessingLog.LOG_INFO, loglines)
        SagaUtils.executeSaga(progress)