Beispiel #1
0
 def initializeSettings(self):
     '''this is the place where you should add config parameters using the ProcessingConfig class.
     This method is called when a provider is added to the processing framework.
     By default it just adds a setting to activate or deactivate algorithms from the provider'''
     ProcessingConfig.settingIcons[self.getDescription()] = self.getIcon()
     name = "ACTIVATE_" + self.getName().upper().replace(" ", "_")
     ProcessingConfig.addSetting(Setting(self.getDescription(), name, "Activate", self.activate))
Beispiel #2
0
 def testGrass(self):
     '''Test GRASS is installed QGIS-89 (2)'''
     folder = ProcessingConfig.getSetting(GrassUtils.GRASS_FOLDER)
     ProcessingConfig.removeSetting(GrassUtils.GRASS_FOLDER)
     msg = GrassUtils.checkGrassIsInstalled()
     self.assertIsNone(msg)
     ProcessingConfig.setSettingValue(GrassUtils.GRASS_FOLDER, folder)
 def unload(self):
     """Setting should be removed here, so they do not appear anymore
     when the plugin is unloaded.
     """
     AlgorithmProvider.unload(self)
     ProcessingConfig.removeSetting(
         Basis_nl_algorithm_provider.INPUT_FOLDER)
 def initializeSettings(self):
     AlgorithmProvider.initializeSettings(self)
     ProcessingConfig.addSetting(Setting(
         self.getDescription(),
         GdalUtils.GDAL_HELP_PATH,
         self.tr('Location of GDAL docs'),
         GdalUtils.gdalHelpPath()))
Beispiel #5
0
 def load(self):
     ProcessingConfig.settingIcons[self.name()] = self.icon()
     ProcessingConfig.addSetting(Setting(self.name(), 'ACTIVATE_GDAL',
                                         self.tr('Activate'), True))
     ProcessingConfig.readSettings()
     self.refreshAlgorithms()
     return True
 def unload(self):
     """Setting should be removed here, so they do not appear anymore
     when the plugin is unloaded.
     """
     ProcessingConfig.removeSetting('ACTIVATE_EXAMPLE')
     ProcessingConfig.removeSetting(
         ExampleAlgorithmProvider.MY_DUMMY_SETTING)
Beispiel #7
0
    def initialize():
        # Add the basic providers
        Processing.addProvider(QGISAlgorithmProvider())
        Processing.addProvider(ModelerOnlyAlgorithmProvider())
        Processing.addProvider(GdalOgrAlgorithmProvider())
        Processing.addProvider(LidarToolsAlgorithmProvider())
        Processing.addProvider(OTBAlgorithmProvider())
        Processing.addProvider(RAlgorithmProvider())
        Processing.addProvider(SagaAlgorithmProvider())
        Processing.addProvider(GrassAlgorithmProvider())
        Processing.addProvider(Grass7AlgorithmProvider())
        Processing.addProvider(ScriptAlgorithmProvider())
        Processing.addProvider(TauDEMAlgorithmProvider())
        Processing.addProvider(Processing.modeler)
        Processing.modeler.initializeSettings()

        # And initialize
        AlgorithmDecorator.loadClassification()
        ProcessingLog.startLogging()
        ProcessingConfig.initialize()
        ProcessingConfig.readSettings()
        RenderingStyles.loadStyles()
        Processing.loadFromProviders()
        
        # Inform registered listeners that all providers' algorithms have been loaded
        Processing.fireAlgsListHasChanged()
 def unload(self):
     """Setting should be removed here, so they do not appear anymore
     when the plugin is unloaded.
     """
     AlgorithmProvider.unload(self)
     ProcessingConfig.removeSetting(
         DifferentialPrivacyUtils.DIFFERENTIAL_EPSILON)
