Example #1
0
 def validateOtbFolder(self, v):
     if not self.isActive():
         return
     if not v or not os.path.exists(v):
         self.setActive(False)
         raise ValueError(self.tr("'{}' does not exist. OTB provider will be disabled".format(v)))
     path = self.normalize_path(v)
     app_launcher_path = OtbUtils.getExecutableInPath(path, 'otbApplicationLauncherCommandLine')
     if not os.path.exists(app_launcher_path):
         self.setActive(False)
         raise ValueError(self.tr("Cannot find '{}'. OTB will be disabled".format(app_launcher_path)))
 def validateOtbFolder(self, v):
     if not self.isActive():
         return
     if not v or not os.path.exists(v):
         self.setActive(False)
         raise ValueError(self.tr("'{}' does not exist. OTB provider will be disabled".format(v)))
     path = self.normalize_path(v)
     app_launcher_path = OtbUtils.getExecutableInPath(path, 'otbApplicationLauncherCommandLine')
     if not os.path.exists(app_launcher_path):
         self.setActive(False)
         raise ValueError(self.tr("Cannot find '{}'. OTB will be disabled".format(app_launcher_path)))
    def validateAppFolders(self, v):
        if not self.isActive():
            return
        if not v:
            self.setActive(False)
            raise ValueError(self.tr('Cannot activate OTB provider'))

        folder = OtbUtils.otbFolder()
        otb_app_dirs = self.appDirs(v)
        if len(otb_app_dirs) < 1:
            self.setActive(False)
            raise ValueError(
                self.tr("'{}' does not exist. OTB provider will be disabled".
                        format(v)))

        #isValid is True if there is atleast one valid otb application is given path
        isValid = False
        descr_folder = self.descrFolder(folder)
        for app_dir in otb_app_dirs:
            if not os.path.exists(app_dir):
                continue
            for otb_app in os.listdir(app_dir):
                if not otb_app.startswith('otbapp_') or \
                    'TestApplication' in otb_app or \
                        'ApplicationExample' in otb_app:
                    continue
                app_name = os.path.basename(otb_app).split('.')[0][7:]
                dfile = os.path.join(descr_folder, app_name + '.txt')
                isValid = True
                if not os.path.exists(dfile):
                    cmdlist = [
                        OtbUtils.getExecutableInPath(folder,
                                                     'otbQgisDescriptor'),
                        app_name, app_dir, descr_folder + '/'
                    ]
                    commands = ' '.join(cmdlist)
                    QgsMessageLog.logMessage(self.tr(commands),
                                             self.tr('Processing'),
                                             Qgis.Critical)
                    OtbUtils.executeOtb(commands, feedback=None)

        if isValid:
            # if check needed for testsing
            if utils.iface is not None:
                utils.iface.messageBar().pushInfo(
                    "OTB",
                    "OTB provider is activated from '{}'.".format(folder))
        else:
            self.setActive(False)
            raise ValueError(
                self.tr(
                    "No OTB algorithms found in '{}'. OTB will be disabled".
                    format(','.join(otb_app_dirs))))
    def validateAppFolders(self, v):
        if not self.isActive():
            return
        if not v:
            self.setActive(False)
            raise ValueError(self.tr('Cannot activate OTB provider'))

        folder = OtbUtils.otbFolder()
        otb_app_dirs = self.appDirs(v)
        if len(otb_app_dirs) < 1:
            self.setActive(False)
            raise ValueError(self.tr("'{}' does not exist. OTB provider will be disabled".format(v)))

        #isValid is True if there is atleast one valid otb application is given path
        isValid = False
        descr_folder = self.descrFolder(folder)
        for app_dir in otb_app_dirs:
            if not os.path.exists(app_dir):
                continue
            for otb_app in os.listdir(app_dir):
                if not otb_app.startswith('otbapp_') or \
                    'TestApplication' in otb_app or \
                        'ApplicationExample' in otb_app:
                    continue
                app_name = os.path.basename(otb_app).split('.')[0][7:]
                dfile = os.path.join(descr_folder, app_name + '.txt')
                isValid = True
                if not os.path.exists(dfile):
                    cmdlist = [OtbUtils.getExecutableInPath(folder, 'otbQgisDescriptor'),
                               app_name, app_dir, descr_folder + '/']
                    commands = ' '.join(cmdlist)
                    QgsMessageLog.logMessage(self.tr(commands), self.tr('Processing'), Qgis.Critical)
                    OtbUtils.executeOtb(commands, feedback=None)

        if isValid:
            # if check needed for testsing
            if utils.iface is not None:
                utils.iface.messageBar().pushInfo("OTB", "OTB provider is activated from '{}'.".format(folder))
        else:
            self.setActive(False)
            raise ValueError(self.tr("No OTB algorithms found in '{}'. OTB will be disabled".format(','.join(otb_app_dirs))))
