示例#1
0
文件: menus.py 项目: ndavid/QGIS
def _executeAlgorithm(alg):
    ok, message = alg.canExecute()
    if not ok:
        dlg = MessageDialog()
        dlg.setTitle(Processing.tr('Missing dependency'))
        dlg.setMessage(
            Processing.tr('<h3>Missing dependency. This algorithm cannot '
                          'be run :-( </h3>\n{0}').format(message))
        dlg.exec_()
        return

    if (alg.countVisibleParameters()) > 0:
        dlg = alg.createCustomParametersWidget(None)
        if not dlg:
            dlg = AlgorithmDialog(alg)
        canvas = iface.mapCanvas()
        prevMapTool = canvas.mapTool()
        dlg.show()
        dlg.exec_()
        if canvas.mapTool() != prevMapTool:
            try:
                canvas.mapTool().reset()
            except:
                pass
            canvas.setMapTool(prevMapTool)
    else:
        feedback = MessageBarProgress()
        context = dataobjects.createContext(feedback)
        parameters = {}
        ret, results = execute(alg, parameters, context, feedback)
        handleAlgorithmResults(alg, context, feedback)
        feedback.close()
示例#2
0
 def setUpClass(cls):
     start_app()
     from processing.core.Processing import Processing
     Processing.initialize()
     cls.cleanup_paths = []
     cls.in_place_layers = {}
     cls.vector_layer_params = {}
示例#3
0
    def initGui(self):
        # Create action that will start plugin configuration
        self.action = QAction(
            QIcon(":/resources/icon"),
            u"Blurring", self.iface.mainWindow())
        # connect the action to the run method
        self.action.triggered.connect(self.run)

        # Add toolbar button and menu item
        self.iface.addToolBarIcon(self.action)
        self.iface.addPluginToVectorMenu(u"&Blurring", self.action)
        
        #Variables
        self.mapLayerRegistry = QgsMapLayerRegistry.instance()
        
        #Height and widht
        self.minWidth = 425
        self.maxWidth = 786
        self.height = 357
        
        #Connectors
        QObject.connect(self.dlg.checkBox_envelope, SIGNAL("clicked()"), self.enableEnvelope)
        QObject.connect(self.dlg.pushButton_help, SIGNAL("clicked()"), self.displayHelp)
        QObject.connect(self.dlg.pushButton_browseFolder, SIGNAL('clicked()'), self.selectFile)
        QObject.connect(self.dlg.pushButton_ok, SIGNAL("clicked()"), self.compute)
        QObject.connect(self.dlg.pushButton_cancel, SIGNAL("clicked()"), self.cancel)
        QObject.connect(self.dlg.pushButton_advanced, SIGNAL("clicked()"), self.advanced)
        
        QObject.connect(QgsMapLayerRegistry.instance(), SIGNAL("layerRemoved(QString)"), self.layerDeleted)
        QObject.connect(QgsMapLayerRegistry.instance(), SIGNAL("layerWasAdded(QgsMapLayer*)"), self.layerAdded)
        
        #Add the plugin to processing
        Processing.addProvider(self.provider, True)
    def setUpClass(cls):
        start_app()
        from processing.core.Processing import Processing
        Processing.initialize()
        cls.cleanup_paths = []

        assert Grass7Utils.installedVersion()
示例#5
0
    def unload(self):
        self.toolbox.setVisible(False)
        self.iface.removeDockWidget(self.toolbox)
        self.iface.attributesToolBar().removeAction(self.toolboxAction)

        self.resultsDock.setVisible(False)
        self.iface.removeDockWidget(self.resultsDock)

        self.toolbox.deleteLater()
        self.menu.deleteLater()

        # delete temporary output files
        folder = QgsProcessingUtils.tempFolder()
        if QDir(folder).exists():
            shutil.rmtree(folder, True)

        # also delete temporary help files
        folder = tempHelpFolder()
        if QDir(folder).exists():
            shutil.rmtree(folder, True)

        self.iface.unregisterMainWindowAction(self.toolboxAction)
        self.iface.unregisterMainWindowAction(self.modelerAction)
        self.iface.unregisterMainWindowAction(self.historyAction)
        self.iface.unregisterMainWindowAction(self.resultsAction)

        self.iface.unregisterOptionsWidgetFactory(self.options_factory)
        self.iface.deregisterLocatorFilter(self.locator_filter)
        self.iface.unregisterCustomDropHandler(self.drop_handler)
        QgsApplication.dataItemProviderRegistry().removeProvider(self.item_provider)

        removeMenus()
        Processing.deinitialize()
示例#6
0
 def openModeler(self):
     dlg = ModelerDialog()
     dlg.show()
     dlg.exec_()
     if dlg.update:
         Processing.updateAlgsList()
         self.toolbox.updateProvider('model')
示例#7
0
    def initGui(self):
        icon = QtGui.QIcon(os.path.dirname(__file__) + "/images/geoserver.png")
        self.explorerAction = QtGui.QAction(icon, "GeoServer Explorer", self.iface.mainWindow())
        self.explorerAction.triggered.connect(self.openExplorer)
        self.iface.addPluginToWebMenu(u"GeoServer", self.explorerAction)

        settings = QtCore.QSettings()
        self.explorer = GeoServerExplorer()
        self.iface.addDockWidget(QtCore.Qt.RightDockWidgetArea, self.explorer)
        if not settings.value("/GeoServer/Settings/General/ExplorerVisible", False, bool):
            self.explorer.hide()
        self.explorer.visibilityChanged.connect(self._explorerVisibilityChanged)


        icon = QtGui.QIcon(os.path.dirname(__file__) + "/images/config.png")
        self.configAction = QtGui.QAction(icon, "GeoServer Explorer settings", self.iface.mainWindow())
        self.configAction.triggered.connect(self.openSettings)
        self.iface.addPluginToWebMenu(u"GeoServer", self.configAction)

        icon = QtGui.QIcon(os.path.dirname(__file__) + "/images/help.png")
        self.helpAction = QtGui.QAction(icon, "GeoServer Explorer help", self.iface.mainWindow())
        self.helpAction.triggered.connect(self.showHelp)
        self.iface.addPluginToWebMenu(u"GeoServer", self.helpAction)

        Processing.addProvider(self.provider)

        layerwatcher.connectLayerWasAdded(self.explorer)
示例#8
0
文件: menus.py 项目: cayetanobv/QGIS
def _executeAlgorithm(alg):
    message = alg.checkBeforeOpeningParametersDialog()
    if message:
        dlg = MessageDialog()
        dlg.setTitle(Processing.tr('Missing dependency'))
        dlg.setMessage(
            Processing.tr('<h3>Missing dependency. This algorithm cannot '
                          'be run :-( </h3>\n{0}').format(message))
        dlg.exec_()
        return
    alg = alg.getCopy()
    if (alg.getVisibleParametersCount() + alg.getVisibleOutputsCount()) > 0:
        dlg = alg.getCustomParametersDialog()
        if not dlg:
            dlg = AlgorithmDialog(alg)
        canvas = iface.mapCanvas()
        prevMapTool = canvas.mapTool()
        dlg.show()
        dlg.exec_()
        if canvas.mapTool() != prevMapTool:
            try:
                canvas.mapTool().reset()
            except:
                pass
            canvas.setMapTool(prevMapTool)
    else:
        feedback = MessageBarProgress()
        execute(alg, feedback)
        handleAlgorithmResults(alg, feedback)
        feedback.close()
示例#9
0
    def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface

        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value("locale/userLocale")[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'QuickOSM_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)

            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)

        #Add to processing
        self.provider = QuickOSMAlgorithmProvider()
        Processing.addProvider(self.provider, True)
示例#10
0
    def unload(self):
        self.toolbox.setVisible(False)
        self.iface.removeDockWidget(self.toolbox)

        self.resultsDock.setVisible(False)
        self.iface.removeDockWidget(self.resultsDock)

        self.menu.deleteLater()

        # delete temporary output files
        folder = tempFolder()
        if QDir(folder).exists():
            shutil.rmtree(folder, True)

        # also delete temporary help files
        folder = tempHelpFolder()
        if QDir(folder).exists():
            shutil.rmtree(folder, True)

        self.iface.unregisterMainWindowAction(self.toolboxAction)
        self.iface.unregisterMainWindowAction(self.modelerAction)
        self.iface.unregisterMainWindowAction(self.historyAction)
        self.iface.unregisterMainWindowAction(self.resultsAction)

        self.iface.unregisterOptionsWidgetFactory(self.options_factory)
        self.iface.deregisterLocatorFilter(self.locator_filter)

        removeMenus()
        Processing.deinitialize()
示例#11
0
    def __init__(self, iface):

        self.iface = iface
        self.plugin_dir = dirname(__file__)
        # initialize locale
        locale = QSettings().value("locale/userLocale")[0:2]
        locale_path = join(
            self.plugin_dir,
            'i18n',
            'GeoHealth_{}.qm'.format(locale))

        if exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)

            if qVersion() > '4.3.3':
                # noinspection PyCallByClass,PyTypeChecker,PyArgumentList
                QCoreApplication.installTranslator(self.translator)

        self.plugin_menu = None
        self.geohealth_menu = None
        self.main_action = None
        self.xy_action = None
        self.blur_action = None
        self.incidence_action = None
        self.density_action = None
        self.histogram_action = None

        # Add to processing
        self.provider = Provider()
        Processing.addProvider(self.provider, True)
示例#12
0
    def initGui(self):
 
        # Create action that will start plugin configuration
        self.action = QAction(QIcon(":/plugins/wps/images/wps-add.png"),
                              "WPS-Client", self.iface.mainWindow())
        QObject.connect(self.action, SIGNAL("triggered()"), self.run)

        self.actionAbout = QAction("About", self.iface.mainWindow())
        QObject.connect(self.actionAbout, SIGNAL("triggered()"), self.doAbout)

        # Add toolbar button and menu item
        self.iface.addToolBarIcon(self.action)
     
        if hasattr(self.iface,  "addPluginToWebMenu"):
            self.iface.addPluginToWebMenu("WPS-Client", self.action)
            self.iface.addPluginToWebMenu("WPS-Client", self.actionAbout)
        else:
            self.iface.addPluginToMenu("WPS", self.action)
            self.iface.addPluginToWebMenu("WPS", self.action)

        self.myDockWidget = QgsWpsDockWidget(self.iface)
        self.myDockWidget.setWindowTitle('WPS')
        self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.myDockWidget)
        self.myDockWidget.show()

        if PROCESSING_SUPPORT:
            self.provider = WpsAlgorithmProvider(self.myDockWidget)
        else:
            self.provider = None

        if self.provider:
            try:
                Processing.addProvider(self.provider, True) #Force tree update
            except TypeError:
                Processing.addProvider(self.provider)
示例#13
0
 def initGui(self):
     """Create the menu entries and toolbar icons inside the QGIS GUI."""
     
     icon_path = ':/plugins/PostTelemac/icons/posttelemac.png'
     self.add_action(
         icon_path,
         text=self.tr(u'PostTelemac'),
         callback=self.run,
         parent=self.iface.mainWindow())
     self.add_action(
         icon_path,
         text=self.tr(u'PostTelemac Help'),
         add_to_toolbar=False,
         callback=self.showHelp,
         parent=self.iface.mainWindow())
     self.add_action(
         icon_path,
         text=self.tr(u'PostTelemac About'),
         add_to_toolbar=False,
         callback=self.showAbout,
         parent=self.iface.mainWindow())
     
         
     #Processing thing
     if DOPROCESSING : Processing.addProvider(self.provider)
示例#14
0
 def openCommander(self):
     if self.commander is None:
         self.commander = CommanderWindow(interface.iface.mainWindow(),
                 interface.iface.mapCanvas())
         Processing.addAlgListListener(self.commander)
     self.commander.prepareGui()
     self.commander.show()
def apply():
    try:
        from processing.core.Processing import Processing

        Processing.activateProvider("ntv2_transformations")
    except:
        pass
示例#16
0
    def initGui(self):
        mapToolIcon = QIcon(os.path.join(os.path.dirname(__file__), "w3w.png"))
        self.toolAction = QAction(mapToolIcon, "what3words map tool",
                                     self.iface.mainWindow())
        self.toolAction.triggered.connect(self.setTool)
        self.toolAction.setCheckable(True)
        self.iface.addToolBarIcon(self.toolAction)
        self.iface.addPluginToMenu("what3words", self.toolAction)

        zoomToIcon = QIcon(':/images/themes/default/mActionZoomIn.svg')
        self.zoomToAction = QAction(zoomToIcon, "Zoom to 3 word address",
                                     self.iface.mainWindow())
        self.zoomToAction.triggered.connect(self.zoomTo)
        self.iface.addPluginToMenu("what3words", self.zoomToAction)

        self.apikeyAction = QAction("Set API key",
                                     self.iface.mainWindow())
        self.apikeyAction.triggered.connect(askForApiKey)
        self.iface.addPluginToMenu("what3words", self.apikeyAction)

        self.iface.mapCanvas().mapToolSet.connect(self.unsetTool)

        self.zoomToDialog = W3WCoordInputDialog(self.iface.mapCanvas(), self.iface.mainWindow())
        self.iface.addDockWidget(Qt.TopDockWidgetArea, self.zoomToDialog)
        self.zoomToDialog.hide()

        if processingOk:
            Processing.addProvider(self.provider)
示例#17
0
    def initGui(self):
        Processing.initialize()

        self.commander = None
        self.toolbox = ProcessingToolbox()
        self.iface.addDockWidget(Qt.RightDockWidgetArea, self.toolbox)
        self.toolbox.hide()
        Processing.addAlgListListener(self.toolbox)

        self.menu = QMenu(self.iface.mainWindow().menuBar())
        self.menu.setObjectName('processing')
        self.menu.setTitle(self.tr('Pro&cessing'))

        self.toolboxAction = self.toolbox.toggleViewAction()
        self.toolboxAction.setObjectName('toolboxAction')
        self.toolboxAction.setIcon(
            QIcon(os.path.join(cmd_folder, 'images', 'alg.png')))
        self.toolboxAction.setText(self.tr('&Toolbox'))
        self.menu.addAction(self.toolboxAction)

        self.modelerAction = QAction(
            QIcon(os.path.join(cmd_folder, 'images', 'model.png')),
            self.tr('Graphical &Modeler...'), self.iface.mainWindow())
        self.modelerAction.setObjectName('modelerAction')
        self.modelerAction.triggered.connect(self.openModeler)
        self.menu.addAction(self.modelerAction)

        self.historyAction = QAction(
            QIcon(os.path.join(cmd_folder, 'images', 'history.gif')),
            self.tr('&History and Log...'), self.iface.mainWindow())
        self.historyAction.setObjectName('historyAction')
        self.historyAction.triggered.connect(self.openHistory)
        self.menu.addAction(self.historyAction)

        self.configAction = QAction(
            QIcon(os.path.join(cmd_folder, 'images', 'config.png')),
            self.tr('&Options...'), self.iface.mainWindow())
        self.configAction.setObjectName('configAction')
        self.configAction.triggered.connect(self.openConfig)
        self.menu.addAction(self.configAction)

        self.resultsAction = QAction(
            QIcon(os.path.join(cmd_folder, 'images', 'results.png')),
            self.tr('&Results Viewer...'), self.iface.mainWindow())
        self.resultsAction.setObjectName('resultsAction')
        self.resultsAction.triggered.connect(self.openResults)
        self.menu.addAction(self.resultsAction)

        menuBar = self.iface.mainWindow().menuBar()
        menuBar.insertMenu(
            self.iface.firstRightStandardMenu().menuAction(), self.menu)

        self.commanderAction = QAction(
            QIcon(os.path.join(cmd_folder, 'images', 'commander.png')),
            self.tr('&Commander'), self.iface.mainWindow())
        self.commanderAction.setObjectName('commanderAction')
        self.commanderAction.triggered.connect(self.openCommander)
        self.menu.addAction(self.commanderAction)
        self.iface.registerMainWindowAction(self.commanderAction,
            self.tr('Ctrl+Alt+M'))