Beispiel #9
0
    def grassPath():
        if not isWindows() and not isMac():
            return ''

        folder = ProcessingConfig.getSetting(GrassUtils.GRASS_FOLDER) or ''
        if not os.path.exists(folder):
            folder = None
        if folder is None:
            if isWindows():
                if "OSGEO4W_ROOT" in os.environ:
                    testfolder = os.path.join(str(os.environ['OSGEO4W_ROOT']), "apps")
                else:
                    testfolder = str(QgsApplication.prefixPath())
                testfolder = os.path.join(testfolder, 'grass')
                if os.path.isdir(testfolder):
                    for subfolder in os.listdir(testfolder):
                        if subfolder.startswith('grass-6'):
                            folder = os.path.join(testfolder, subfolder)
                            break
            else:
                folder = os.path.join(QgsApplication.prefixPath(), 'grass')
                if not os.path.isdir(folder):
                    folder = '/Applications/GRASS-6.4.app/Contents/MacOS'

        if folder:
            ProcessingConfig.setSettingValue(GrassUtils.GRASS_FOLDER, folder)
        return folder or ''
 def unload(self):
     ProcessingConfig.removeSetting('ACTIVATE_GRASS7')
     if isWindows() or isMac():
         ProcessingConfig.removeSetting(Grass7Utils.GRASS_FOLDER)
     ProcessingConfig.removeSetting(Grass7Utils.GRASS_LOG_COMMANDS)
     ProcessingConfig.removeSetting(Grass7Utils.GRASS_LOG_CONSOLE)
     ProcessingConfig.removeSetting(Grass7Utils.GRASS_HELP_PATH)
Beispiel #11
0
    def writeRaw(self, fileName, hrLayer, studyLayer, areas):
        sepField = ProcessingConfig.getSetting('FIELD_SEPARATOR')
        sepNumber = ProcessingConfig.getSetting('DECIMAL_SEPARATOR')

        with open(fileName, 'w') as f:
            f.write('QGIS Random Home Range summary\n')
            f.write('Frame layer%s%s\n' % (sepField, studyLayer.name()))
            f.write('Home ranges layer%s%s\n' % (sepField, hrLayer.name()))
            f.write('Number of the home ranges%s%s\n' % (sepField, studyLayer.featureCount()))
            f.write('Number of iterations%s%s\n\n' % (sepField, len(self.overlaps) - 1))
            f.write('Note: The first column contains the home range area\n\n')
            for i in range(len(self.overlaps)):
                if i == 0:
                    f.write('Observed data:\n')
                else:
                    f.write('Iteration %s:\n' % i)

                for j in range(len(self.overlaps[i])):
                    text = str(areas[j]) + sepField
                    for k in range(len(self.overlaps[i]) - len(self.overlaps[i][j])):
                        text += sepField

                    for k in range(len(self.overlaps[i][j])):
                        val = self.overlaps[i][j][k]
                        text += str(val).replace('.', sepNumber) + sepField

                    text = text[:len(text) - 1] + '\n'
                    f.write(text)

                f.write('\n')
Beispiel #12
0
 def addToLog(msgtype, msg):
     try:
         # It seems that this fails sometimes depending on the msg
         # added. To avoid it stopping the normal functioning of the
         # algorithm, we catch all errors, assuming that is better
         # to miss some log info that breaking the algorithm.
         if isinstance(msg, list):
             a = '|'.join(m.strip('\n') for m in msg)
             text = a
         else:
             text = msg.replace('\n', '|')
         line = msgtype + '|' + datetime.datetime.now().strftime(
                 ProcessingLog.DATE_FORMAT).decode('utf-8') + '|' \
                 + text + '\n'
         logfile = codecs.open(ProcessingLog.logFilename(), 'a',
                               encoding='utf-8')
         logfile.write(line)
         logfile.close()
         if msgtype == ProcessingLog.LOG_ALGORITHM:
             algname = text[len('Processing.runalg("'):]
             algname = algname[:algname.index('"')]
             if algname not in ProcessingLog.recentAlgs:
                 ProcessingLog.recentAlgs.append(algname)
                 recentAlgsString = ';'.join(ProcessingLog.recentAlgs[-6:])
                 ProcessingConfig.setSettingValue(
                         ProcessingConfig.RECENT_ALGORITHMS,
                         recentAlgsString)
     except:
         pass
 def unload(self):
     """Setting should be removed here, so they do not appear anymore
     when the plugin is unloaded.
     """
     AlgorithmProvider.unload(self)
     ProcessingConfig.removeSetting(
         MultiClipProvider.MY_DUMMY_SETTING)