Example #5
0
    def processAlgorithm(self, parameters, context, feedback):
        app_launcher_path = OtbUtils.getExecutableInPath(OtbUtils.otbFolder(), 'otbApplicationLauncherCommandLine')
        command = '"{}" {} {}'.format(app_launcher_path, self.name(), OtbUtils.appFolder())
        outputPixelType = None
        for k, v in parameters.items():
            # if value is None for a parameter we don't have any businees with this key
            if not v or v is None:
                continue
            # for 'outputpixeltype' parameter we find the pixeltype string from self.pixelTypes
            if k == 'outputpixeltype':
                pixel_type = self.pixelTypes[int(parameters['outputpixeltype'])]
                outputPixelType = None if pixel_type == 'float' else pixel_type
                continue

            param = self.parameterDefinition(k)
            if param.isDestination():
                continue
            if isinstance(param, QgsProcessingParameterEnum):
                value = self.parameterAsEnum(parameters, param.name(), context)
            elif isinstance(param, QgsProcessingParameterBoolean):
                value = self.parameterAsBoolean(parameters, param.name(), context)
            elif isinstance(param, QgsProcessingParameterCrs):
                crsValue = self.parameterAsCrs(parameters, param.name(), context)
                authid = crsValue.authid()
                if authid.startswith('EPSG:'):
                    value = authid.split('EPSG:')[1]
                else:
                    raise QgsProcessingException(
                        self.tr("Incorrect value for parameter '{}'. No EPSG code found in '{}'".format(
                            param.name(),
                            authid)))
            elif isinstance(param, QgsProcessingParameterFile):
                value = self.parameterAsFile(parameters, param.name(), context)
            elif isinstance(param, QgsProcessingParameterMultipleLayers):
                layers = self.parameterAsLayerList(parameters, param.name(), context)
                if layers is None or len(layers) == 0:
                    continue
                value = ' '.join(['"{}"'.format(self.getLayerSource(param.name(), layer)) for layer in layers])
            elif isinstance(param, QgsProcessingParameterNumber):
                if param.dataType() == QgsProcessingParameterNumber.Integer:
                    value = self.parameterAsInt(parameters, param.name(), context)
                else:
                    value = self.parameterAsDouble(parameters, param.name(), context)
            elif isinstance(param, (QgsProcessingParameterRasterLayer, QgsProcessingParameterVectorLayer)):
                value = '"{}"'.format(self.getLayerSource(param.name(), self.parameterAsLayer(parameters, param.name(), context)))
            elif isinstance(param, QgsProcessingParameterString):
                value = '"{}"'.format(self.parameterAsString(parameters, param.name(), context))
            else:
                # Use whatever is given
                value = '"{}"'.format(parameters[param.name()])

            # Check if value is set in above if elif ladder and update command string
            if value and value is not None:
                command += ' -{} {}'.format(k, value)

        output_files = {}

        for out in self.destinationParameterDefinitions():
            filePath = self.parameterAsOutputLayer(parameters, out.name(), context)
            if filePath:
                output_files[out.name()] = filePath
                if outputPixelType is not None:
                    command += ' -{} "{}" "{}"'.format(out.name(), filePath, outputPixelType)
                else:
                    command += ' -{} "{}"'.format(out.name(), filePath)

        OtbUtils.executeOtb(command, feedback)

        result = {}
        for o in self.outputDefinitions():
            if o.name() in output_files:
                result[o.name()] = output_files[o.name()]
        return result