示例#18
0
文件: general.py 项目: dmarteau/QGIS
def run(algOrName, parameters, onFinish=None, feedback=None, context=None, is_child_algorithm=False):
    """
    Executes given algorithm and returns its outputs as dictionary object.

    :param algOrName: Either an instance of an algorithm, or an algorithm's ID
    :param parameters: Algorithm parameters dictionary
    :param onFinish: optional function to run after the algorithm has completed
    :param feedback: Processing feedback object
    :param context: Processing context object
    :param is_child_algorithm: Set to True if this algorithm is being run as part of a larger algorithm,
    i.e. it is a sub-part of an algorithm which calls other Processing algorithms.

    :returns algorithm results as a dictionary, or None if execution failed
    :rtype: Union[dict, None]
    """
    if onFinish or not is_child_algorithm:
        return Processing.runAlgorithm(algOrName, parameters, onFinish, feedback, context)
    else:
        # for child algorithms, we disable to default post-processing step where layer ownership
        # is transferred from the context to the caller. In this case, we NEED the ownership to remain
        # with the context, so that further steps in the algorithm have guaranteed access to the layer.
        def post_process(_alg, _context, _feedback):
            return

        return Processing.runAlgorithm(algOrName, parameters, onFinish=post_process, feedback=feedback, context=context)
示例#19
0
 def unload(self):
     pem.removePkiTempFiles(self.explorer.catalogs())
     self.explorer.deleteLater()
     self.iface.removePluginWebMenu(u"GeoServer", self.explorerAction)
     self.iface.removePluginWebMenu(u"GeoServer", self.configAction)
     self.iface.removePluginWebMenu(u"GeoServer", self.helpAction)
     Processing.removeProvider(self.provider)
     layerwatcher.disconnectLayerWasAdded()
示例#20
0
 def initGui(self):
     Processing.addProvider(self.processing_provider, updateList=True)
     self.action = QAction(QIcon(':plugins/qgisconefor/assets/icon.png'),
                           self._plugin_name, self.iface.mainWindow())
     QObject.connect(self.action, SIGNAL('triggered()'), self.run)
     self.iface.addPluginToVectorMenu('&%s' % self._plugin_name,
                                      self.action)
     self.iface.addVectorToolBarIcon(self.action)
示例#21
0
 def unload(self):
     self.iface.removePluginWebMenu(u'&QuickOSM', self.mainWindowAction)
     self.iface.removePluginWebMenu(u'&QuickOSM', self.myQueriesAction)
     self.iface.removePluginWebMenu(u'&QuickOSM', self.queryAction)
     self.iface.removePluginWebMenu(u'&QuickOSM', self.quickQueryAction)
     self.iface.removePluginWebMenu(u'&QuickOSM', self.osmFileAction)
     self.iface.removeToolBarIcon(self.mainWindowAction)
     Processing.removeProvider(self.provider)
示例#22
0
    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)
示例#23
0
 def setUpClass(cls):
     start_app()
     from processing.core.Processing import Processing
     Processing.initialize()
     QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms())
     cls.cleanup_paths = []
     cls.in_place_layers = {}
     cls.vector_layer_params = {}
示例#24
0
 def __init__(self, iface):
     self.iface = iface
     self.options_factory = ProcessingOptionsFactory()
     self.options_factory.setTitle(self.tr('Processing'))
     iface.registerOptionsWidgetFactory(self.options_factory)
     self.locator_filter = AlgorithmLocatorFilter()
     iface.registerLocatorFilter(self.locator_filter)
     Processing.initialize()
示例#25
0
    def initGui(self):
        self.commander = None
        self.toolbox = ProcessingToolbox()
        interface.iface.addDockWidget(Qt.RightDockWidgetArea, self.toolbox)
        self.toolbox.hide()
        Processing.addAlgListListener(self.toolbox)

        self.menu = QMenu(interface.iface.mainWindow())
        self.menu.setTitle(QCoreApplication.translate('Processing',
                           'Processing'))

        self.toolboxAction = self.toolbox.toggleViewAction()
        self.toolboxAction.setIcon(QIcon(':/processing/images/alg.png'))
        self.toolboxAction.setText(QCoreApplication.translate('Processing',
                                   'Toolbox'))
        self.menu.addAction(self.toolboxAction)

        self.modelerAction = QAction(QIcon(':/processing/images/model.png'),
                                     QCoreApplication.translate('Processing',
                                     'Graphical modeler'),
                                     interface.iface.mainWindow())
        self.modelerAction.triggered.connect(self.openModeler)
        self.menu.addAction(self.modelerAction)

        self.historyAction = QAction(QIcon(':/processing/images/history.gif'),
                                     QCoreApplication.translate('Processing',
                                     'History and log'),
                                     interface.iface.mainWindow())
        self.historyAction.triggered.connect(self.openHistory)
        self.menu.addAction(self.historyAction)

        self.configAction = QAction(QIcon(':/processing/images/config.png'),
                                    QCoreApplication.translate('Processing',
                                    'Options and configuration'),
                                    interface.iface.mainWindow())
        self.configAction.triggered.connect(self.openConfig)
        self.menu.addAction(self.configAction)

        self.resultsAction = QAction(QIcon(':/processing/images/results.png'),
                                     QCoreApplication.translate('Processing',
                                     '&Results viewer'),
                                     interface.iface.mainWindow())
        self.resultsAction.triggered.connect(self.openResults)
        self.menu.addAction(self.resultsAction)

        menuBar = interface.iface.mainWindow().menuBar()
        menuBar.insertMenu(
            interface.iface.firstRightStandardMenu().menuAction(), self.menu)

        self.commanderAction = QAction(
                QIcon(':/processing/images/commander.png'),
                QCoreApplication.translate('Processing', '&Commander'),
                interface.iface.mainWindow())
        self.commanderAction.triggered.connect(self.openCommander)
        self.menu.addAction(self.commanderAction)
        interface.iface.registerMainWindowAction(self.commanderAction,
                'Ctrl+Alt+M')
示例#26
0
 def unload(self):
     self.iface.mapCanvas().unsetMapTool(self.mapTool)
     self.iface.removeToolBarIcon(self.toolAction)
     self.iface.removePluginMenu("what3words", self.toolAction)
     self.iface.removePluginMenu("what3words", self.zoomToAction)
     self.iface.removePluginMenu("what3words", self.apikeyAction)
     self.iface.removeDockWidget(self.zoomToDialog)
     if processingOk:
         Processing.removeProvider(self.provider)
示例#27
0
 def updateProvider(self, providerName, updateAlgsList = True):
     if updateAlgsList:
         Processing.updateAlgsList()
     for i in xrange(self.algorithmTree.invisibleRootItem().childCount()):
         child = self.algorithmTree.invisibleRootItem().child(i)
         if isinstance(child, TreeProviderItem):
             if child.providerName == providerName:
                 child.refresh()
                 break
示例#28
0
 def setUpClass(cls):
     start_app()
     from processing.core.Processing import Processing
     Processing.initialize()
     ProcessingConfig.setSettingValue(ModelerUtils.MODELS_FOLDER, os.path.join(os.path.dirname(__file__), 'models'))
     QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms())
     cls.cleanup_paths = []
     cls.in_place_layers = {}
     cls.vector_layer_params = {}
     cls._original_models_folder = ProcessingConfig.getSetting(ModelerUtils.MODELS_FOLDER)
 def setUpClass(cls):
     """Run before all tests"""
     QCoreApplication.setOrganizationName("QGIS_Test")
     QCoreApplication.setOrganizationDomain(
         "QGIS_TestPyQgsProcessingInPlace.com")
     QCoreApplication.setApplicationName("QGIS_TestPyQgsProcessingInPlace")
     QgsSettings().clear()
     Processing.initialize()
     QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms())
     cls.registry = QgsApplication.instance().processingRegistry()
示例#30
0
    def fillTreeUsingProviders(self):
        self.algorithmTree.clear()
        text = unicode(self.searchBox.text())
        for providerName in Processing.algs.keys():
            groups = {}
            count = 0
            provider = Processing.algs[providerName]
            name = 'ACTIVATE_' + providerName.upper().replace(' ', '_')
            if not ProcessingConfig.getSetting(name):
                continue
            algs = provider.values()

            # Add algorithms
            for alg in algs:
                if not alg.showInToolbox:
                    continue
                if text == '' or text.lower() in alg.name.lower():
                    if alg.group in groups:
                        groupItem = groups[alg.group]
                    else:
                        groupItem = QTreeWidgetItem()
                        groupItem.setText(0, alg.group)
                        groupItem.setToolTip(0, alg.group)
                        groups[alg.group] = groupItem
                    algItem = TreeAlgorithmItem(alg)
                    groupItem.addChild(algItem)
                    count += 1

            actions = Processing.actions[providerName]
            for action in actions:
                if text == '' or text.lower() in action.name.lower():
                    if action.group in groups:
                        groupItem = groups[action.group]
                    else:
                        groupItem = QTreeWidgetItem()
                        groupItem.setText(0, action.group)
                        groups[action.group] = groupItem
                    algItem = TreeActionItem(action)
                    groupItem.addChild(algItem)

            if len(groups) > 0:
                providerItem = QTreeWidgetItem()
                providerItem.setText(0, Processing.getProviderFromName(
                        providerName).getDescription()
                        + ' [' + str(count) + ' geoalgorithms]')
                providerItem.setIcon(0, Processing.getProviderFromName(
                        providerName).getIcon())
                providerItem.setToolTip(0, providerItem.text(0))
                for groupItem in groups.values():
                    providerItem.addChild(groupItem)
                self.algorithmTree.addTopLevelItem(providerItem)
                providerItem.setExpanded(text != '')
                for groupItem in groups.values():
                    groupItem.setExpanded(text != '')
示例#31
0
 def tearDownClass(cls):
     from processing.core.Processing import Processing
     Processing.deinitialize()
     for path in cls.cleanup_paths:
         shutil.rmtree(path)
示例#32
0
文件: general.py 项目: zgustaf/QGIS
def runAndLoadResults(name, *args, **kwargs):
    """Executes given algorithm and load its results into QGIS project
    when possible.
    """
    return Processing.runAlgorithm(name, handleAlgorithmResults, *args,
                                   **kwargs)
示例#33
0
文件: general.py 项目: drnextgis/QGIS
def runandload(name, *args, **kwargs):
    return Processing.runAlgorithm(name, handleAlgorithmResults, *args,
                                   **kwargs)