Beispiel #14
0
 def addToLog(msgtype, msg):
     try:
         # It seems that this fails sometimes depending on the msg
         # added. To avoid it stopping the normal functioning of the
         # algorithm, we catch all errors, assuming that is better
         # to miss some log info than breaking the algorithm.
         if msgtype == ProcessingLog.LOG_ALGORITHM:
             line = msgtype + '|' + datetime.datetime.now().strftime(
                 ProcessingLog.DATE_FORMAT) + '|' \
                 + msg + '\n'
             with codecs.open(ProcessingLog.logFilename(), 'a',
                              encoding='utf-8') as logfile:
                 logfile.write(line)
             algname = msg[len('Processing.runalg("'):]
             algname = algname[:algname.index('"')]
             if algname not in ProcessingLog.recentAlgs:
                 ProcessingLog.recentAlgs.append(algname)
                 recentAlgsString = ';'.join(ProcessingLog.recentAlgs[-6:])
                 ProcessingConfig.setSettingValue(
                     ProcessingConfig.RECENT_ALGORITHMS,
                     recentAlgsString)
         else:
             if isinstance(msg, list):
                 msg = '\n'.join([m for m in msg])
             msgtypes = {ProcessingLog.LOG_ERROR: QgsMessageLog.CRITICAL,
                         ProcessingLog.LOG_INFO: QgsMessageLog.INFO,
                         ProcessingLog.LOG_WARNING: QgsMessageLog.WARNING, }
             QgsMessageLog.logMessage(msg, ProcessingLog.tr("Processing"), msgtypes[msgtype])
     except:
         pass
Beispiel #15
0
        def __init__(self, layer, request):
            self.layer = layer
            self.selection = False
            if ProcessingConfig.getSetting(ProcessingConfig.USE_SELECTED)\
                    and layer.selectedFeatureCount() > 0:
                self.iter = layer.selectedFeaturesIterator(request)
                self.selection = True
            else:
                self.iter = layer.getFeatures(request)

            invalidFeaturesMethod = ProcessingConfig.getSetting(ProcessingConfig.FILTER_INVALID_GEOMETRIES)

            def filterFeature(f, ignoreInvalid):
                geom = f.geometry()
                if geom is None:
                    ProcessingLog.addToLog(ProcessingLog.LOG_INFO,
                                           self.tr('Feature with NULL geometry found.'))
                elif not geom.isGeosValid():
                    ProcessingLog.addToLog(ProcessingLog.LOG_ERROR,
                                           self.tr('GEOS geoprocessing error: One or more input features have invalid geometry.'))
                    if ignoreInvalid:
                        return False
                    else:
                        raise GeoAlgorithmExecutionException(self.tr('Features with invalid geometries found. Please fix these geometries or specify the "Ignore invalid input features" flag'))
                return True

            if invalidFeaturesMethod == self.IGNORE:
                self.iter = filter(lambda x: filterFeature(x, True), self.iter)
            elif invalidFeaturesMethod == self.RAISE_EXCEPTION:
                self.iter = filter(lambda x: filterFeature(x, False), self.iter)
    def initializeSettings(self):
        AlgorithmProvider.initializeSettings(self)

        ProcessingConfig.addSetting(Setting('AniMove',
            self.FIELD_SEPARATOR, 'CSV field separator', ','))
        ProcessingConfig.addSetting(Setting('AniMove',
            self.DECIMAL_SEPARATOR, 'CSV decimal separator', '.'))
    def unload(self):
        """
        Unloads the provider. Any tear-down steps required by the provider
        should be implemented here.
        """
		
        ProcessingConfig.removeSetting('VISIBILITY_ANALYSIS_ACTIVATED')