Example #6
0
    def processAlgorithm(self, parameters, context, feedback):
        app_launcher_path = OtbUtils.getExecutableInPath(OtbUtils.otbFolder(), 'otbApplicationLauncherCommandLine')
        command = '"{}" {} {}'.format(app_launcher_path, self.name(), OtbUtils.appFolder())
        outputPixelType = None
        for k, v in parameters.items():
            # if value is None for a parameter we don't have any businees with this key
            if not v or v is None:
                continue
            # for 'outputpixeltype' parameter we find the pixeltype string from self.pixelTypes
            if k == 'outputpixeltype':
                pixel_type = self.pixelTypes[int(parameters['outputpixeltype'])]
                outputPixelType = None if pixel_type == 'float' else pixel_type
                continue

            param = self.parameterDefinition(k)
            if param.isDestination():
                continue
            if isinstance(param, QgsProcessingParameterEnum):
                value = self.parameterAsEnum(parameters, param.name(), context)
            elif isinstance(param, QgsProcessingParameterBoolean):
                value = self.parameterAsBoolean(parameters, param.name(), context)
            elif isinstance(param, QgsProcessingParameterCrs):
                crsValue = self.parameterAsCrs(parameters, param.name(), context)
                authid = crsValue.authid()
                if authid.startswith('EPSG:'):
                    value = authid.split('EPSG:')[1]
                else:
                    raise QgsProcessingException(
                        self.tr("Incorrect value for parameter '{}'. No EPSG code found in '{}'".format(
                            param.name(),
                            authid)))
            elif isinstance(param, QgsProcessingParameterFile):
                value = self.parameterAsFile(parameters, param.name(), context)
            elif isinstance(param, QgsProcessingParameterMultipleLayers):
                layers = self.parameterAsLayerList(parameters, param.name(), context)
                if layers is None or len(layers) == 0:
                    continue
                value = ' '.join(['"{}"'.format(self.getLayerSource(param.name(), layer)) for layer in layers])
            elif isinstance(param, QgsProcessingParameterNumber):
                if param.dataType() == QgsProcessingParameterNumber.Integer:
                    value = self.parameterAsInt(parameters, param.name(), context)
                else:
                    value = self.parameterAsDouble(parameters, param.name(), context)
            elif isinstance(param, (QgsProcessingParameterRasterLayer, QgsProcessingParameterVectorLayer)):
                value = '"{}"'.format(self.getLayerSource(param.name(), self.parameterAsLayer(parameters, param.name(), context)))
            elif isinstance(param, QgsProcessingParameterString):
                value = '"{}"'.format(self.parameterAsString(parameters, param.name(), context))
            else:
                # Use whatever is given
                value = '"{}"'.format(parameters[param.name()])

            # Check if value is set in above if elif ladder and update command string
            if value and value is not None:
                command += ' -{} {}'.format(k, value)

        output_files = {}

        for out in self.destinationParameterDefinitions():
            filePath = self.parameterAsOutputLayer(parameters, out.name(), context)
            if filePath:
                output_files[out.name()] = filePath
                if outputPixelType is not None:
                    command += ' -{} "{}" "{}"'.format(out.name(), filePath, outputPixelType)
                else:
                    command += ' -{} "{}"'.format(out.name(), filePath)

        OtbUtils.executeOtb(command, feedback)

        result = {}
        for o in self.outputDefinitions():
            if o.name() in output_files:
                result[o.name()] = output_files[o.name()]
        return result