def calculate_basic_attributes(
    grassdb,
    grass_location,
    qgis_prefix_path,
    input_geo_names,
    projection,
    catinfo,
    cat_ply_info,
    cat_riv_info,
    outlet_pt_info,
):

    catchments = input_geo_names["catchment_without_merging_lakes"]
    river_r = input_geo_names["river_without_merging_lakes"]
    river_v = input_geo_names["str_v"]
    dem = input_geo_names["dem"]
    fdr = input_geo_names["nfdr_grass"]
    acc = input_geo_names["acc"]
    cat_use_default_acc = input_geo_names["cat_use_default_acc"]
    problem_seg = input_geo_names["problem_seg"]
    nfdr_arcgis = input_geo_names["nfdr_arcgis"]

    import grass.script as grass
    import grass.script.setup as gsetup
    from grass.pygrass.modules import Module
    from grass.pygrass.modules.shortcuts import general as g
    from grass.pygrass.modules.shortcuts import raster as r
    from grass.script import array as garray
    from grass.script import core as gcore
    from grass_session import Session

    QgsApplication.setPrefixPath(qgis_prefix_path, True)
    Qgs = QgsApplication([], False)
    Qgs.initQgis()
    from processing.core.Processing import Processing
    from processing.tools import dataobjects
    from qgis import processing

    feedback = QgsProcessingFeedback()
    Processing.initialize()
    QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms())
    context = dataobjects.createContext()
    context.setInvalidGeometryCheck(QgsFeatureRequest.GeometryNoCheck)

    os.environ.update(
        dict(GRASS_COMPRESS_NULLS="1",
             GRASS_COMPRESSOR="ZSTD",
             GRASS_VERBOSE="1"))
    PERMANENT = Session()
    PERMANENT.open(gisdb=grassdb, location=grass_location, create_opts="")

    con = sqlite3.connect(
        os.path.join(grassdb, grass_location, "PERMANENT", "sqlite",
                     "sqlite.db"))

    # create a catchment vector and overlay with str v
    exp = "%s = int(%s)" % (catchments, catchments)
    grass.run_command("r.mapcalc", expression=exp, overwrite=True)

    grass.run_command(
        "r.to.vect",
        input=catchments,
        output=cat_ply_info + "t1",
        type="area",
        overwrite=True,
    )
    grass.run_command("v.db.addcolumn",
                      map=cat_ply_info + "t1",
                      columns="GC_str VARCHAR(40)")
    grass.run_command("v.db.addcolumn",
                      map=cat_ply_info + "t1",
                      columns="Area_m double")
    grass.run_command("v.db.update",
                      map=cat_ply_info + "t1",
                      column="GC_str",
                      qcol="value")
    # dissolve based on gridcode
    grass.run_command(
        "v.dissolve",
        input=cat_ply_info + "t1",
        column="GC_str",
        output=cat_ply_info,
        overwrite=True,
    )

    grass.run_command("v.db.addcolumn",
                      map=cat_ply_info,
                      columns="Gridcode INT")
    grass.run_command("v.db.update",
                      map=cat_ply_info,
                      column="Gridcode",
                      qcol="GC_str")

    ## obtain a stream vector, segmentation based on new catchment polygon
    grass.run_command(
        "v.overlay",
        ainput=river_v,
        alayer=2,
        atype="line",
        binput=cat_ply_info,
        operator="and",
        output=cat_riv_info + "t1",
        overwrite=True,
    )
    grass.run_command(
        "v.out.ogr",
        input=cat_riv_info + "t1",
        output=os.path.join(grassdb, cat_riv_info + "t1" + ".shp"),
        format="ESRI_Shapefile",
        overwrite=True,
    )
    processing.run(
        "gdal:dissolve",
        {
            "INPUT": os.path.join(grassdb, cat_riv_info + "t1" + ".shp"),
            "FIELD": "b_GC_str",
            "OUTPUT": os.path.join(grassdb, cat_riv_info + ".shp"),
        },
    )
    grass.run_command(
        "v.import",
        input=os.path.join(grassdb, cat_riv_info + ".shp"),
        output=cat_riv_info,
        overwrite=True,
    )

    grass.run_command("v.db.addcolumn",
                      map=cat_riv_info,
                      columns="Gridcode INT")
    grass.run_command("v.db.addcolumn",
                      map=cat_riv_info,
                      columns="Length_m double")
    grass.run_command("v.db.update",
                      map=cat_riv_info,
                      column="Gridcode",
                      qcol="b_GC_str")
    grass.run_command("v.db.dropcolumn",
                      map=cat_riv_info,
                      columns=["b_GC_str"])

    grass.run_command(
        "r.out.gdal",
        input=dem,
        output=os.path.join(grassdb, "dem_par.tif"),
        format="GTiff",
        overwrite=True,
    )

    PERMANENT.close()

    os.system("gdalwarp " + '"' + os.path.join(grassdb, "dem_par.tif") + '"' +
              "    " + '"' + os.path.join(grassdb, "dem_proj.tif") + '"' +
              " -t_srs  " + '"' + projection + '"')

    project = Session()
    project.open(gisdb=grassdb,
                 location=grass_location + "_proj",
                 create_opts=projection)

    grass.run_command(
        "r.import",
        input=os.path.join(grassdb, "dem_proj.tif"),
        output="dem_proj",
        overwrite=True,
    )
    grass.run_command("g.region", raster="dem_proj")
    grass.run_command(
        "v.proj",
        location=grass_location,
        mapset="PERMANENT",
        input=cat_riv_info,
        overwrite=True,
    )
    grass.run_command(
        "v.proj",
        location=grass_location,
        mapset="PERMANENT",
        input=cat_ply_info,
        overwrite=True,
    )

    grass.run_command(
        "v.to.db",
        map=cat_ply_info,
        option="area",
        columns="Area_m",
        units="meters",
        overwrite=True,
    )
    grass.run_command(
        "v.to.db",
        map=cat_riv_info,
        option="length",
        columns="Length_m",
        units="meters",
        overwrite=True,
    )

    grass.run_command(
        "r.slope.aspect",
        elevation="dem_proj",
        slope="slope",
        aspect="aspect",
        precision="DCELL",
        overwrite=True,
    )

    ### calcuate averaged slope and aspect of each subbasin
    grass.run_command(
        "v.rast.stats",
        map=cat_ply_info,
        raster="slope",
        column_prefix="s",
        method="average",
    )
    grass.run_command(
        "v.rast.stats",
        map=cat_ply_info,
        raster="aspect",
        column_prefix="a",
        method="average",
    )

    grass.run_command(
        "v.rast.stats",
        map=cat_ply_info,
        raster="dem_proj",
        column_prefix="d",
        method="average",
    )

    ### calcuate minimum and maximum dem along the channel
    grass.run_command(
        "v.rast.stats",
        map=cat_riv_info,
        raster="dem_proj",
        column_prefix="d",
        method=["minimum", "maximum"],
    )

    project.close()

    PERMANENT = Session()
    PERMANENT.open(gisdb=grassdb, location=grass_location, create_opts="")
    grass.run_command("g.region", raster="dem")
    grass.run_command(
        "v.proj",
        location=grass_location + "_proj",
        mapset="PERMANENT",
        input=cat_riv_info,
        overwrite=True,
    )
    grass.run_command(
        "v.proj",
        location=grass_location + "_proj",
        mapset="PERMANENT",
        input=cat_ply_info,
        overwrite=True,
    )

    ### calcuate averaged DEM in each subbasin
    # grass.run_command(
    #     "v.rast.stats",
    #     map=cat_ply_info,
    #     raster="dem",
    #     column_prefix="d",
    #     method="average",
    # )
    #
    # ### calcuate minimum and maximum dem along the channel
    # grass.run_command(
    #     "v.rast.stats",
    #     map=cat_riv_info,
    #     raster="dem",
    #     column_prefix="d",
    #     method=["minimum", "maximum"],
    # )

    ## get routing structure

    exp = "%s = int(%s)" % (fdr, fdr)
    grass.run_command(
        "r.mapcalc",
        expression=exp,
        overwrite=True,
    )

    grass.run_command(
        "r.accumulate",
        direction=fdr,
        accumulation="acc_grass_CatOL",
        overwrite=True,
    )

    ##### obtain catment id overlaied with problem seg
    prom_seg_id, cat_pro_id = generate_stats_list_from_grass_raster(
        grass, mode=2, input_a=problem_seg, input_b=catchments)
    cat_pro_id = np.unique(cat_pro_id)
    grass.run_command("g.copy",
                      rast=(catchments, cat_use_default_acc),
                      overwrite=True)
    if len(cat_pro_id) > 0:
        grass.run_command("r.null",
                          map=cat_use_default_acc,
                          setnull=cat_pro_id,
                          overwrite=True)
    else:
        cat_pro_id = []

    exp = "acc_grass_CatOL2 = if(isnull(%s),%s,%s)" % (
        cat_use_default_acc,
        "acc_grass_CatOL",
        acc,
    )
    grass.run_command(
        "r.mapcalc",
        expression=exp,
        overwrite=True,
    )

    routing_temp = generate_routing_info_of_catchments(
        grass,
        con,
        cat=catchments,
        acc="acc_grass_CatOL2",
        Name="Final",
        str=river_r,
        garray=garray,
    )

    routing_temp = generate_routing_info_of_catchments(
        grass,
        con,
        cat=river_r,
        acc="acc_grass_CatOL2",
        Name="Friv",
        str=river_r,
        garray=garray,
    )

    cat_array = garray.array(mapname=catchments)
    nfdr_arcgis_array = garray.array(mapname=nfdr_arcgis)
    cat_outlet_array = garray.array(mapname="Final_OL")
    ncols = int(cat_array.shape[1])
    nrows = int(cat_array.shape[0])

    grass.run_command("g.copy",
                      vector=("Final_OL_v", outlet_pt_info),
                      overwrite=True)
    PERMANENT.close()

    ## add coordinates to outlet point in wgs84 system
    project_wgs84 = Session()
    project_wgs84.open(gisdb=grassdb,
                       location=grass_location + "_wgs84",
                       create_opts='EPSG:4326')
    grass.run_command(
        "v.proj",
        location=grass_location,
        mapset="PERMANENT",
        input=outlet_pt_info,
        overwrite=True,
    )
    grass.run_command(
        "v.to.db",
        map=outlet_pt_info,
        type='point',
        option='coor',
        columns=['outletLng', 'outletLat'],
        overwrite=True,
    )
    project_wgs84.close()

    ## import updated outlet points after add coordinates in wgs84 system
    PERMANENT = Session()
    PERMANENT.open(gisdb=grassdb, location=grass_location, create_opts="")
    grass.run_command("g.region", raster="dem")
    grass.run_command(
        "v.proj",
        location=grass_location + "_wgs84",
        mapset="PERMANENT",
        input=outlet_pt_info,
        overwrite=True,
    )

    ### update dataframe
    ###
    sqlstat = "SELECT Gridcode, Length_m, d_minimum, d_maximum FROM %s" % (
        cat_riv_info)
    leninfo = pd.read_sql_query(sqlstat, con)
    ### read catchment
    sqlstat = "SELECT Gridcode, Area_m,d_average,s_average,a_average FROM %s" % (
        cat_ply_info)
    areainfo = pd.read_sql_query(sqlstat, con)

    ### read catchment
    sqlstat = "SELECT SubId, DowSubId,ILSubIdmax,ILSubIdmin,outletLat, outletLng FROM %s" % (
        outlet_pt_info)
    outletinfo = pd.read_sql_query(sqlstat, con)
    outletinfo = outletinfo.fillna(-9999)
    outletinfo = outletinfo.loc[outletinfo['SubId'] >= 0]
    ### read catchment
    sqlstat = "SELECT SubId, DSubId_str FROM %s" % ('Friv_OL_v')
    outlet_riv_info = pd.read_sql_query(sqlstat, con)
    outlet_riv_info = outlet_riv_info.fillna(-9999)

    leninfo = leninfo.astype(float).fillna(-9999)
    areainfo = areainfo.astype(float).fillna(-9999)

    for i in range(0, len(outletinfo)):
        catid = outletinfo["SubId"].values[i]
        DownSubID_cat = outletinfo["DowSubId"].values[i]
        outlet_lat = outletinfo["outletLat"].values[i]
        outlet_lon = outletinfo["outletLng"].values[i]

        catinfo.loc[i, "SubId"] = catid
        catinfo.loc[i, "outletLat"] = outlet_lat
        catinfo.loc[i, "outletLng"] = outlet_lon

        # load routing info based on str
        outlet_riv_info_i = outlet_riv_info.loc[outlet_riv_info['SubId'] ==
                                                catid]

        # check if riv outlet exist
        if len(outlet_riv_info_i) < 1:
            DownSubID = DownSubID_cat
            DownSubID_riv = -9999
        else:
            # get down sub id based in river network
            DownSubID_riv = outlet_riv_info_i['DSubId_str'].values[0]

            # may need to modify if downsub id from river != down subid from cat
            if DownSubID_riv != DownSubID_cat:

                # check if DownSubID_cat drainage to DSubId_str
                Down_id_of_downriv_info = outletinfo.loc[outletinfo['SubId'] ==
                                                         DownSubID_riv]
                if len(Down_id_of_downriv_info) > 0:
                    # get down subid of down subid of river
                    DSubId_DSubId_str = Down_id_of_downriv_info[
                        'DowSubId'].values[0]
                    # if down subid of down sub id of river  = down sub id from cat
                    if catid == 10762:
                        print(DSubId_DSubId_str, DownSubID_cat)

                    if DSubId_DSubId_str == DownSubID_cat:
                        DownSubID = DownSubID_riv
                    else:
                        DownSubID = DownSubID_cat
                else:
                    DownSubID = DownSubID_cat
            else:
                DownSubID = DownSubID_cat

        if catid in cat_pro_id or DownSubID == catid or DownSubID == -9999:
            downsubid_array = return_subid_of_next_down_stream_grids(
                cat_array, catid, nfdr_arcgis_array, cat_outlet_array, ncols,
                nrows)
            #            print(catid,DownSubID,downsubid_array)
            if downsubid_array > 0:
                DownSubID = downsubid_array

        ### change the downsub id to -1 for watershed outlet
        if len(outletinfo.loc[outletinfo["SubId"] == DownSubID]) < 1:
            catinfo.loc[i, "DowSubId"] = -1
        elif catid == DownSubID:
            catinfo.loc[i, "DowSubId"] = -1
        else:
            catinfo.loc[i, "DowSubId"] = DownSubID

        catarea = np.unique(areainfo.loc[areainfo["Gridcode"] == catid]
                            ["Area_m"].values)  #'Area_m'
        catslope = np.unique(
            areainfo.loc[areainfo["Gridcode"] == catid]["s_average"].values)
        catelev = np.unique(
            areainfo.loc[areainfo["Gridcode"] == catid]["d_average"].values)
        cataspect = np.unique(
            areainfo.loc[areainfo["Gridcode"] == catid]["a_average"].values)
        if len(catarea) == 1:
            catinfo.loc[i, "BasArea"] = catarea
            catinfo.loc[i, "BasSlope"] = catslope
            catinfo.loc[i, "BasAspect"] = cataspect
            catinfo.loc[i, "MeanElev"] = catelev
        else:
            print(
                "Warning  basin area of stream  ",
                catid,
                "   need check   ",
                len(catarea),
            )
            catinfo.loc[i, "BasArea"] = -9999
            catinfo.loc[i, "BasSlope"] = -9999
            catinfo.loc[i, "BasAspect"] = -9999
            catinfo.loc[i, "MeanElev"] = -9999

        ### add river parameters
        rivlen = np.unique(leninfo.loc[leninfo["Gridcode"] == catid]
                           ["Length_m"].values)  #'Area_m'
        dmaxelev = np.unique(
            leninfo.loc[leninfo["Gridcode"] == catid]["d_maximum"].values)
        dminelev = np.unique(
            leninfo.loc[leninfo["Gridcode"] == catid]["d_minimum"].values)
        if len(rivlen) > 0:
            catinfo.loc[i, "RivLength"] = rivlen[0]
            maxdem = dmaxelev[0]
            mindem = dminelev[0]
            catinfo.loc[i, "Min_DEM"] = mindem
            catinfo.loc[i, "Max_DEM"] = maxdem
            if rivlen[0] >= 0:
                if max(0, float((maxdem - mindem)) / float(rivlen[0])) == 0:
                    slope_rch = -9999
                else:
                    slope_rch = max(
                        0,
                        float((maxdem - mindem)) / float(rivlen[0]))

                slope_rch = max(slope_rch, min_riv_slope)
                slope_rch = min(slope_rch, max_riv_slope)

                catinfo.loc[i, "RivSlope"] = slope_rch

            else:
                catinfo.loc[i, "RivSlope"] = -9999
        else:
            catinfo.loc[i, "RivLength"] = -9999
            catinfo.loc[i, "RivSlope"] = -9999
            catinfo.loc[i, "FloodP_n"] = -9999
            catinfo.loc[i, "Min_DEM"] = -9999
            catinfo.loc[i, "Max_DEM"] = -9999

    PERMANENT.close()
    return catinfo
示例#35
0
 def initGui(self):
     Processing.addProvider(self.provider)
示例#36
0
def idw_interpolation(layer, parent_dialog):
    """Run interpolation using inverse distance weight algorithm

    :param layer: Vector layer with drivetimes
    :type layer: QgsVectorLayer

    :param parent_dialog: A dialog for showing progress.
    :type parent_dialog: QProgressDialog

    :returns raster_layer: Interpolated raster layer with drivetimes
    :rtype raster_layer: QgsRasterLayer

    """
    raster_layer = None
    try:
        Processing.initialize()

        # Create temporary file

        temp_output_file = tempfile.NamedTemporaryFile()
        temp_output_file_path = temp_output_file.name + '.tif'

        saved_layer = save_layer(layer)

        params = {'INPUT': saved_layer.dataProvider().dataSourceUri(),
                  'Z_FIELD': 'minutes',
                  'POWER': 2,
                  'SMOOTHING': 0,
                  'RADIUS_1': 0,
                  'RADIUS_2': 0,
                  'ANGLE': 0,
                  'MAX_POINTS': 0,
                  'MIN_POINTS': 0,
                  'NODATA': 0,
                  'DATA_TYPE': 5,
                  'OUTPUT': temp_output_file_path
                  }

        output_raster = processing.run(
            'gdal:gridinversedistance', params
        )

        output_file = output_raster['OUTPUT']

        # retrieving the raster output , styling it and load it in Qgis

        raster_layer = QgsRasterLayer(output_file, 'styled map')

        raster_layer = style_raster_layer(raster_layer, parent_dialog)

        QgsProject.instance().addMapLayer(raster_layer)

        # TODO use stored static style instead of dynamic one??
        #  map_style = resources_path(
        #     'styles',
        #     'qgis',
        #     'map.qml')
        # raster_layer.loadNamedStyle(map_style)
        #
        # raster_layer.triggerRepaint()

    except Exception as exception:  # pylint: disable=broad-except
            # noinspection PyCallByClass,PyTypeChecker,PyArgumentList
        if parent_dialog:
            message = 'Error loading isochrone map,'\
                      'please check if you have processing '\
                      'plugin installed \n'.\
                      format(str(exception))
            display_warning_message_box(
                parent_dialog,
                parent_dialog.tr(
                    'Error'),
                parent_dialog.tr(message))
        else:
            display_warning_message_box(
                parent_dialog,
                'Error',
                'Error loading isochrone map,'
                'please check if you have processing '
                'plugin installed ')

        raise IsochroneMapStyleError

    return raster_layer