Beispiel #18
0
def sagaPath():
    folder = ProcessingConfig.getSetting(SAGA_FOLDER)
    if folder is None or folder == '':
        folder = findSagaFolder()
        if folder is not None:
            ProcessingConfig.setSettingValue(SAGA_FOLDER, folder)
    return folder or ''
 def runAlgorithm(self):
     '''
     Execute geo-operation GeoAlgorithm Processing based
     '''
     self.dlg.openChartDialogButton.setEnabled(False)
     algorithm = self.GeoprocessingAlgorithms[self.dlg.getGeoprocessingTypeData()](self.dlg.getOutputType())
     self.dlg.algorithm = algorithm
     algorithm.provider = QGISAlgorithmProvider()
     algorithm.setParameterValue('ORIGIN',self.dlg.getComboboxData('originLayerSelect'))
     algorithm.setParameterValue('TARGET',self.dlg.getComboboxData('targetLayerSelect'))
     algorithm.setParameterValue('FIELDSORIGIN',self.dlg.getSelectedFields('tableViewOriginLayerFields'))
     algorithm.setParameterValue('FIELDSTARGET',self.dlg.getSelectedFields('tableViewTargetLayerFields'))
     algorithm.setParameterValue('EXPRESSIONSORIGIN',self.dlg.getSelectedFieldsNameWithExpression('tableViewOriginLayerFields'))
     algorithm.setParameterValue('EXPRESSIONSTARGET',self.dlg.getSelectedFieldsNameWithExpression('tableViewTargetLayerFields'))
     ProcessingConfig.setSettingValue(ProcessingConfig.USE_FILENAME_AS_LAYER_NAME,True)
     if self.dlg.getOutputType() == 'Shape File':
         outputFile = self.dlg.outputShapeFile.text()
     elif self.dlg.getOutputType() == 'Spatialite':
         outputFile = self.dlg.outputSpatialite.text()
     else:
         outputFile = self.dlg.getPostgisOutputValues()
     algorithm.setOutputValue('OUTPUT',outputFile)
     algorithm.execute(self.dlg)
     self.dlg.reslayer = handleAlgorithmResults(algorithm,self.dlg)
     #QObject.connect(self.dlg.reslayer[0], SIGNAL('layerDeleted()'),self.dlg.clearReslayer)
     ProcessingConfig.setSettingValue(ProcessingConfig.USE_FILENAME_AS_LAYER_NAME,False)
     self.dlg.openChartDialogButton.setEnabled(True)
Beispiel #20
0
def initializeMenus():
    for provider in Processing.providers:
        for alg in provider.algs:
            d = defaultMenuEntries.get(alg.commandLineName(), "")
            setting = Setting("Menus", "MENU_" + alg.commandLineName(), alg.name, d)
            ProcessingConfig.addSetting(setting)

    ProcessingConfig.readSettings()
 def unload(self):
     """
     Setting should be removed here, so they do not appear anymore
     when the plugin is unloaded.
     """
     AlgorithmProvider.unload(self)
     ProcessingConfig.removeSetting(
         GISCloudUtils.GISCloud_character)
 def unload(self):
     AlgorithmProvider.unload(self)
     if isWindows() or isMac():
         ProcessingConfig.removeSetting(GrassUtils.GRASS_FOLDER)
         ProcessingConfig.removeSetting(GrassUtils.GRASS_WIN_SHELL)
     ProcessingConfig.removeSetting(GrassUtils.GRASS_LOG_COMMANDS)
     ProcessingConfig.removeSetting(GrassUtils.GRASS_LOG_CONSOLE)
     ProcessingConfig.removeSetting(GrassUtils.GRASS_HELP_PATH)
 def unload(self):
     """Setting should be removed here, so they do not appear anymore
     when the plugin is unloaded.
     """
     AlgorithmProvider.unload(self)
     ProcessingConfig.removeSetting(
         ScipyPointClusteringUtils.POINT_LIMIT
     )
Beispiel #24
0
 def setUp(self):
     ProcessingConfig.setSettingValue(ProcessingConfig.USE_THREADS, self.threaded)
     print
     print bcolors.INFO, self.msg, bcolors.ENDC,
     print "Parameters: ", self.alg.parameters,
     print "Outputs: ", [out for out in self.alg.outputs if not out.hidden],
     self.args = list(self.gen_test_parameters(self.alg, True))
     print ' => ', self.args, bcolors.WARNING,
 def initializeSettings(self):
     AlgorithmProvider.initializeSettings(self)
     ProcessingConfig.addSetting(Setting(self.getDescription(),
             LAStoolsUtils.LASTOOLS_FOLDER,
             'LAStools folder', LAStoolsUtils.LAStoolsPath()))
     ProcessingConfig.addSetting(Setting(self.getDescription(),
             FusionUtils.FUSION_FOLDER,
             'Fusion folder', FusionUtils.FusionPath()))
    def unload(self):
        """Setting should be removed here, so they do not appear anymore
        when the plugin is unloaded.

        """
        AlgorithmProvider.unload(self)
        ProcessingConfig.removeSetting(
            PolygonsParallelToLineProvider.MY_SETTING)