示例#37
0
 def __init__(self, iface):
     self.iface = iface
     self.options_factory = ProcessingOptionsFactory()
     self.options_factory.setTitle(self.tr('Processing'))
     iface.registerOptionsWidgetFactory(self.options_factory)
     Processing.initialize()
示例#38
0
from processing.gui.AlgorithmDialog import AlgorithmDialog
from qgis.utils import iface
from qgis.core import QgsApplication, QgsMessageLog, QgsStringUtils, QgsProcessingAlgorithm
from qgis.gui import QgsGui
from processing.gui.MessageBarProgress import MessageBarProgress
from processing.gui.AlgorithmExecutor import execute
from processing.gui.Postprocessing import handleAlgorithmResults
from processing.core.Processing import Processing
from processing.tools import dataobjects

algorithmsToolbar = None
menusSettingsGroup = 'Menus'

defaultMenuEntries = {}
vectorMenu = QApplication.translate('MainWindow', 'Vect&or')
analysisToolsMenu = vectorMenu + "/" + Processing.tr('&Analysis Tools')
defaultMenuEntries.update({
    'qgis:distancematrix': analysisToolsMenu,
    'native:sumlinelengths': analysisToolsMenu,
    'native:countpointsinpolygon': analysisToolsMenu,
    'qgis:listuniquevalues': analysisToolsMenu,
    'qgis:basicstatisticsforfields': analysisToolsMenu,
    'native:nearestneighbouranalysis': analysisToolsMenu,
    'native:meancoordinates': analysisToolsMenu,
    'native:lineintersections': analysisToolsMenu
})
researchToolsMenu = vectorMenu + "/" + Processing.tr('&Research Tools')
defaultMenuEntries.update({
    'native:creategrid': researchToolsMenu,
    'qgis:randomselection': researchToolsMenu,
    'qgis:randomselectionwithinsubsets': researchToolsMenu,
示例#39
0
from PyQt4.QtCore import QVariant





app = QApplication([])
QgsApplication.setPrefixPath("/usr", True)
QgsApplication.initQgis()

# Prepare processing framework 

sys.path.append('/usr/share/qgis/python/plugins')
from processing.core.Processing import Processing

Processing.initialize()
from processing.tools import *

########DON*T DISTRIBUTE REMOVES EVERTTHING tmp*!!##########
os.system("rm -r tmp*")

def compare(path, verticenumber, friciton, poly, lcpLos, cellsize, maxdist):
	print friciton
	print poly
	if os.path.isdir(path):
		"path already used"
		return
	os.system("mkdir "+path)
	
	# Generate Random start point:
	general.runalg("qgis:randompointsinlayerbounds",poly,1,cellsize,path +"random_start.shp")
 def initGui(self):
     Processing.addScripts(os.path.join(os.path.dirname(__file__), "scripts"))
示例#41
0
文件: general.py 项目: ns5001/QGIS
def run(algOrName, parameters, onFinish=None, feedback=None, context=None):
    """Executes given algorithm and returns its outputs as dictionary
    object.
    """
    return Processing.runAlgorithm(algOrName, parameters, onFinish, feedback,
                                   context)
示例#42
0
 def __init__(self, iface):
     self.iface = iface
     Processing.initialize()
 def unload(self):
     Processing.removeScripts(os.path.join(os.path.dirname(__file__), "scripts"))
示例#44
0
def init_processing() -> None:
    from processing.core.Processing import Processing
    from qgis.analysis import QgsNativeAlgorithms
    from qgis.core import QgsApplication
    QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms())
    Processing.initialize()
示例#45
0
 def initProcessing(self):
     if not self.initialized:
         self.initialized = True
         Processing.initialize()
示例#46
0
def createTest(text):
    definition = {}

    tokens = list(parseParameters(text[len('processing.run('):-1]))
    cmdname = tokens[0]
    alg = Processing.getAlgorithm(cmdname)

    definition['name'] = 'Test ({})'.format(cmdname)
    definition['algorithm'] = cmdname

    params = {}
    results = {}

    i = 0
    for param in alg.parameters:
        if param.hidden:
            continue

        i += 1
        token = tokens[i]
        # Handle empty parameters that are optionals
        if param.optional and token is None:
            continue

        if isinstance(param, ParameterVector):
            schema, filepath = extractSchemaPath(token)
            p = {
                'type': 'vector',
                'name': filepath
            }
            if not schema:
                p['location'] = '[The source data is not in the testdata directory. Please use data in the processing/tests/testdata folder.]'

            params[param.name] = p
        elif isinstance(param, ParameterRaster):
            schema, filepath = extractSchemaPath(token)
            p = {
                'type': 'raster',
                'name': filepath
            }
            if not schema:
                p['location'] = '[The source data is not in the testdata directory. Please use data in the processing/tests/testdata folder.]'

            params[param.name] = p
        elif isinstance(param, ParameterTable):
            schema, filepath = extractSchemaPath(token)
            p = {
                'type': 'table',
                'name': filepath
            }
            if not schema:
                p['location'] = '[The source data is not in the testdata directory. Please use data in the processing/tests/testdata folder.]'

            params[param.name] = p
        elif isinstance(param, ParameterMultipleInput):
            multiparams = token.split(';')
            newparam = []

            # Handle datatype detection
            dataType = param.dataType()
            if dataType in ['points', 'lines', 'polygons', 'any vectors']:
                dataType = 'vector'
            else:
                dataType = 'raster'

            for mp in multiparams:
                schema, filepath = extractSchemaPath(mp)
                newparam.append({
                    'type': dataType,
                    'name': filepath
                })
            p = {
                'type': 'multi',
                'params': newparam
            }
            if not schema:
                p['location'] = '[The source data is not in the testdata directory. Please use data in the processing/tests/testdata folder.]'

            params[param.name] = p
        elif isinstance(param, ParameterFile):
            schema, filepath = extractSchemaPath(token)
            p = {
                'type': 'file',
                'name': filepath
            }
            if not schema:
                p['location'] = '[The source data is not in the testdata directory. Please use data in the processing/tests/testdata folder.]'

            params[param.name] = p
        elif isinstance(param, ParameterString):
            params[param.name] = token
        elif isinstance(param, ParameterBoolean):
            params[param.name] = token
        elif isinstance(param, ParameterNumber):
            if param.isInteger:
                params[param.name] = int(token)
            else:
                params[param.name] = float(token)
        else:
            if token[0] == '"':
                token = token[1:]
            if token[-1] == '"':
                token = token[:-1]
            params[param.name] = token

    definition['params'] = params

    for i, out in enumerate([out for out in alg.outputs if not out.hidden]):
        token = tokens[i - alg.getVisibleOutputsCount()]

        if isinstance(out, (OutputNumber, OutputString)):
            results[out.name] = str(out)
        elif isinstance(out, OutputRaster):
            if token is None:
                QMessageBox.warning(None,
                                    tr('Error'),
                                    tr('Seems some outputs are temporary '
                                       'files. To create test you need to '
                                       'redirect all algorithm outputs to '
                                       'files'))
                return

            dataset = gdal.Open(token, GA_ReadOnly)
            dataArray = nan_to_num(dataset.ReadAsArray(0))
            strhash = hashlib.sha224(dataArray.data).hexdigest()

            results[out.name] = {
                'type': 'rasterhash',
                'hash': strhash
            }
        elif isinstance(out, OutputVector):
            schema, filepath = extractSchemaPath(token)
            results[out.name] = {
                'type': 'vector',
                'name': filepath
            }
            if not schema:
                results[out.name]['location'] = '[The expected result data is not in the testdata directory. Please write it to processing/tests/testdata/expected. Prefer gml files.]'
        elif isinstance(out, OutputHTML) or isinstance(out, OutputFile):
            schema, filepath = extractSchemaPath(token)
            results[out.name] = {
                'type': 'file',
                'name': filepath
            }
            if not schema:
                results[out.name]['location'] = '[The expected result file is not in the testdata directory. Please redirect the output to processing/tests/testdata/expected.]'

    definition['results'] = results
    dlg = ShowTestDialog(yaml.dump([definition], default_flow_style=False))
    dlg.exec_()
示例#47
0
def generate_drivetimes_contour(raster_layer, interval, parent_dialog):
    """Create drive times contour

    :param raster_layer: Interpolated raster layer with drivetimes
    :type raster_layer: QgsRasterLayer

    :param interval: drivetimes interval
    :type interval: int

    :param parent_dialog: A dialog that called this function.
    :type parent_dialog: QProgressDialog

    :returns layer: Vector layer with contour drivetimes
    :rtype layer: QgsVectorLayer

    """
    drivetime_layer = None

    try:
        Processing.initialize()

        temp_output_file = tempfile.NamedTemporaryFile()
        temp_output_file_path = temp_output_file.name + '.shp'

        params = {
                'INPUT': raster_layer,
                'INTERVAL': interval,
                'FIELD_NAME': 'minutes',
                'CREATE_3D': False,
                'IGNORE_NODATA': False,
                'NODATA': 0,
                'BAND': 1,
                'OUTPUT': temp_output_file_path
        }

        output_vector = processing.run(
            'gdal:contour', params
        )

        drivetime_layer = QgsVectorLayer(
                output_vector['OUTPUT'],
                'time(min)',
                'ogr')

    except Exception as exception:  # pylint: disable=broad-except
            # noinspection PyCallByClass,PyTypeChecker,PyArgumentList
        if parent_dialog:
            message = 'Error loading isochrone map,' \
                      'please check if you have processing ' \
                      'plugin installed \n'. \
                      format(str(exception))
            display_warning_message_box(
                parent_dialog,
                parent_dialog.tr(
                    'Error'),
                parent_dialog.tr(message))
        else:
            message = 'Error loading isochrone map,'\
                      'please check if you have processing '\
                        'plugin installed \n'.\
                        format(str(exception))

            display_warning_message_box(
                parent_dialog,
                'Error',
                message)

        raise IsochroneMapStyleError

    return drivetime_layer
示例#48
0
 def editRenderingStyles(self):
     item = self.algorithmTree.currentItem()
     if isinstance(item, TreeAlgorithmItem):
         alg = Processing.getAlgorithm(item.alg.commandLineName())
         dlg = EditRenderingStylesDialog(alg)
         dlg.exec_()
示例#49
0
 def unload(self):
     Processing.removeProvider(self.provider)
示例#50
0
    def initGui(self):

        # Create action that will show the about page
        self.aboutAction = QAction(
            QIcon(":/plugins/crayfish/images/crayfish.png"), "About",
            self.iface.mainWindow())
        QObject.connect(self.aboutAction, SIGNAL("triggered()"), self.about)

        # Create action for upload
        self.uploadAction = QAction(
            QIcon(":/plugins/illuvis/illuvis_u_32w.png"),
            "Upload to illuvis ...", self.iface.mainWindow())
        QObject.connect(self.uploadAction, SIGNAL("triggered()"), self.upload)

        # Add menu items
        self.menu = self.iface.pluginMenu().addMenu(
            QIcon(":/plugins/crayfish/images/crayfish.png"), "Crayfish")
        self.menu.addAction(self.aboutAction)
        self.menu.addAction(self.uploadAction)

        if not ensure_library_installed():
            return

        self.crayfishLibFound = True

        # Create action that will load a layer to view
        self.action = QAction(
            QIcon(":/plugins/crayfish/images/crayfish_viewer_add_layer.png"),
            "Add Crayfish Layer", self.iface.mainWindow())
        QObject.connect(self.action, SIGNAL("triggered()"),
                        self.addCrayfishLayer)

        self.actionExportGrid = QAction(
            QIcon(":/plugins/crayfish/images/crayfish_export_raster.png"),
            "Export to Raster Grid ...", self.iface.mainWindow())
        QObject.connect(self.actionExportGrid, SIGNAL("triggered()"),
                        self.exportGrid)

        self.actionExportContours = QAction(
            QIcon(":/plugins/crayfish/images/contour.png"),
            "Export Contours ...", self.iface.mainWindow())
        QObject.connect(self.actionExportContours, SIGNAL("triggered()"),
                        self.exportContours)

        self.actionExportAnimation = QAction(
            QIcon(":/plugins/crayfish/images/icon_video.png"),
            "Export Animation ...", self.iface.mainWindow())
        QObject.connect(self.actionExportAnimation, SIGNAL("triggered()"),
                        self.exportAnimation)

        self.actionPlot = QAction(
            QgsApplication.getThemeIcon("/histogram.png"), "Plot",
            self.iface.mainWindow())

        self.actionHelp = QAction(
            QgsApplication.getThemeIcon("/mActionHelpContents.svg"), "Help",
            self.iface.mainWindow())
        QObject.connect(self.actionHelp, SIGNAL("triggered()"), self.help)

        # Add toolbar button and menu item
        layerTB = self.iface.layerToolBar()
        layerTB.insertAction(self.iface.actionAddPgLayer(), self.action)

        # Add menu item
        self.menu.addAction(self.action)
        self.menu.addAction(self.actionExportGrid)
        self.menu.addAction(self.actionExportContours)
        self.menu.addAction(self.actionExportAnimation)
        self.menu.addAction(self.actionPlot)
        self.menu.addAction(self.actionHelp)

        # Register plugin layer type
        self.lt = CrayfishPluginLayerType()
        QgsPluginLayerRegistry.instance().addPluginLayerType(self.lt)

        # Register actions for context menu
        self.iface.legendInterface().addLegendLayerAction(
            self.actionExportGrid, '', '', QgsMapLayer.PluginLayer, False)
        self.iface.legendInterface().addLegendLayerAction(
            self.actionExportContours, '', '', QgsMapLayer.PluginLayer, False)
        self.iface.legendInterface().addLegendLayerAction(
            self.uploadAction, '', '', QgsMapLayer.PluginLayer, False)
        self.iface.legendInterface().addLegendLayerAction(
            self.actionExportAnimation, '', '', QgsMapLayer.PluginLayer, False)

        # Make connections
        QObject.connect(self.lr, SIGNAL("layersWillBeRemoved(QStringList)"),
                        self.layersRemoved)
        QObject.connect(self.lr, SIGNAL("layerWillBeRemoved(QString)"),
                        self.layerRemoved)
        QObject.connect(self.lr, SIGNAL("layerWasAdded(QgsMapLayer*)"),
                        self.layerWasAdded)

        # Create the dock widget
        self.dock = CrayfishDock(self.iface)
        self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.dock)
        self.dock.hide()  # do not show the dock by default
        QObject.connect(self.dock, SIGNAL("visibilityChanged(bool)"),
                        self.dockVisibilityChanged)
        custom_actions = [
            self.actionExportGrid, self.actionExportContours,
            self.uploadAction, self.actionExportAnimation
        ]
        self.dock.treeDataSets.setCustomActions(custom_actions)

        self.actionPlot.triggered.connect(self.dock.plot)

        # Register data items provider (if possible - since 2.10)
        self.dataItemsProvider = None
        if 'QgsDataItemProvider' in globals():
            self.dataItemsProvider = CrayfishDataItemProvider()
            QgsDataItemProviderRegistry.instance().addProvider(
                self.dataItemsProvider)

        # Processing toolbox
        try:
            from processing.core.Processing import Processing
            from .algs import CrayfishProcessingProvider
            self.processing_provider = CrayfishProcessingProvider()
            Processing.addProvider(self.processing_provider, updateList=True)
        except ImportError:
            pass
示例#51
0
from qgis.core import QgsApplication, QgsMessageLog, QgsStringUtils, QgsProcessingAlgorithm
from qgis.gui import QgsGui
from processing.gui.MessageBarProgress import MessageBarProgress
from processing.gui.AlgorithmExecutor import execute
from processing.gui.Postprocessing import handleAlgorithmResults
from processing.core.Processing import Processing
from processing.tools import dataobjects

algorithmsToolbar = None
menusSettingsGroup = 'Menus'

defaultMenuEntries = {}
vectorMenu = QApplication.translate('MainWindow', 'Vect&or')
# analysisToolsMenu = vectorMenu + "/" + Processing.tr('&Analysis Tools')
analysisToolsMenu = [
    vectorMenu + "/" + Processing.tr('&Analysis Tools'),
    vectorMenu + "/" + 'Analysis_Tools'
]
defaultMenuEntries.update({
    'qgis:distancematrix': analysisToolsMenu,
    'native:sumlinelengths': analysisToolsMenu,
    'native:countpointsinpolygon': analysisToolsMenu,
    'qgis:listuniquevalues': analysisToolsMenu,
    'qgis:basicstatisticsforfields': analysisToolsMenu,
    'native:nearestneighbouranalysis': analysisToolsMenu,
    'native:meancoordinates': analysisToolsMenu,
    'native:lineintersections': analysisToolsMenu
})
# researchToolsMenu = vectorMenu + "/" + Processing.tr('&Research Tools')
researchToolsMenu = [
    vectorMenu + "/" + Processing.tr('&Research Tools'),
示例#52
0
 def __init__(self, providerName):
     QTreeWidgetItem.__init__(self)
     self.providerName = providerName
     self.provider = Processing.getProviderFromName(providerName)
     self.setIcon(0, self.provider.getIcon())
     self.populate()
示例#53
0
import sip
API_NAMES = [
    "QDate", "QDateTime", "QString", "QTextStream", "QTime", "QUrl", "QVariant"
]
API_VERSION = 2
for name in API_NAMES:
    sip.setapi(name, API_VERSION)

from PyQt4.QtGui import *
app = QgsApplication([], True)
app.setPrefixPath("C:/OSGeo4W64/apps/qgis", True)
app.initQgis()

import processing
from processing.core.Processing import Processing
Processing.initialize()
Processing.updateAlgsList()
# ------------------------------------------------------------------------------------------------------------
from PyQt4.QtCore import *
from xlrd import open_workbook
from PyQt4.QtCore import QVariant
import os
import shutil
'''
==============================================================================================================
Technology codes:
                    1 --> Wood pellets central
                    2 --> Heat pump air/water
                    3 --> Gas central
                    4 --> District Heating (DH)
==============================================================================================================                    
示例#54
0
文件: general.py 项目: drnextgis/QGIS
def runalg(algOrName, *args, **kwargs):
    alg = Processing.runAlgorithm(algOrName, None, *args, **kwargs)
    if alg is not None:
        return alg.getOutputValuesAsDictionary()
示例#55
0
    def symbology_graduated(self, layer):

        # connect to PostGIS database with the municipalities and the data table
        layer = iface.activeLayer()
        uri = QgsDataSourceUri()
        uri.setConnection("localhost", "5432", "MED", "postgres", "postgres")
        uri.setDataSource("public", "distritos", "geom", '', "gid")

        # now query the table
        db = QSqlDatabase.addDatabase("QPSQL")
        db.setDatabaseName(uri.database())
        db.setPort(int(uri.port()))
        db.setUserName(uri.username())
        db.setPassword(uri.password())
        db.open()

        attribute_choose = self.dlg.comboBox.currentText()
        level_choose = self.dlg.comboBox_5.currentText()
        pqi_choose = self.dlg.comboBox_6.currentText()
        ICD_choose = self.dlg.comboBox_8.currentText()
        year_choose = self.dlg.comboBox_7.currentText()

        #if self.dlg.comboBox_7.currentText()!='all':
        import os
        directory = 'C:\OSGeo4W64/apps\qgis\python\plugins\hcqi_tool'
        with open(os.path.join(directory, 'pqi.bat'), 'w') as OPATH:
            OPATH.writelines([
                'SET Path=%WINDIR%\system32;%WINDIR%;%WINDIR%\System32\Wbem;&',
                'C:/"Program Files"/PostgreSQL/12/bin/pgsql2shp.exe -f C:/Users/Lia/AppData/Roaming/QGIS/QGIS3/profiles/default/layer_pqi2.shp -u postgres -P postgres MED "SELECT distritos.distrito,data_pqi.valor_pqi,geom FROM data_pqi INNER JOIN distritos ON data_pqi.geo=distritos.distrito WHERE (data_pqi.pqi='
                + "'" + str(pqi_choose) + "'" + ' AND data_pqi.chrono=' + "'" +
                str(year_choose) + "'" + ' AND data_pqi.codificacao=' + "'" +
                str(ICD_choose) + "'" +
                ') GROUP BY distritos.distrito, data_pqi.valor_pqi, data_pqi.chrono, distritos.geom ORDER BY distritos.distrito"'
            ])
        # QMessageBox.about(self.dlg.checkBox, 'teste', str('yes'))
        #layer = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/layer_average.shp"
        #os.system(os.path.join(QGIS_DIR, "python/plugins/hcqi_tool/average.bat"))
        os.system(os.path.join(QGIS_DIR, "python/plugins/hcqi_tool/pqi.bat"))
        layer = "C:/Users/Lia/AppData/Roaming/QGIS/QGIS3/profiles/default/layer_pqi2.shp"

        #vdlayer = QgsVectorLayer(str(layer), "layer", "ogr")
        # QgsMapLayerRegistry.instance().addMapLayer(vdlayer)

        layer_proj = "C:/Users/Lia/AppData/Roaming/QGIS/QGIS3/profiles/default/layer_pqi_proj_etrs89.shp"

        proj_layer = Processing.runAlgorithm(
            "native:reprojectlayer", {
                'INPUT': str(layer),
                'TARGET_CRS': QgsCoordinateReferenceSystem('EPSG:3763'),
                'OPERATION':
                '+proj=pipeline +step +proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=tmerc +lat_0=39.6682583333333 +lon_0=-8.13310833333333 +k=1 +x_0=0 +y_0=0 +ellps=GRS80',
                'OUTPUT': str(layer_proj)
            })

        vdlayer = QgsVectorLayer(str(layer_proj), "layer", "ogr")
        fields_at = vdlayer.fields()
        # QMessageBox.about(self.dlg.checkBox, 'teste', str(fields_at))
        self.field_names_at = fields_at.names()
        # QMessageBox.about(self.dlg.checkBox, 'teste', str(self.field_names_at))
        mean = self.field_names_at[1]

        # self.field = self.dlg.comboBox.currentText()
        # self.classes = self.dlg.spinBox.value()
        myRenderer = QgsGraduatedSymbolRenderer()
        myRenderer.setClassAttribute(mean)
        myRenderer.setMode(QgsGraduatedSymbolRenderer.EqualInterval)
        myRenderer.updateClasses(vdlayer,
                                 QgsGraduatedSymbolRenderer.EqualInterval, 5)
        myStyle = QgsStyle().defaultStyle()
        defaultColorRampNames = myStyle.colorRampNames()
        ramp = myStyle.colorRamp(defaultColorRampNames[5])

        myRenderer.updateColorRamp(ramp)
        vdlayer.setRenderer(myRenderer)
        QgsProject.instance().addMapLayer(vdlayer)
    def convert(self):
        self.buttonBox.button(QDialogButtonBox.Ok).setDefault(False)
        inputLayer = self.inputLayerCombo.currentText()
        # layer information
        layer = QgsVectorLayer(inputLayer, inputLayer, "ogr")
        vectorlayer_vector = layer.dataProvider()
        # extent
        extent_rect = vectorlayer_vector.extent()
        xmin = extent_rect.xMinimum()
        xmax = extent_rect.xMaximum()
        ymin = extent_rect.yMinimum()
        ymax = extent_rect.yMaximum()
        extent = str(xmin) + "," + str(xmax) + "," + str(ymin) + "," + str(
            ymax)
        # attribute
        Elevation = self.lineAttrib.currentText()
        # cellsize
        cellSize = int(self.linePix.value())
        outPath = self.inputLayerCombo3.text()

        # indexes for hidraulic conductivity
        numberRows = int(self.tableWidget.rowCount())
        numberColumns = int(self.tableWidget.columnCount())
        classes = ''
        lista = []
        for i in range(0, numberRows):
            for j in range(0, numberColumns):
                self.line = self.tableWidget.item(i, j)
                lista = lista + [str(self.line.text())]
                string = ","
                intervals = string.join(lista)
        results = list(map(float, lista))

        Processing.initialize()
        conductivity = QFileInfo(
            QgsApplication.qgisUserDatabaseFilePath()).path() + "/conductivity"

        Processing.runAlgorithm(
            "grass7:v.to.rast", {
                'input': inputLayer,
                'type': [0, 1, 3],
                'where': '',
                'use': 0,
                'attribute_column': Elevation,
                'rgb_column': None,
                'label_column': None,
                'value': None,
                'memory': 300,
                'output': conductivity,
                'GRASS_REGION_PARAMETER': extent,
                'GRASS_REGION_CELLSIZE_PARAMETER': cellSize,
                'GRASS_RASTER_FORMAT_OPT': '',
                'GRASS_RASTER_FORMAT_META': '',
                'GRASS_SNAP_TOLERANCE_PARAMETER': -1,
                'GRASS_MIN_AREA_PARAMETER': 0.0001
            })

        #cond_reclassify = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/cond_reclassify.sdat"
        Processing.runAlgorithm(
            "saga:reclassifyvalues", {
                'INPUT': conductivity,
                'METHOD': 2,
                'OLD': 0,
                'NEW': 1,
                'SOPERATOR': 0,
                'MIN': 0,
                'MAX': 1,
                'RNEW': 2,
                'ROPERATOR': 0,
                'RETAB': results,
                'TOPERATOR': 0,
                'NODATAOPT': True,
                'NODATA': 0,
                'OTHEROPT': True,
                'OTHERS': 0,
                'RESULT': outPath
            })

        #Processing.runAlgorithm("grass7:r.surf.idw", None, cond_reclassify, 12, False, extent, cellSize, outPath)

        # add result into canvas
        file_info_norm = QFileInfo(str(outPath))
        # QMessageBox.about(self, "teste", str(file_info_norm))
        rlayer_new_norm = QgsRasterLayer(outPath, file_info_norm.fileName(),
                                         'gdal')
        # QMessageBox.about(self, "teste", str(rlayer_new_norm))
        QgsProject.instance().addMapLayer(rlayer_new_norm)
        self.iface.canvas.setExtent(rlayer_new_norm.extent())
        # set the map canvas layer set
        self.iface.canvas.setLayers([rlayer_new_norm])
        # add result into canvas
        # file_info = QFileInfo(outPath)
        # if file_info.exists():
        #     layer_name = file_info.baseName()
        # else:
        #     return False
        # rlayer_new = QgsRasterLayer(outPath, layer_name)
        # if rlayer_new.isValid():
        #     QgsMapLayerRegistry.instance().addMapLayer(rlayer_new)
        #     layer = QgsMapCanvasLayer(rlayer_new)
        #     layerList = [layer]
        #     extent = self.iface.canvas.setExtent(rlayer_new.extent())
        #     self.iface.canvas.setLayerSet(layerList)
        #     self.iface.canvas.setVisible(True)
        #     return True
        # else:
        #     return False
        # QMessageBox.information(self, self.tr( "Finished" ), self.tr( "Hidraulic conductivity completed." ) )

        self.buttonBox.button(QDialogButtonBox.Ok).setDefault(True)
    def convert(self):

        gdal.AllRegister()
        # ------------------------ FIRST METHOD -------------------------------------------------
        self.buttonBox.button(QDialogButtonBox.Ok).setDefault(False)
        if self.inputLayerCombo.currentText() != "":
            inputLayer = self.inputLayerCombo.currentText()
            inputMask = self.inputMaskCombo.currentText()
            # layer information
            layer = QgsVectorLayer(inputLayer, inputLayer, "ogr")
            vectorlayer_vector = layer.dataProvider()
            layer_mask = QgsVectorLayer(inputMask, inputMask, "ogr")
            vectorlayer_mask = layer_mask.dataProvider()
            # mask extent
            extent_rect = vectorlayer_mask.extent()
            xmin = extent_rect.xMinimum()
            xmax = extent_rect.xMaximum()
            ymin = extent_rect.yMinimum()
            ymax = extent_rect.yMaximum()
            extent = str(xmin) + "," + str(xmax) + "," + str(ymin) + "," + str(
                ymax)
            # attribute
            Elevation = self.lineAttrib.currentText()
            # cellsize
            cellSize = int(self.linePix.value())
            outPath = self.inputLayerCombo3.text()
            # size of atributte table == number of points
            count = layer.featureCount()

            # points interpolation idw
            if self.comboBoxMethod.currentText(
            ) == "Inverse Distance Weighting":
                Processing.initialize()
                # grid directory (qgis2)
                idw_interpolation = QFileInfo(
                    QgsApplication.qgisUserDbFilePath()).path(
                    ) + "/idw_interpolation"
                Processing.runAlgorithm("grass:v.surf.idw", None, inputLayer,
                                        count, 2.0, Elevation, False, extent,
                                        cellSize, -1.0, 0.0001,
                                        idw_interpolation)
                idw_int = idw_interpolation + "." + "tif"

                int_mask = QFileInfo(
                    QgsApplication.qgisUserDbFilePath()).path() + "/int_mask"
                # clip grid(interpolation) with polygon (mask)
                Processing.runAlgorithm("saga:clipgridwithpolygon", None,
                                        idw_int, inputMask, int_mask)
                int_mask_zone = int_mask + "." + "tif"

            # indexes for topography
            numberRows = int(self.tableWidget.rowCount())
            numberColumns = int(self.tableWidget.columnCount())
            classes = ''
            lista = []
            for i in range(0, numberRows):
                for j in range(0, numberColumns):
                    self.line = self.tableWidget.item(i, j)
                    lista = lista + [str(self.line.text())]
                    string = ","
                    intervalos = string.join(lista)

            # reclassify idw interpolation
            if self.comboBoxMethod.currentText(
            ) == "Inverse Distance Weighting":
                idw_reclassify = QFileInfo(QgsApplication.qgisUserDbFilePath()
                                           ).path() + "/idw_reclassify"
                Processing.runAlgorithm("saga:reclassifygridvalues", None,
                                        int_mask_zone, 2, 0.0, 1.0, 0, 0.0,
                                        1.0, 2.0, 0, intervalos, 0, True, 0.0,
                                        True, 0.0, outPath)

                # add result into canvas
                file_info = QFileInfo(outPath)
                if file_info.exists():
                    layer_name = file_info.baseName()
                else:
                    return False
                rlayer_new = QgsRasterLayer(outPath, layer_name)
                if rlayer_new.isValid():
                    QgsMapLayerRegistry.instance().addMapLayer(rlayer_new)
                    layer = QgsMapCanvasLayer(rlayer_new)
                    layerList = [layer]
                    extent = self.iface.canvas.setExtent(rlayer_new.extent())
                    self.iface.canvas.setLayerSet(layerList)
                    self.iface.canvas.setVisible(True)
                    return True
                else:
                    return False

            # points interpolation kriging
            if self.comboBoxMethod.currentText() == "Kriging":
                Processing.initialize()
                # grid directory (qgis2)
                kriging_interpolation = QFileInfo(
                    QgsApplication.qgisUserDbFilePath()).path(
                    ) + "/kriging_interpolation"
                Processing.runAlgorithm("saga:ordinarykrigingglobal", None,
                                        inputLayer, Elevation, True, 0, 1,
                                        False, 100, False, 0.0, 10, 1000, 1.0,
                                        0.1, 1.0, 0.5, cellSize, True, extent,
                                        kriging_interpolation, None)
                kriging_int = kriging_interpolation + "." + "tif"

                int_mask_kriging = QFileInfo(QgsApplication.qgisUserDbFilePath(
                )).path() + "/int_mask_kriging"
                # clip grid(interpolation) with polygon (mask)
                Processing.runAlgorithm("saga:clipgridwithpolygon", None,
                                        kriging_int, inputMask,
                                        int_mask_kriging)
                int_mask_zone_k = int_mask_kriging + "." + "tif"

                kriging_reclassify = QFileInfo(
                    QgsApplication.qgisUserDbFilePath()).path(
                    ) + "/kriging_reclassify"
                Processing.runAlgorithm("saga:reclassifygridvalues", None,
                                        int_mask_zone_k, 2, 0.0, 1.0, 0, 0.0,
                                        1.0, 2.0, 0, intervalos, 0, True, 0.0,
                                        True, 0.0, outPath)

                # add result into canvas
                file_info_k = QFileInfo(outPath)
                if file_info_k.exists():
                    layer_name_k = file_info_k.baseName()
                else:
                    return False
                rlayer_new_k = QgsRasterLayer(outPath, layer_name_k)
                if rlayer_new_k.isValid():
                    QgsMapLayerRegistry.instance().addMapLayer(rlayer_new_k)
                    layer_k = QgsMapCanvasLayer(rlayer_new_k)
                    layerList_k = [layer_k]
                    extent_k = self.iface.canvas.setExtent(
                        rlayer_new_k.extent())
                    self.iface.canvas.setLayerSet(layerList_k)
                    self.iface.canvas.setVisible(True)
                    return True
                else:
                    return False

                # points interpolation cubic spline
            if self.comboBoxMethod.currentText(
            ) == "Cubic spline approximation (SAGA)":
                Processing.initialize()
                # grid directory (qgis2)
                cubicSpline_interpolation = QFileInfo(
                    QgsApplication.qgisUserDbFilePath()).path(
                    ) + "/cubicSpline_interpolation"
                Processing.runAlgorithm("saga:cubicsplineapproximation", None,
                                        inputLayer, Elevation, 0, 3, count, 5,
                                        140.0, extent, cellSize,
                                        cubicSpline_interpolation)
                cubicSpline_int = cubicSpline_interpolation + "." + "tif"

                int_mask_cubicSpline = QFileInfo(
                    QgsApplication.qgisUserDbFilePath()).path(
                    ) + "/int_mask_cubicSpline"
                # clip grid(interpolation) with polygon (mask)
                Processing.runAlgorithm("saga:clipgridwithpolygon", None,
                                        cubicSpline_int, inputMask,
                                        int_mask_cubicSpline)
                int_mask_zone_cs = int_mask_cubicSpline + "." + "tif"

                cubicSpline_reclassify = QFileInfo(
                    QgsApplication.qgisUserDbFilePath()).path(
                    ) + "/cubicSpline_reclassify"
                Processing.runAlgorithm("saga:reclassifygridvalues", None,
                                        int_mask_zone_cs, 2, 0.0, 1.0, 0, 0.0,
                                        1.0, 2.0, 0, intervalos, 0, True, 0.0,
                                        True, 0.0, outPath)

                # add result into canvas
                file_info_cs = QFileInfo(outPath)
                if file_info_cs.exists():
                    layer_name_cs = file_info_cs.baseName()
                else:
                    return False
                rlayer_new_cs = QgsRasterLayer(outPath, layer_name_cs)
                if rlayer_new_cs.isValid():
                    QgsMapLayerRegistry.instance().addMapLayer(rlayer_new_cs)
                    layer_cs = QgsMapCanvasLayer(rlayer_new_cs)
                    layerList_cs = [layer_cs]
                    extent_cs = self.iface.canvas.setExtent(
                        rlayer_new_cs.extent())
                    self.iface.canvas.setLayerSet(layerList_cs)
                    self.iface.canvas.setVisible(True)
                    return True
                else:
                    return False

            if self.comboBoxMethod.currentText(
            ) == "Spatial approximation using spline with tension (GRASS)":
                Processing.initialize()
                # grid directory (qgis2)
                rst_interpolation = QFileInfo(
                    QgsApplication.qgisUserDbFilePath()).path(
                    ) + "/rst_interpolation"
                Processing.runAlgorithm("grass:v.surf.rst", None, inputLayer,
                                        "", None, Elevation, 40, 40, 300,
                                        0.001, 2.5, 1, 0, 0, False, False,
                                        extent, cellSize, -1, 0.0001,
                                        rst_interpolation, None, None, None,
                                        None, None)
                rst_int = rst_interpolation + "." + "tif"

                int_mask_rst = QFileInfo(QgsApplication.qgisUserDbFilePath()
                                         ).path() + "/int_mask_rst"
                # clip grid(interpolation) with polygon (mask)
                Processing.runAlgorithm("saga:clipgridwithpolygon", None,
                                        rst_int, inputMask, int_mask_rst)
                int_mask_zone_rst = int_mask_rst + "." + "tif"

                rst_reclassify = QFileInfo(QgsApplication.qgisUserDbFilePath()
                                           ).path() + "/rst_reclassify"
                Processing.runAlgorithm("saga:reclassifygridvalues", None,
                                        int_mask_zone_rst, 2, 0.0, 1.0, 0, 0.0,
                                        1.0, 2.0, 0, intervalos, 0, True, 0.0,
                                        True, 0.0, outPath)

                # add result into canvas
                file_info_rst = QFileInfo(outPath)
                if file_info_rst.exists():
                    layer_name_rst = file_info_rst.baseName()
                else:
                    return False
                rlayer_new_rst = QgsRasterLayer(outPath, layer_name_rst)
                if rlayer_new_rst.isValid():
                    QgsMapLayerRegistry.instance().addMapLayer(rlayer_new_rst)
                    layer_rst = QgsMapCanvasLayer(rlayer_new_rst)
                    layerList_rst = [layer_rst]
                    extent_rst = self.iface.canvas.setExtent(
                        rlayer_new_rst.extent())
                    self.iface.canvas.setLayerSet(layerList_rst)
                    self.iface.canvas.setVisible(True)
                    return True
                else:
                    return False

    # ----------------------- SECOND RASTER ----------------------------------------------------------------------------------------
        if self.inputLayerCombo_mdt != "":
            outPath2 = self.inputLayerCombo3.text()
            # read raster
            inputRaster = self.inputLayerCombo_mdt.currentText()
            layer_raster = QgsRasterLayer(inputRaster, inputRaster, "gdal")
            data_mdt = layer_raster.dataProvider()
            extent_raster = data_mdt.extent()
            xmin_raster = extent_raster.xMinimum()
            xmax_raster = extent_raster.xMaximum()
            ymin_raster = extent_raster.yMinimum()
            ymax_raster = extent_raster.yMaximum()
            extent_raster_str = str(xmin_raster) + "," + str(
                xmax_raster) + "," + str(ymin_raster) + "," + str(ymax_raster)
            cellSize = layer_raster.rasterUnitsPerPixelX()

            # read maximum depth
            max_depth = self.line_max.value()
            # read distance
            distance = self.line_distance.value()
            # minimum size
            size = self.line_size.value()

            Processing.initialize()
            # grid directory (qgis2)
            # generate stream segments
            stream = QFileInfo(
                QgsApplication.qgisUserDatabaseFilePath()).path() + "/stream"
            Processing.runAlgorithm(
                "grass7:r.watershed", {
                    'elevation': inputRaster,
                    'depression': None,
                    'flow': None,
                    'disturbed_land': None,
                    'blocking': None,
                    'threshold': size,
                    'max_slope_length': None,
                    'convergence': 5,
                    'memory': 300,
                    '-s': False,
                    '-m': False,
                    '-4': False,
                    '-a': False,
                    '-b': False,
                    'accumulation': None,
                    'drainage': None,
                    'basin': None,
                    'stream': stream,
                    'half_basin': None,
                    'length_slope': None,
                    'slope_steepness': None,
                    'tci': None,
                    'spi': None,
                    'GRASS_REGION_PARAMETER':
                    extent_raster_str + '[EPSG:3763]',
                    'GRASS_REGION_CELLSIZE_PARAMETER': cellSize,
                    'GRASS_RASTER_FORMAT_OPT': '',
                    'GRASS_RASTER_FORMAT_META': ''
                })

            # condition stream > 1 to have the lines with value 1
            stream_ones = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()
                                    ).path() + "/stream_ones"

            Processing.runAlgorithm(
                "gdal:rastercalculator", {
                    'INPUT_A': stream,
                    'BAND_A': 1,
                    'INPUT_B': None,
                    'BAND_B': -1,
                    'INPUT_C': None,
                    'BAND_C': -1,
                    'INPUT_D': None,
                    'BAND_D': -1,
                    'INPUT_E': None,
                    'BAND_E': -1,
                    'INPUT_F': None,
                    'BAND_F': -1,
                    'FORMULA': "A>1",
                    'NO_DATA': None,
                    'RTYPE': 5,
                    'EXTRA': '',
                    'OPTIONS': '',
                    'OUTPUT': stream_ones
                })

            # raster distance
            raster_distance = QFileInfo(
                QgsApplication.qgisUserDatabaseFilePath()).path(
                ) + "/raster_distance.sdat"

            Processing.runAlgorithm(
                "gdal:proximity", {
                    'INPUT': str(stream_ones),
                    'BAND': 1,
                    'VALUES': '1',
                    'UNITS': 0,
                    'MAX_DISTANCE': 0,
                    'REPLACE': 0,
                    'NODATA': 0,
                    'OPTIONS': '',
                    'DATA_TYPE': 5,
                    'OUTPUT': str(raster_distance)
                })
            # condition distance >=  200, always maximum depth meters
            dist_major_200 = QFileInfo(QgsApplication.qgisUserDatabaseFilePath(
            )).path() + "/dist_major_200"

            Processing.runAlgorithm(
                "gdal:rastercalculator", {
                    'INPUT_A': raster_distance,
                    'BAND_A': 1,
                    'INPUT_B': None,
                    'BAND_B': -1,
                    'INPUT_C': None,
                    'BAND_C': -1,
                    'INPUT_D': None,
                    'BAND_D': -1,
                    'INPUT_E': None,
                    'BAND_E': -1,
                    'INPUT_F': None,
                    'BAND_F': -1,
                    'FORMULA': "A>=" + str(distance),
                    'NO_DATA': None,
                    'RTYPE': 5,
                    'EXTRA': '',
                    'OPTIONS': '',
                    'OUTPUT': dist_major_200
                })

            dist_multiplication = QFileInfo(
                QgsApplication.qgisUserDatabaseFilePath()).path(
                ) + "/dist_multiplication"

            Processing.runAlgorithm(
                "gdal:rastercalculator", {
                    'INPUT_A': dist_major_200,
                    'BAND_A': 1,
                    'INPUT_B': None,
                    'BAND_B': -1,
                    'INPUT_C': None,
                    'BAND_C': -1,
                    'INPUT_D': None,
                    'BAND_D': -1,
                    'INPUT_E': None,
                    'BAND_E': -1,
                    'INPUT_F': None,
                    'BAND_F': -1,
                    'FORMULA': "A*" + str(max_depth),
                    'NO_DATA': None,
                    'RTYPE': 5,
                    'EXTRA': '',
                    'OPTIONS': '',
                    'OUTPUT': dist_multiplication
                })

            # condition distance < 200, inteprolation between 0 and maximum depth
            dist_minor_200 = QFileInfo(QgsApplication.qgisUserDatabaseFilePath(
            )).path() + "/dist_minor_200"

            Processing.runAlgorithm(
                "gdal:rastercalculator", {
                    'INPUT_A': raster_distance,
                    'BAND_A': 1,
                    'INPUT_B': None,
                    'BAND_B': -1,
                    'INPUT_C': None,
                    'BAND_C': -1,
                    'INPUT_D': None,
                    'BAND_D': -1,
                    'INPUT_E': None,
                    'BAND_E': -1,
                    'INPUT_F': None,
                    'BAND_F': -1,
                    'FORMULA': "A<" + str(distance),
                    'NO_DATA': None,
                    'RTYPE': 5,
                    'EXTRA': '',
                    'OPTIONS': '',
                    'OUTPUT': dist_minor_200
                })

            # multiplication by the raster distance
            dist_multiplication_dist = QFileInfo(
                QgsApplication.qgisUserDatabaseFilePath()).path(
                ) + "/dist_multiplication_dist"

            Processing.runAlgorithm(
                "gdal:rastercalculator", {
                    'INPUT_A': dist_minor_200,
                    'BAND_A': 1,
                    'INPUT_B': raster_distance,
                    'BAND_B': 1,
                    'INPUT_C': None,
                    'BAND_C': -1,
                    'INPUT_D': None,
                    'BAND_D': -1,
                    'INPUT_E': None,
                    'BAND_E': -1,
                    'INPUT_F': None,
                    'BAND_F': -1,
                    'FORMULA': "A*B",
                    'NO_DATA': None,
                    'RTYPE': 5,
                    'EXTRA': '',
                    'OPTIONS': '',
                    'OUTPUT': dist_multiplication_dist
                })

            # interpolation between 0 and distance
            interpolation_dist = QFileInfo(
                QgsApplication.qgisUserDatabaseFilePath()).path(
                ) + "/interpolation_dist"

            Processing.runAlgorithm(
                "gdal:rastercalculator", {
                    'INPUT_A': dist_multiplication_dist,
                    'BAND_A': 1,
                    'INPUT_B': None,
                    'BAND_B': -1,
                    'INPUT_C': None,
                    'BAND_C': -1,
                    'INPUT_D': None,
                    'BAND_D': -1,
                    'INPUT_E': None,
                    'BAND_E': -1,
                    'INPUT_F': None,
                    'BAND_F': -1,
                    'FORMULA': "A*" + str(max_depth) + "/" + str(distance),
                    'NO_DATA': None,
                    'RTYPE': 5,
                    'EXTRA': '',
                    'OPTIONS': '',
                    'OUTPUT': interpolation_dist
                })

            # depth surface = sum of two conditions
            depth_surface = QFileInfo(QgsApplication.qgisUserDatabaseFilePath(
            )).path() + "/depth_surface"

            Processing.runAlgorithm(
                "gdal:rastercalculator", {
                    'INPUT_A': dist_multiplication,
                    'BAND_A': 1,
                    'INPUT_B': interpolation_dist,
                    'BAND_B': 1,
                    'INPUT_C': None,
                    'BAND_C': -1,
                    'INPUT_D': None,
                    'BAND_D': -1,
                    'INPUT_E': None,
                    'BAND_E': -1,
                    'INPUT_F': None,
                    'BAND_F': -1,
                    'FORMULA': "A+B",
                    'NO_DATA': None,
                    'RTYPE': 5,
                    'EXTRA': '',
                    'OPTIONS': '',
                    'OUTPUT': depth_surface
                })

            # indexes for topography
            numberRows = int(self.tableWidget.rowCount())
            numberColumns = int(self.tableWidget.columnCount())
            classes = ''
            lista = []
            for i in range(0, numberRows):
                for j in range(0, numberColumns):
                    self.line = self.tableWidget.item(i, j)
                    lista = lista + [str(self.line.text())]
                    string = ","
                    intervalos = string.join(lista)
            results = list(map(float, lista))

            depth_reclassify = QFileInfo(
                QgsApplication.qgisUserDatabaseFilePath()).path(
                ) + "/depth_reclassify.sdat"
            Processing.runAlgorithm(
                "saga:reclassifyvalues", {
                    'INPUT': depth_surface,
                    'METHOD': 2,
                    'OLD': 0,
                    'NEW': 1,
                    'SOPERATOR': 0,
                    'MIN': 0,
                    'MAX': 1,
                    'RNEW': 2,
                    'ROPERATOR': 0,
                    'RETAB': results,
                    'TOPERATOR': 0,
                    'NODATAOPT': True,
                    'NODATA': 0,
                    'OTHEROPT': True,
                    'OTHERS': 0,
                    'RESULT': outPath2
                })

            #Processing.runAlgorithm("grass:r.surf.idw", None, depth_reclassify, 12, False, extent_raster_str, cellSize, outPath2)

            # add result into canvas
            # add result into canvas
            file_info_norm = QFileInfo(str(outPath2))
            # QMessageBox.about(self, "teste", str(file_info_norm))
            rlayer_new_norm = QgsRasterLayer(outPath2,
                                             file_info_norm.fileName(), 'gdal')
            # QMessageBox.about(self, "teste", str(rlayer_new_norm))
            QgsProject.instance().addMapLayer(rlayer_new_norm)
            self.iface.canvas.setExtent(rlayer_new_norm.extent())
            # set the map canvas layer set
            self.iface.canvas.setLayers([rlayer_new_norm])

            # file_info_norm = QFileInfo(outPath2)
            # if file_info_norm.exists():
            #     layer_name_norm = file_info_norm.baseName()
            # else:
            #     return False
            # rlayer_new_norm = QgsRasterLayer(outPath2, layer_name_norm)
            # if rlayer_new_norm.isValid():
            #     QgsMapLayerRegistry.instance().addMapLayer(rlayer_new_norm)
            #     layer_norm = QgsMapCanvasLayer(rlayer_new_norm)
            #     layerList_norm = [layer_norm]
            #     extent_norm = self.iface.canvas.setExtent(rlayer_new_norm.extent())
            #     self.iface.canvas.setLayerSet(layerList_norm)
            #     self.iface.canvas.setVisible(True)
            #     return True
            # else:
            #     return False

        QMessageBox.information(self, self.tr("Finished"),
                                self.tr("Depth completed."))
        self.buttonBox.button(QDialogButtonBox.Ok).setDefault(True)
示例#58
0
    def layout(self):
        # ___Create composition___
        # composition
        layerset = []
        # QgsMapLayerRegistry.instance().addMapLayer(RUSLE_color_raster)
        Processing.initialize()
        # reproject layer from 3857 to epsg 3763
        # layer_3763 = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/layer_3763.shp"
        # Processing.runAlgorithm("qgis:reprojectlayer",None,self.layer,"EPSG:3763",layer_3763)
        # layer_etrs89 = QgsVectorLayer(unicode(layer_3763).encode('utf8'), "Grande Porto", "ogr")
        # QgsMapLayerRegistry.instance().addMapLayer(layer_etrs89)

        canvas = iface.mapCanvas()
        layers = canvas.layers()
        # QMessageBox.about(self.dlg.checkBox, 'teste', str(layers))
        for l in layers:
            layerset.append(l.id())
            layer = l
            #QMessageBox.about(self.dlg.checkBox, 'teste', str(layer))

        if layer == None:
            QMessageBox.information(None, "WARNING",
                                    str('There is no shapefile.'))

        extent_rect = layer.extent()
        # QMessageBox.about(self.dlg.checkBox, 'teste', str(extent_rect))

        xmin = extent_rect.xMinimum()
        xmax = extent_rect.xMaximum()
        ymin = extent_rect.yMinimum()
        ymax = extent_rect.yMaximum()

        extent = QgsRectangle(xmin, ymin, xmax, ymax)
        # QMessageBox.about(self.dlg.checkBox, 'teste', str(extent))

        #self.symbology_graduated(layer)

        # layerset.append(layer_etrs89.id())

        myMap = QgsMapSettings()

        actual_crs = layer.crs()
        #QMessageBox.about(self.dlg, 'teste', str(actual_crs))
        # map_proj = QgsCoordinateReferenceSystem(3763, QgsCoordinateReferenceSystem.PostgisCrsId)
        myMap.setDestinationCrs(actual_crs)
        myMap.setLayers(layers)
        mapRectangle = myMap.fullExtent()
        # QMessageBox.about(self.dlg.checkBox, 'teste', str(mapRectangle.xMinimum()))
        # QMessageBox.about(self.dlg.checkBox, 'teste', str(mapRectangle.xMaximum()))
        # QMessageBox.about(self.dlg.checkBox, 'teste', str(mapRectangle.yMinimum()))
        xmin = mapRectangle.xMinimum() - 5000
        xmax = mapRectangle.xMaximum() + 2000

        # mapRectangle.scale(0.5)
        # myMap.setExtent(mapRectangle)
        myMap.setExtent(mapRectangle)
        # myMap.setOutputSize(QSize(700,300))
        myMap.setOutputSize(QSize(950, 500))

        #initialize a new print layout
        p = QgsProject.instance()
        myComposition = QgsLayout(p)
        myComposition.initializeDefaults()
        #myComposition.setPlotStyle(QgsComposition.Print)

        mapp = QgsLayoutItemMap(myComposition)
        mapp.setRect(20, 20, 20, 20)
        #myMap = QgsMapSettings()

        actual_crs = layer.crs()
        # QMessageBox.about(self.dlg, 'teste', str(actual_crs))
        # map_proj = QgsCoordinateReferenceSystem(3763, QgsCoordinateReferenceSystem.PostgisCrsId)
        mapp.setCrs(actual_crs)
        mapp.setLayers(layers)
        #mapRectangle = mapp.fullExtent()
        # QMessageBox.about(self.dlg.checkBox, 'teste', str(mapRectangle.xMinimum()))
        # QMessageBox.about(self.dlg.checkBox, 'teste', str(mapRectangle.xMaximum()))
        # QMessageBox.about(self.dlg.checkBox, 'teste', str(mapRectangle.yMinimum()))
        xmin = mapRectangle.xMinimum() - 5000
        xmax = mapRectangle.xMaximum() + 2000

        # mapRectangle.scale(0.5)
        # myMap.setExtent(mapRectangle)
        mapp.setExtent(mapRectangle)
        # myMap.setOutputSize(QSize(700,300))
        #mapp.setOutputSize(QSize(950, 500))
        myComposition.addItem(mapp)
        # myFile = str(self.plugin_dir) + '/template2.qpt'
        # myFile = str(self.plugin_dir) + '/template.qpt'

        # myTemplateFile = open(myFile, 'rt')
        # myTemplateContent = myTemplateFile.read()
        ####QMessageBox.about(self, "plano", myTemplateContent)
        # myTemplateFile.close()
        # myDocument = QtXml.QDomDocument()
        # myDocument.setContent(myTemplateContent)
        # myComposition.loadFromTemplate(myDocument)

        # x,y = 20,40
        x, y = 9, 9
        # paper A4
        # w,h = myComposition.paperWidth(), myComposition.paperHeight()
        #myComposition.setPaperSize(420, 297)
        # myComposition.setPaperSize(297,210)
        #w, h = myComposition.paperWidth(), myComposition.paperHeight()
        # QMessageBox.about(self.dlg.listWidget,'test', str(self.dlg.listWidget_4.currentItem().text()))
        # QMessageBox.about(self.dlg.checkBox,'test', str(h))
        # QMessageBox.about(self.dlg.checkBox,'test', str(w))
        # composerMap = QgsComposerMap(myComposition,x,y,w-30,h-70)
        # composerMap = QgsComposerMap(myComposition,x,y,w-121,h-114)
        # composerMap = QgsComposerMap(myComposition, x, y, w - 20, h - 27)
        # # composerMap.setNewExtent(extent)
        # # QMessageBox.about(self.dlg.checkBox, 'teste', str(composerMap.extent()))
        # composerMap.grid()
        # composerMap.grid().setGridLineWidth(0.1)
        # composerMap.grid().setIntervalX(10000)
        # composerMap.grid().setIntervalY(10000)
        # composerMap.grid().setAnnotationEnabled(True)
        # composerMap.grid().setAnnotationPosition(1, 0)
        # composerMap.grid().setAnnotationPosition(1, 1)
        # composerMap.grid().setAnnotationDirection(1, 0)
        # composerMap.grid().setAnnotationDirection(1, 1)
        # composerMap.grid().setFrameStyle(5)
        # myComposition.addComposerMap(composerMap)
        # composerMap.setLayerSet(myMap.layers())

        # legend
        legend = QgsLayoutItemLegend(myComposition)
        legend.setLinkedMap(mapp)
        # legend.model().setLayerSet(myMap.layers())
        # legend.model().setLayerSet
        myComposition.addItem(legend)
        # legend.displayName()
        # legend.setItemPosition(343.9, 239, 65.6, 25.9)
        # legend.setAutoUpdateModel(False)
        # legend.setLegendFilterByMapEnabled(True)
        # # QMessageBox.about(self.dlg.pushButton,'test', str(t))
        # legend.update()
        # legend.setItemPosition (100,122)
        # legend.setFrameEnabled(True)
        # legend.setScale(.7)

        # title
        title = QgsLayoutItemLabel(myComposition)
        # title.setText(str(self.dlg.listWidget_3.currentItem().text()))
        title.setText('PQI' + ' ' + str(self.dlg.comboBox.currentText()))
        title.setFont(QFont("Cambria", 40, QFont.Bold))
        #title.setItemPosition(140, 1)
        title.adjustSizeToText()
        # title.setMargin(-6)
        # title.setFrameEnabled(True)
        myComposition.addItem(title)

        # text_inf = "Prognostico" + "\n" + "Coordinate System: ETRS89 PTTM06" + '\n' + str(self.pr)
        # QMessageBox.about(self.dlg.listWidget,'test', str(text_inf))

        # information text
        # text = QgsComposerLabel(myComposition)
        # text.setText("Prognostico")
        # text.setFont(QFont("Cambria",15, QFont.Bold))
        # text.setItemPosition(328.2, 72.3, 87.7,102.3)
        # text.adjustSizeToText()
        ##title.setFrameEnabled(True)
        # myComposition.addItem(text)

        # arrow picture
        # pic_path = str(self.plugin_dir) + '/north.png'
        # pic = QgsComposerPicture(myComposition)
        # pic.setPictureFile(pic_path)
        # pic.setRotationMap(0)
        # pic.setSceneRect(QRectF(0, 0, 20, 20))
        # myComposition.addComposerPicture(pic)
        # pic.setItemPosition(2.2, 2.6)

        # attribute table
        # attr_table = QgsComposerAttributeTable(myComposition)
        # attr_table.setVectorLayer(layer_etrs89)
        # attr_table.setComposerMap(composerMap)
        # attr_table.setDisplayOnlyVisibleFeatures(True)
        # myComposition.addItem(attr_table)
        # attr_table.setItemPosition(330.7, 29.6, 77.5,24.7)

        # add scale bar
        item = QgsLayoutItemScaleBar(myComposition)
        item.setLinkedMap(mapp)
        myComposition.addItem(item)
        item.setStyle('Double Box')  # optionally modify the style
        # item.SegmentSizeMode('SegmentSizeFitWidth')
        #item.adjustBoxSize()
        # item.setNumSegments(4)
        item.setUnitLabel("km")
        # item.setNumMapUnitsPerScaleBarUnit(1)
        # item.setHeight(8)
        ##item.correctXPositionAlignment(10,10)
        item.applyDefaultSize()
        #item.setItemPosition(16.5, 256.4, 123.9, 20)
        item.update()

        # export layout
        # base_path = os.path.join(QgsProject.instance().homePath())
        # pdf_path = os.path.join(base_path, "output.pdf")
        output_jpeg = self.dlg.lineEdit.text()
        exporter = QgsLayoutExporter(myComposition)
        exporter.exportToPdf(output_jpeg,
                             QgsLayoutExporter.PdfExportSettings())

        #POSTGIS_DIR = "C:\Program Files\PostgreSQL/12/bin/pgsql2shp.exe"

        # myImage = myComposition.printPageAsRaster(0)
        # myImage.save(output_jpeg)

        QMessageBox.information(None, "Layout created:",
                                str("The layout was created"))
示例#59
0
    def accept(self):
        description = str(self.nameTextBox.text())
        if description.strip() == '':
            QMessageBox.warning(self, self.tr('Unable to define parameter'),
                                self.tr('Invalid parameter name'))
            return
        if self.param is None:
            validChars = \
                'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
            safeName = ''.join(c for c in description if c in validChars)
            name = safeName.lower()
            i = 2
            while self.alg.parameterDefinition(name):
                name = safeName.lower() + str(i)
                i += 1
        else:
            name = self.param.name()
        if (self.paramType == parameters.PARAMETER_BOOLEAN or
                isinstance(self.param, QgsProcessingParameterBoolean)):
            self.param = QgsProcessingParameterBoolean(name, description, self.state.isChecked())
        elif (self.paramType == parameters.PARAMETER_TABLE_FIELD or
              isinstance(self.param, QgsProcessingParameterField)):
            if self.parentCombo.currentIndex() < 0:
                QMessageBox.warning(self, self.tr('Unable to define parameter'),
                                    self.tr('Wrong or missing parameter values'))
                return
            parent = self.parentCombo.currentData()
            datatype = self.datatypeCombo.currentData()
            default = self.defaultTextBox.text()
            if not default:
                default = None
            self.param = QgsProcessingParameterField(name, description, defaultValue=default,
                                                     parentLayerParameterName=parent, type=datatype,
                                                     allowMultiple=self.multipleCheck.isChecked())
        elif (self.paramType == parameters.PARAMETER_BAND or
              isinstance(self.param, QgsProcessingParameterBand)):
            if self.parentCombo.currentIndex() < 0:
                QMessageBox.warning(self, self.tr('Unable to define parameter'),
                                    self.tr('Wrong or missing parameter values'))
                return
            parent = self.parentCombo.currentData()
            self.param = QgsProcessingParameterBand(name, description, None, parent)
        elif (self.paramType == parameters.PARAMETER_MAP_LAYER or
              isinstance(self.param, QgsProcessingParameterMapLayer)):
            self.param = QgsProcessingParameterMapLayer(
                name, description)
        elif (self.paramType == parameters.PARAMETER_RASTER or
              isinstance(self.param, QgsProcessingParameterRasterLayer)):
            self.param = QgsProcessingParameterRasterLayer(
                name, description)
        elif (self.paramType == parameters.PARAMETER_TABLE or
              isinstance(self.param, QgsProcessingParameterVectorLayer)):
            self.param = QgsProcessingParameterVectorLayer(
                name, description,
                [self.shapetypeCombo.currentData()])
        elif (self.paramType == parameters.PARAMETER_VECTOR or
              isinstance(self.param, QgsProcessingParameterFeatureSource)):
            self.param = QgsProcessingParameterFeatureSource(
                name, description,
                [self.shapetypeCombo.currentData()])
        elif (self.paramType == parameters.PARAMETER_MULTIPLE or
              isinstance(self.param, QgsProcessingParameterMultipleLayers)):
            self.param = QgsProcessingParameterMultipleLayers(
                name, description,
                self.datatypeCombo.currentData())
        elif (self.paramType == parameters.PARAMETER_NUMBER or
              isinstance(self.param, QgsProcessingParameterNumber)):
            try:
                self.param = QgsProcessingParameterNumber(name, description, QgsProcessingParameterNumber.Double,
                                                          self.defaultTextBox.text())
                vmin = self.minTextBox.text().strip()
                if not vmin == '':
                    self.param.setMinimum(float(vmin))
                vmax = self.maxTextBox.text().strip()
                if not vmax == '':
                    self.param.setMaximum(float(vmax))
            except:
                QMessageBox.warning(self, self.tr('Unable to define parameter'),
                                    self.tr('Wrong or missing parameter values'))
                return
        elif (self.paramType == parameters.PARAMETER_EXPRESSION or
              isinstance(self.param, QgsProcessingParameterExpression)):
            parent = self.parentCombo.currentData()
            self.param = QgsProcessingParameterExpression(name, description,
                                                          str(self.defaultEdit.expression()),
                                                          parent)
        elif (self.paramType == parameters.PARAMETER_STRING or
              isinstance(self.param, QgsProcessingParameterString)):
            self.param = QgsProcessingParameterString(name, description,
                                                      str(self.defaultTextBox.text()))
        elif (self.paramType == parameters.PARAMETER_EXTENT or
              isinstance(self.param, QgsProcessingParameterExtent)):
            self.param = QgsProcessingParameterExtent(name, description)
        elif (self.paramType == parameters.PARAMETER_FILE or
              isinstance(self.param, QgsProcessingParameterFile)):
            isFolder = self.fileFolderCombo.currentIndex() == 1
            self.param = QgsProcessingParameterFile(name, description,
                                                    QgsProcessingParameterFile.Folder if isFolder else QgsProcessingParameterFile.File)
        elif (self.paramType == parameters.PARAMETER_POINT or
              isinstance(self.param, QgsProcessingParameterPoint)):
            self.param = QgsProcessingParameterPoint(name, description,
                                                     str(self.defaultTextBox.text()))
        elif (self.paramType == parameters.PARAMETER_CRS or
              isinstance(self.param, QgsProcessingParameterCrs)):
            self.param = QgsProcessingParameterCrs(name, description, self.selector.crs().authid())
        else:
            from processing.core.Processing import Processing

            param = Processing.registeredParameters()[self.paramType]

            self.param = param['parameter'](name, description, None)
            self.param.setMetadata(param['metadata'])

        if not self.requiredCheck.isChecked():
            self.param.setFlags(self.param.flags() | QgsProcessingParameterDefinition.FlagOptional)

        settings = QgsSettings()
        settings.setValue("/Processing/modelParametersDefinitionDialogGeometry", self.saveGeometry())

        QDialog.accept(self)
示例#60
0
    def symbology_categorized(self, layer):

        # connect to PostGIS database with the municipalities and the data table
        layer = iface.activeLayer()
        uri = QgsDataSourceUri()
        uri.setConnection("localhost", "5432", "MED", "postgres", "postgres")
        uri.setDataSource("public", "distritos2", "geom", '', "gid")

        # now query the table
        db = QSqlDatabase.addDatabase("QPSQL")
        db.setDatabaseName(uri.database())
        db.setPort(int(uri.port()))
        db.setUserName(uri.username())
        db.setPassword(uri.password())
        # QMessageBox.about(self.dlg.checkBox, 'teste', str(uri.database()))
        # QMessageBox.about(self.dlg.checkBox, 'teste', str(uri.port()))
        # QMessageBox.about(self.dlg.checkBox, 'teste', str(uri.username()))
        # QMessageBox.about(self.dlg.checkBox, 'teste', str(uri.password()))
        db.open()

        # get attribute
        attribute = self.dlg.comboBox.currentText()
        # get values from attribute
        # n = len(self.field_names)
        # lista_attrib = []
        # for i in range(0,n):
        # f = self.field_names[i]
        # if f==str(attribute):
        # number = i
        # for feat in layer.getFeatures():
        # attrb = feat.attributes()
        # attribute_read = attrb[number] #reads the attribute one by one
        # lista_attrib = lista_attrib + [str(attribute_read)]
        # lista_attributes = lista_attrib
        ## list without duplicates
        # woduplicates = list(set(lista_attributes))
        #QMessageBox.about(self.dlg.checkBox, 'teste', str(attribute))

        if attribute == 'ANO':
            if self.ANO is None:
                self.ANO = year_attrib()
            self.ANO.show()

            # create tuple with the colors and the fields
        # list_color = ["yellow", "darkcyan", "red", "grey"]
        ##list_fields = woduplicates
        # list_fields = ['1', '2', '6', " "]
        # dicti = {'1':('yellow','1'), '2':('darkcyan','2'), '6':('red', '6'), '':("grey", ' ')}
        # tuples = zip(list_color, list_fields)
        ## get attributes
        # attrb = woduplicates
        ## create dict with the tuples and the attributes
        # attribute_sym = dict(zip(attrb, tuples))
        # QMessageBox.about(self.dlg.checkBox, 'teste', str(attribute_sym))
        ## symbolize
        # categories = []

        ## get default style
        # myStyle = QgsStyleV2().defaultStyle()
        ##QMessageBox.about(self.dlg.checkBox, 'teste', str(myStyle))
        ### get a list of default color ramps [u'Blues', u'BrBG', u'BuGn'....]
        # defaultColorRampNames = myStyle.colorRampNames()
        ##QMessageBox.about(self.dlg.checkBox, 'teste', str(defaultColorRampNames))
        ### setting ramp to Blues, first index of defaultColorRampNames
        # ramp = myStyle.colorRamp(defaultColorRampNames[0])
        ##pr = ramp.properties()
        ##QMessageBox.about(self.dlg.checkBox, 'teste', str(pr))
        ## set up an empty categorized renderer and assign the color ramp
        # self.field = self.dlg.comboBox.currentText()
        # renderer = QgsCategorizedSymbolRendererV2(self.field, [])
        # renderer.setSourceColorRamp(ramp)
        # layer.setRendererV2(renderer)

        # converter string para numeric
        #subprocess.call('ALTER TABLE sample_reside_join ALTER COLUMN totdias TYPE integer USING (trim(totdias)::integer);')

        # subprocess.call('"C:\Program Files\PostgreSQL/12/bin/pgsql2shp.exe" -f ' + '"C:\Users\Lia\Desktop/categorized.shp" ' + '-h localhost -p 5432 -u postgres -P postgres LIA ' + '"SELECT freguesia, mode(ADM_TIP), geom FROM grande_porto LEFT OUTER JOIN sample_reside_join ON grande_porto.dicofre = sample_reside_join.reside GROUP BY freguesia, geom ORDER BY freguesia"')

        shape = QFileInfo(
            QgsApplication.qgisUserDatabaseFilePath()).path() + "/result.shp"
        subprocess.call(
            '"C:\Program Files\PostgreSQL/12/bin/pgsql2shp.exe" -f ' + '"' +
            str(shape) + '" ' + '-h localhost -p ' + str(uri.port()) + ' -u ' +
            str(uri.username()) + ' -P ' + str(uri.password()) + ' ' +
            str(uri.database()) + ' "SELECT freguesia, sum(' + str(attribute) +
            '), geom FROM grande_porto LEFT OUTER JOIN sample_reside_join ON grande_porto.dicofre = sample_reside_join.reside GROUP BY freguesia, geom ORDER BY freguesia"'
        )
        # subprocess.call('"C:\Program Files\PostgreSQL/12/bin/pgsql2shp.exe" -f ' + '"C:\Users\Lia\Desktop/categorized2.shp" ' + '-h localhost -p 5432 -u postgres -P postgres LIA ' + '"SELECT freguesia,(cnt_2/total::float)*100 perc_adm FROM (SELECT freguesia, count(*) total, sum(CASE WHEN adm_tip::integer = 2 THEN 1 ELSE 0 END) cnt_2, geom FROM grande_porto LEFT OUTER JOIN sample_reside_join ON grande_porto.dicofre = sample_reside_join.reside GROUP BY freguesia, geom) x ORDER BY freguesia"')
        #QMessageBox.about(self.dlg.checkBox, 'teste',
        # '"C:\Program Files\PostgreSQL/12/bin/pgsql2shp.exe" -f ' + '"' + str(
        #     shape) + '" ' + '-h localhost -p ' + str(uri.port()) + ' -u ' + str(
        #     uri.username()) + ' -P ' + str(uri.password()) + str(
        #     uri.database()) + ' "SELECT freguesia, mode(' + str(
        #     attribute) + '), geom FROM grande_porto LEFT OUTER JOIN sample_reside_join ON grande_porto.dicofre = sample_reside_join.reside GROUP BY freguesia, geom ORDER BY freguesia"')

        # vdlayer = QgsVectorLayer(unicode("C:\Users\Lia\Desktop/categorized.shp").encode('utf8'), "average", "ogr")
        vdlayer = QgsVectorLayer(str(shape), "average", "ogr")
        fields_at = vdlayer.fields()
        self.field_names_at = fields_at.names()
        #QMessageBox.about(self.dlg.checkBox, 'teste', str(self.field_names_at))
        mode = self.field_names_at[1]
        # get values from attribute
        n = len(self.field_names_at)
        # QMessageBox.about(self.dlg.checkBox, 'teste', str(n))
        lista_attrib = []
        for i in range(0, n):
            f = self.field_names_at[i]
            # QMessageBox.about(self.dlg.checkBox, 'teste', str(f))
            if f == 'MODE':
                #QMessageBox.about(self.dlg.checkBox, 'teste', str(f))
                number = i
                for feat in vdlayer.getFeatures():
                    attrb = feat.attributes()
                    QMessageBox.about(self.dlg.checkBox, 'teste', str(attrb))
                    attribute_read = attrb[
                        number]  # reads the attribute one by one
                    lista_attrib = lista_attrib + [str(attribute_read)]
        lista_attributes = lista_attrib
        #QMessageBox.about(self.dlg.checkBox, 'teste', str(lista_attributes))
        # list without duplicates
        woduplicates = list(set(lista_attributes))
        # QMessageBox.about(self.dlg.checkBox, 'teste', str(woduplicates))
        for index, ii in enumerate(woduplicates):
            if ii == 'NULL':
                woduplicates[index] = ' '

        # QMessageBox.about(self.dlg.checkBox, 'teste', str(woduplicates))

        # 'SELECT freguesia, adm_tip, CASE WHEN adm_tip='2' THEN count(adm_tip)/17::float*100 ELSE 0 END FROM grande_porto LEFT OUTER JOIN sample_reside_join ON grande_porto.dicofre = sample_reside_join.reside GROUP BY freguesia, adm_tip ORDER BY freguesia'

        # create tuple with the colors and the fields
        list_color = ["yellow", "darkcyan", "red", "grey"]
        # list_fields = woduplicates
        # list_fields = ['1', '2', '6', " "]
        # dicti = {'1':('yellow','1'), '2':('darkcyan','2'), '6':('red', '6'), '':("grey", ' ')}
        tuples = zip(list_color, woduplicates)
        # create dict with the tuples and the attributes
        attribute_sym = dict(zip(woduplicates, tuples))
        # QMessageBox.about(self.dlg.checkBox, 'teste', str(attribute_sym))
        # symbolize
        categories = []

        for code, (color, fields) in attribute_sym.items():
            sym = QgsSymbol.defaultSymbol(vdlayer.geometryType())
            sym.setColor(QColor(color))
            category = QgsRendererCategory(code, sym, fields)
            categories.append(category)
        # QMessageBox.about(self.dlg.checkBox, 'teste', str(categories))
        # self.field = self.dlg.comboBox.currentText()
        renderer = QgsCategorizedSymbolRenderer('MODE', categories)
        # renderer.setSourceColorRamp(ramp)
        vdlayer.setRenderer(renderer)
        # layer.setRendererV2(renderer)
        QgsProject.instance().addMapLayer(vdlayer)
        self.canvas = QgsMapCanvas()
        # self.canvas.scene().addItem(vdlayer)
        QgsProject.instance().addMapLayer(vdlayer)

        # self.canvas = QgsMapCanvas()
        # self.canvas.setExtent(layer.extent())
        # self.canvas.setLayerSet( [ QgsMapCanvasLayer(layer) ] )
        # self.setCentralWidget(self.canvas)

        if self.dlg.checkBox_2.isChecked():
            Processing.initialize()
            layer_limit = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()
                                    ).path() + "/layer_limit.shp"
            # QMessageBox.about(self.dlg.checkBox, 'teste', str(layer.source()))
            Processing.runAlgorithm("qgis:dissolve", None, layer, True, "None",
                                    layer_limit)
            l_limit = QgsVectorLayer(
                unicode(layer_limit).encode('utf8'), "layer_limit", "ogr")
            QgsMapLayerRegistry.instance().addMapLayer(l_limit)