Beispiel #27
0
 def unload(self):
     ProcessingConfig.removeSetting('ACTIVATE_R')
     ProcessingConfig.removeSetting(RUtils.RSCRIPTS_FOLDER)
     if isWindows():
         ProcessingConfig.removeSetting(RUtils.R_FOLDER)
         ProcessingConfig.removeSetting(RUtils.R_LIBS_USER)
         ProcessingConfig.removeSetting(RUtils.R_USE64)
     ProviderActions.deregisterProviderActions(self)
     ProviderContextMenuActions.deregisterProviderContextMenuActions(self.contextMenuActions)
Beispiel #28
0
 def unload(self):
     '''Setting should be removed here, so they do not appear anymore
     when the plugin is unloaded'''
     AlgorithmProvider.unload(self)
     ProcessingConfig.removeSetting(qsdm_settings.JAVA_EXEC)
     ProcessingConfig.removeSetting(qsdm_settings.MAXENT)
     ProcessingConfig.removeSetting(qsdm_settings.MEM)        
     ProcessingConfig.removeSetting(qsdm_settings.WORK_DIR)
     ProcessingConfig.removeSetting(qsdm_settings.TEMP)
Beispiel #29
0
def handleAlgorithmResults(alg, context, feedback=None, showResults=True):
    wrongLayers = []
    if feedback is None:
        feedback = QgsProcessingFeedback()
    feedback.setProgressText(QCoreApplication.translate('Postprocessing', 'Loading resulting layers'))
    i = 0

    for l, details in context.layersToLoadOnCompletion().items():
        if feedback.isCanceled():
            return False

        if len(context.layersToLoadOnCompletion()) > 2:
            # only show progress feedback if we're loading a bunch of layers
            feedback.setProgress(100 * i / float(len(context.layersToLoadOnCompletion())))

        try:
            layer = QgsProcessingUtils.mapLayerFromString(l, context, typeHint=details.layerTypeHint)
            if layer is not None:
                set_layer_name(layer, details)

                style = None
                if details.outputName:
                    style = RenderingStyles.getStyle(alg.id(), details.outputName)
                if style is None:
                    if layer.type() == QgsMapLayer.RasterLayer:
                        style = ProcessingConfig.getSetting(ProcessingConfig.RASTER_STYLE)
                    else:
                        if layer.geometryType() == QgsWkbTypes.PointGeometry:
                            style = ProcessingConfig.getSetting(ProcessingConfig.VECTOR_POINT_STYLE)
                        elif layer.geometryType() == QgsWkbTypes.LineGeometry:
                            style = ProcessingConfig.getSetting(ProcessingConfig.VECTOR_LINE_STYLE)
                        else:
                            style = ProcessingConfig.getSetting(ProcessingConfig.VECTOR_POLYGON_STYLE)
                if style:
                    layer.loadNamedStyle(style)

                details.project.addMapLayer(context.temporaryLayerStore().takeMapLayer(layer))

                if details.postProcessor():
                    details.postProcessor().postProcessLayer(layer, context, feedback)

            else:
                wrongLayers.append(str(l))
        except Exception:
            QgsMessageLog.logMessage(QCoreApplication.translate('Postprocessing', "Error loading result layer:") + "\n" + traceback.format_exc(), 'Processing', Qgis.Critical)
            wrongLayers.append(str(l))
        i += 1

    feedback.setProgress(100)

    if wrongLayers:
        msg = QCoreApplication.translate('Postprocessing', "The following layers were not correctly generated.")
        msg += "<ul>" + "".join(["<li>%s</li>" % lay for lay in wrongLayers]) + "</ul>"
        msg += QCoreApplication.translate('Postprocessing', "You can check the 'Log Messages Panel' in QGIS main window to find more information about the execution of the algorithm.")
        feedback.reportError(msg)

    return len(wrongLayers) == 0
Beispiel #30
0
    def unload(self):
        """Do here anything that you want to be done when the provider
        is removed from the list of available ones.

        This method is called when you remove the provider from
        Processing. Removal of config setting should be done here.
        """
        name = 'ACTIVATE_' + self.getName().upper().replace(' ', '_')
        ProcessingConfig.removeSetting(name)