def setUpClass(cls):
        start_app()
        from processing.core.Processing import Processing
        Processing.initialize()
        cls.cleanup_paths = []

        assert Grass7Utils.installedVersion()
Exemple #2
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'))
Exemple #3
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 = {}
Exemple #4
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)
Exemple #5
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()
 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 = {}
 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()
Exemple #8
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 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()
        Processing.updateAlgsList()

        output_vector = processing.runalg(
                'gdalogr:contour',
                raster_layer,
                interval,
                'minutes',
                None,
                '[temporary_file]')

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

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

    return drivetime_layer
Exemple #10
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.drop_handler = ProcessingDropHandler()
     iface.registerCustomDropHandler(self.drop_handler)
     self.item_provider = ProcessingDataItemProvider()
     QgsApplication.dataItemProviderRegistry().addProvider(self.item_provider)
     self.locator_filter = AlgorithmLocatorFilter()
     iface.registerLocatorFilter(self.locator_filter)
     Processing.initialize()
Exemple #11
0
 def setUpClass(cls):
     start_app()
     from processing.core.Processing import Processing
     Processing.initialize()
     ProcessingConfig.setSettingValue("OTB_ACTIVATE", True)
     ProcessingConfig.setSettingValue(OtbSettings.FOLDER, OTB_INSTALL_DIR)
     ProcessingConfig.setSettingValue(OtbSettings.APP_FOLDER, os.path.join(OTB_INSTALL_DIR, 'lib', 'otb', 'applications'))
     ProcessingConfig.readSettings()
     # Refresh OTB Algorithms after settings are changed.
     for p in QgsApplication.processingRegistry().providers():
         if p.id() == "otb":
             p.refreshAlgorithms()
     cls.descrFolder = os.path.join(OTB_INSTALL_DIR, 'share', 'otb', 'description')
     cls.cleanup_paths = []
Exemple #12
0
        def mock_getAlgorithm(name):
            """
            Modified version of the original getAlgorithm function.

            :param name: Name of the algorithm to load.
            :type name: str

            :return: An algorithm concrete class.
            :rtype: QgsAlgorithm  ?
            """
            Processing.initialize()
            for provider in Processing.algs.values():
                if name in provider:
                    return provider[name]
            return None
Exemple #13
0
    def _initServer(project_path, parameters):
        """Initalize server"""
        try:
            WPS.methods
        except:
            Processing.initialize()
            WPS.methods = Processing.algs
            WPS.processes = []
            for i in WPS.methods:
                for m in WPS.methods[i]:
                    WPS.processes.append(QGISProcessFactory(m))

        # TODO: handle POST, SOAP etc...
        WPS.wps = pywps.Pywps('GET')
        WPS.request = '&'.join(["%s=%s" % (k, parameters[k]) for k in parameters])
        pywps.config.setConfigValue("server","outputPath", '/tmp')
    def setUpClass(cls):
        """Run before all tests"""
        QCoreApplication.setOrganizationName("QGIS_Test")
        QCoreApplication.setOrganizationDomain(
            "QGIS_TestPyQgsExportToPostgis.com")
        QCoreApplication.setApplicationName("QGIS_TestPyQgsExportToPostgis")
        QgsSettings().clear()
        Processing.initialize()
        QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms())
        cls.registry = QgsApplication.instance().processingRegistry()

        # Create DB connection in the settings
        settings = QgsSettings()
        settings.beginGroup('/PostgreSQL/connections/qgis_test')
        settings.setValue('service', 'qgis_test')
        settings.setValue('database', 'qgis_test')
Exemple #15
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.drop_handler = ProcessingDropHandler()
     iface.registerCustomDropHandler(self.drop_handler)
     self.item_provider = ProcessingDataItemProvider()
     QgsApplication.dataItemProviderRegistry().addProvider(self.item_provider)
     self.locator_filter = AlgorithmLocatorFilter()
     iface.registerLocatorFilter(self.locator_filter)
     # Invalidate the locator filter for in-place when active layer changes
     iface.currentLayerChanged.connect(lambda _: self.iface.invalidateLocatorResults())
     self.edit_features_locator_filter = InPlaceAlgorithmLocatorFilter()
     iface.registerLocatorFilter(self.edit_features_locator_filter)
     Processing.initialize()
    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()
        fields = QgsFields()
        fields.append(QgsField('int_f', QVariant.Int))
        cls.vl = QgsMemoryProviderUtils.createMemoryLayer(
            'mylayer', fields, QgsWkbTypes.Point, QgsCoordinateReferenceSystem(4326))

        f1 = QgsFeature(cls.vl.fields())
        f1['int_f'] = 1
        f1.setGeometry(QgsGeometry.fromWkt('Point(9 45)'))
        f2 = QgsFeature(cls.vl.fields())
        f2['int_f'] = 2
        f2.setGeometry(QgsGeometry.fromWkt('Point(9.5 45.6)'))
        cls.vl.dataProvider().addFeatures([f1, f2])

        assert cls.vl.isValid()
        assert cls.vl.featureCount() == 2

        # Multipolygon layer

        cls.multipoly_vl = QgsMemoryProviderUtils.createMemoryLayer(
            'mymultiplayer', fields, QgsWkbTypes.MultiPolygon, QgsCoordinateReferenceSystem(4326))

        f3 = QgsFeature(cls.multipoly_vl.fields())
        f3.setGeometry(QgsGeometry.fromWkt('MultiPolygon (((2.81856297539240419 41.98170998812887689, 2.81874467773035464 41.98167537995160359, 2.81879535908157752 41.98154066615795443, 2.81866433873670452 41.98144056064155905, 2.81848263699778379 41.98147516865246587, 2.81843195500470811 41.98160988234612034, 2.81856297539240419 41.98170998812887689)),((2.81898589063455907 41.9815711567298635, 2.81892080450418803 41.9816030048432367, 2.81884192631866437 41.98143737613141724, 2.8190679469505846 41.98142270931093378, 2.81898589063455907 41.9815711567298635)))'))
        f4 = QgsFeature(cls.multipoly_vl.fields())
        f4.setGeometry(QgsGeometry.fromWkt('MultiPolygon (((2.81823679385631332 41.98133290154246566, 2.81830770255185703 41.98123540208609228, 2.81825871989355159 41.98112524362621656, 2.81813882853970243 41.98111258462271422, 2.81806791984415872 41.98121008407908761, 2.81811690250246416 41.98132024253896333, 2.81823679385631332 41.98133290154246566)),((2.81835835162010895 41.98123286963267731, 2.8183127674586852 41.98108725356146209, 2.8184520523963692 41.98115436357689134, 2.81835835162010895 41.98123286963267731)))'))
        cls.multipoly_vl.dataProvider().addFeatures([f3, f4])

        assert cls.multipoly_vl.isValid()
        assert cls.multipoly_vl.featureCount() == 2

        QgsProject.instance().addMapLayers([cls.vl, cls.multipoly_vl])
Exemple #17
0
        def mock_getAlgorithm(name):
            """
            Modified version of the original getAlgorithm function.

            :param name: Name of the algorithm to load.
            :type name: str

            :return: An algorithm concrete class.
            :rtype: QgsAlgorithm  ?
            """
            Processing.initialize()
            # FIXME: Had some weird bug in QGIS 2.18 MacOSX (KyngChaos)
            try:
                providers = Processing.algs.values()
            except:
                providers = Processing.algs().values()

            for provider in providers:
                if name in provider:
                    return provider[name]
            return None
 def __init__(self, iface):
     self.iface = iface
     QGisLayers.setInterface(iface)
     Processing.initialize()
     Processing.setInterface(iface)
     Processing.setPlugin(self)
Exemple #19
0
    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(
                unicode(inputLayer).encode('utf8'), inputLayer, "ogr")
            vectorlayer_vector = layer.dataProvider()
            layer_mask = QgsVectorLayer(
                unicode(inputMask).encode('utf8'), 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(
                unicode(inputRaster).encode('utf8'), 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.qgisUserDbFilePath()).path() + "/stream"
            Processing.runAlgorithm("grass:r.watershed", None, inputRaster,
                                    None, None, None, None, size, 0, 5, 300,
                                    False, True, False, False,
                                    extent_raster_str, cellSize, None, None,
                                    None, stream, None, None, None, None)
            stream_tif = stream + "." + "tif"

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

            Processing.runAlgorithm("gdalogr:rastercalculator", None,
                                    stream_tif, "1", None, "1", None, "1",
                                    None, "1", None, "1", None, "1", "A>1",
                                    "-9999", 5, "", stream_ones)
            stream_ones_str = stream_ones + "." + "tif"

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

            Processing.runAlgorithm("saga:proximitygrid", None,
                                    stream_ones_str, raster_distance, None,
                                    None)

            # condition distance >=  200, always maximum depth meters
            dist_major_200 = QFileInfo(
                QgsApplication.qgisUserDbFilePath()).path() + "/dist_major_200"

            Processing.runAlgorithm("gdalogr:rastercalculator", None,
                                    raster_distance, "1", None, "1", None, "1",
                                    None, "1", None, "1", None, "1",
                                    "A>=" + str(distance), "-9999", 5, "",
                                    dist_major_200)
            dist_major_200_str = dist_major_200 + "." + "tif"

            dist_multiplication = QFileInfo(QgsApplication.qgisUserDbFilePath(
            )).path() + "/dist_multiplication"
            Processing.runAlgorithm("gdalogr:rastercalculator", None,
                                    dist_major_200_str, "1", None, "1", None,
                                    "1", None, "1", None, "1", None, "1",
                                    "A*" + str(max_depth), "-9999", 5, "",
                                    dist_multiplication)
            dist_multiplication_str = dist_multiplication + "." + "tif"

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

            Processing.runAlgorithm("gdalogr:rastercalculator", None,
                                    raster_distance, "1", None, "1", None, "1",
                                    None, "1", None, "1", None, "1",
                                    "A<" + str(distance), "-9999", 5, "",
                                    dist_minor_200)
            dist_minor_200_str = dist_minor_200 + "." + "tif"

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

            Processing.runAlgorithm("gdalogr:rastercalculator", None,
                                    dist_minor_200_str, "1", raster_distance,
                                    "1", None, "1", None, "1", None, "1", None,
                                    "1", "A*B", "-9999", 5, "",
                                    dist_multiplication_dist)
            dist_multiplication_dist_str = dist_multiplication_dist + "." + "tif"

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

            Processing.runAlgorithm(
                "gdalogr:rastercalculator", None, dist_multiplication_dist_str,
                "1", None, "1", None, "1", None, "1", None, "1", None, "1",
                "A*" + str(max_depth) + "/" + str(distance), "-9999", 5, "",
                interpolation_dist)
            interpolation_dist_str = interpolation_dist + "." + "tif"

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

            Processing.runAlgorithm("gdalogr:rastercalculator", None,
                                    dist_multiplication_str, "1",
                                    interpolation_dist_str, "1", None, "1",
                                    None, "1", None, "1", None, "1", "A+B",
                                    "-9999", 5, "", depth_surface)
            depth_surface_tif = depth_surface + "." + "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)

            depth_reclassify = QFileInfo(QgsApplication.qgisUserDbFilePath()
                                         ).path() + "/depth_reclassify.sdat"
            Processing.runAlgorithm("saga:reclassifygridvalues", None,
                                    depth_surface_tif, 2, 0.0, 1.0, 0, 0.0,
                                    1.0, 2.0, 0, intervalos, 0, True, 0.0,
                                    True, 0.0, outPath2)

            # add result into canvas
            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)
Exemple #20
0
 def __init__(self, iface):
     interface.iface = iface
     Processing.initialize()
    def convert(self):
        self.buttonBox.button(QDialogButtonBox.Ok).setDefault(False)
        # read D raster
        inputLayer = self.inputLayerCombo.currentText()
        # read R raster
        inputLayer2 = self.inputLayerCombo2.currentText()
        # read A raster
        inputLayer3 = self.inputLayerCombo3.currentText()
        
        # outpath
        outPath = self.outputLayerCombo.text()  
        lista = []
        lista.append(inputLayer2)
        lista.append(inputLayer3)

        gdal.AllRegister()
        Processing.initialize()
        Processing.runAlgorithm("saga:rastercalculator", None,inputLayer, ';'.join(lista),"a*b*c",False, 7, outPath)
     
       
        
        if self.checkdrastic.isChecked():
            # 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( "DRASTIC completed." ) )                    
    
        colorfile = 'C:/OSGeo4W64/apps/qgis/python/plugins/DRASTIC/colorfile.clr'
        outPath_color = self.outputLayerCombo_color.text()
        from colorize import raster2png
              
       
        
        if self.checkcolor.isChecked():
            # add result into canvas
            file_info = QFileInfo(outPath_color)
            if file_info.exists():
                layer_name = file_info.baseName()
            else:
                return False
            rlayer_new = QgsRasterLayer(outPath_color, 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( "DRASTIC completed." ) )   
        
        self.buttonBox.button(QDialogButtonBox.Ok).setDefault(True) 
class ClipByExtent(QObject):
    exportError = pyqtSignal(unicode)
    exportMessage = pyqtSignal(unicode)
    exportProcessed = pyqtSignal(int)
    exportFinished = pyqtSignal()

    Processing.initialize()
    QgsApplication.processingRegistry().addProvider(GdalAlgorithmProvider())
    #print(processing.algorithmHelp("gdal:clipvectorbyextent"))

    def __init__(self):
        QObject.__init__(self)

    def setOutputGpkgPath(self, filePath):
        self.gpkgPath = filePath

    def setOutputProjectPath(self, filePath):
        self.qgisProjectpath = filePath

    def setMinMaxClear(self, minmaxclear):
        self.minmaxclear = minmaxclear

    def setExtent(self, extent):
        self.extent = extent

    def clipAndExport(self):
        project = QgsProject.instance()
        self.exportMessage.emit("入力:"+ project.fileName())

		# クリッピング範囲
        #clipextent = self.extent.toString().replace(","," ").replace(":"," ")
        #clipextent = ("{},{},{},{}").format(
        #                    self.extent.xMinimum(), # 順番に要注意
        #                    self.extent.xMaximum(), # 順番に要注意
        #                    self.extent.yMinimum(), # 順番に要注意
        #                    self.extent.yMaximum()) # 順番に要注意

        self.exportMessage.emit("extent:" + self.extent.toString())

		# 1ループ目は上書き
        appendSwitch = ""

		# レイヤリスト保存 ソースがPostgreSQLの場合はここでx
		# ソースレイヤのパスが./となっているとErrInvalidLayerになる
        layers = project.mapLayers()

        # DBのエクスポートと接続情報書き換えで2倍
        cnt = project.count()
        total = 100 / (cnt * 2)

		# LayerID:LayerName
        layerId = {}

        self.exportMessage.emit("Clipping開始")

        # Clip用形状を作成する
        uri = "polygon?crs={}&field=id:integer".format("EPSG:4612");
        cliplayer = QgsVectorLayer(uri, "clippolygon",  "memory");
        fields = cliplayer.fields()
        feature = QgsFeature(fields)
        feature.setGeometry(QgsGeometry.fromRect(self.extent))
        cliplayer.startEditing()
        feature['id'] = 1
        ret = cliplayer.addFeature(feature)
        cliplayer.commitChanges()

        # GeoPackageに出力(デバッグ用)
        #save_options = QgsVectorFileWriter.SaveVectorOptions()
        #save_options.actionOnExistingFile = QgsVectorFileWriter.CreateOrOverwriteFile
        #save_options.fileEncoding = "UTF-8"
        #save_options.layerName = cliplayer.name()
        #transform_context = QgsProject.instance().transformContext()
        #error = QgsVectorFileWriter.writeAsVectorFormatV2(cliplayer,
        #                                                    "c:\\DMP\\overlay.gpkg",
        #                                                    transform_context,
        #                                                    save_options)

        index = 0
        for layer in layers.values():
            if layer.type() == QgsMapLayerType.VectorLayer:
                
                self.exportMessage.emit("name:" + layer.name())
                self.exportMessage.emit("source:" + layer.source())
                self.exportMessage.emit("id:" + layer.id())

                layername = GdalUtils.ogrLayerName(layer.dataProvider().dataSourceUri())
                if not layername:
                    self.exportMessage.emit("未サポートのデータソース:" + layer.name())
                    break

                #layerId[layer.id()] = layername
                # PostGIS->GPKGの場合 gdal:clipvectorbyextent でogr2orすると
                # [schema].[tablename]->[tablename]とschema名無のテーブル名になるため
                layerId[layer.id()] = layer.name()

                outputlayer = QgsProcessingOutputLayerDefinition(self.gpkgPath)
                #'OPTIONS': -a_srsをつけるとエラーになる
                option = ("{}".format(appendSwitch))
                params = { 
                    'INPUT' : layer,
                    #'EXTENT' : clipextent,
                    'EXTENT' : cliplayer,
                    'OPTIONS': option,
                    'OUTPUT' : outputlayer
                }   

                res = processing.run('gdal:clipvectorbyextent', params)
                if not res:
                    self.exportError.emit("processing failed:" + layer.name())
                    break

                '''
                dataSource = ""
                sourceProvider = layer.storageType()
                if sourceProvider == "GPKG":
                    dataSource = layer.source().replace("|layername=", " ")
                elif sourceProvider.find("PostGIS"):
                    result = layer.source().split()
                    self.exportMessage.emit(result)

                    connection = {}
                    for token in result:
                        token2 = token.split("=")
                        if len(token2) == 2:
                            connection[token2[0]] = token2[1]

                    dbName = connection.get("dbname")
                    hostName = connection.get("host")
                    portNo = connection.get("port")
                    usrName = connection.get("user")
                    passWord = connection.get("password")
                    tableName = connection.get("table")
                    if passWord == None:
                        passWord = usrName

                    dataSource = ("PG:\"host={} port={} dbname={} user={} password={}\" {}".
                                    format(hostName, portNo, dbName, usrName, passWord, tableName))
            
                sourceCrs = layer.sourceCrs()

                cmd = ("ogr2ogr {} -f \"GPKG\" {} -a_srs \"{}\" -clipsrc {} {}".
                        format(appendSwitch, self.gpkgPath, sourceCrs.authid(), clipextent, dataSource))

                #runcmd = subprocess.check_call(cmd)
                runcmd = subprocess.run(cmd, 
                                        stdout=subprocess.PIPE, 
                                        stdin=subprocess.DEVNULL, 
                                        stderr=subprocess.STDOUT,
                                        universal_newlines=True)
                self.exportMessage.emit (runcmd)
                '''

                appendSwitch = "-append"
                
            self.exportProcessed.emit(int(index * total))
            index += 1

        #プロジェクトファイルをrename
        newproject = QgsProject.instance()
        newproject.write(self.qgisProjectpath)
        self.exportMessage.emit("出力:" + newproject.fileName())

        # 指定範囲でエクスポートしたDBを再度読み込みsetDataSourceで参照先DBを変更
        self.exportMessage.emit("プロジェクトファイルのデータソース書き換え開始")
        for layerid in layerId.items():
            fullname = self.gpkgPath + "|layername=" + layerid[1]

            display_name = layerid[1]
            tagetlayer = newproject.mapLayer(layerid[0])
            provider_options = QgsDataProvider.ProviderOptions()
            # Use project's transform context
            provider_options.transformContext = newproject.transformContext()

            self.exportMessage.emit("dataSource :" + fullname)
            self.exportMessage.emit("baseName :" + display_name)
            self.exportMessage.emit("RelacelayerID:" + tagetlayer.id())

            tagetlayer.setDataSource(fullname, display_name, "ogr", provider_options)

            # min max Zoom level設定をクリアする
            if self.minmaxclear:
                if tagetlayer.hasScaleBasedVisibility():
                    tagetlayer.setScaleBasedVisibility(False)

            self.exportProcessed.emit(int(index * total))
            index += 1

        newproject.write()
        self.exportMessage.emit("プロジェクトファイルのデータソース書き換え終了")
        self.exportProcessed.emit(100)

        self.exportFinished.emit()
Exemple #23
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.iface.registerMainWindowAction(self.toolboxAction, 'Ctrl+Alt+T')
        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.iface.registerMainWindowAction(self.modelerAction, 'Ctrl+Alt+M')
        self.menu.addAction(self.modelerAction)

        self.historyAction = QAction(
            QIcon(os.path.join(cmd_folder, 'images', 'history.gif')),
            self.tr('&History...'), self.iface.mainWindow())
        self.historyAction.setObjectName('historyAction')
        self.historyAction.triggered.connect(self.openHistory)
        self.iface.registerMainWindowAction(self.historyAction, 'Ctrl+Alt+H')
        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.iface.registerMainWindowAction(self.configAction, 'Ctrl+Alt+C')
        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.iface.registerMainWindowAction(self.resultsAction, 'Ctrl+Alt+R')
        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'))
Exemple #24
0
# -*- coding: utf-8 -*-

from __future__ import unicode_literals

import os.path
import sys

# Prepare processing framework
sys.path.append(":/plugins/processing")
from processing.core.Processing import Processing

Processing.initialize()
from processing.tools import *

from qgis.gui import QgsMessageBarItem
from qgis.core import QgsVectorLayer, QgsApplication, QgsCoordinateReferenceSystem
from qgis.utils import iface

from PyQt4.QtCore import QThread, QSettings
from PyQt4.uic import loadUi

from import_file import Import

from utils_job import popup, execFileDialog, pluginDirectory, no_vector_lyr_msg


class ImportLayer(object):
    """
    /***************************************************************************
     ImportLayer Class
            
def define_project_extent_using_input_polygon(
    grassdb,
    grass_location,
    qgis_prefix_path,
    path_dem_in,
    path_extent_ply,
    mask="MASK",
    dem="dem",
):
    """Define processing extent

    Function that used to define project processing spatial extent (PSE).
    The processing spatial extent is a region where Toolbox will work in. Toolbox
    will not process grids or features outside the processing spatial extent.
    Several options is available here. The PSE can be defined using input polygon

    Parameters
    ----------
    grassdb                           : path (required)
        It is a path to project grass database folder
    grass_location                    : string (required)
        It is a string of grass location name
    qgis_prefix_path                  : string (required)
        It is a string of qgis prefix path
    path_dem_in                      : string (required)
        It is the path to input dem
    path_extent_ply                  : string (optional)
        It is the path of a subregion polygon. It is only used when the Region
        of interest is very large and the resolution of the dem is very high.
        toolbox will first divide the whole region into several small subregions.
        And then using devided subregion polygon as PSE.
    mask                             : string (optional)
        It is a output mask name, which will stored in grass_location in both
        vector and raster format
    dem                              : string (optional)
        It is a output dem raster name, which will be stored in grass_location

    Notes
    -------
    Outputs are following files

    MASK                   : raster
        it is a mask raster stored in grass database, which indicate
        the PSE. The grass database is located at
        os.path.join(grassdb, grass_location)
    dem                   : raster
        it is a dem raster stored in grass database, which is
        has the same extent with MASK. The grass database is located at
        os.path.join(grassdb, grass_location)

    Returns:
    -------
       None

    Examples
    -------
    """

    print("mask region:   using input polygon ")

    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)

    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

    os.environ.update(
        dict(GRASS_COMPRESS_NULLS="1",
             GRASS_COMPRESSOR="ZSTD",
             GRASS_VERBOSE="1"))

    # load subregion mask polygon to target grass location
    PERMANENT = Session()
    PERMANENT.open(
        gisdb=grassdb,
        location=grass_location + "t1",
        create_opts="EPSG:4326",
    )
    grass_raster_v_in_org(
        grass,
        input_path=path_extent_ply,
        output_vector_nm=mask,
        location=grass_location,
    )
    PERMANENT.close()

    # unpack dem and generate mask with loaded vector

    PERMANENT = Session()
    # grass unpack function report an error if gisdb is provided using relative
    # path, so absolute path is provided here
    PERMANENT.open(gisdb=os.path.abspath(grassdb),
                   location=grass_location,
                   create_opts="")

    # unpack dem dataset
    root, ext = os.path.splitext(path_dem_in)
    if ext == ".pack":
        grass_raster_r_unpack(grass,
                              input=os.path.abspath(path_dem_in),
                              output=dem + "_big")
    else:
        grass_raster_r_in_gdal(grass=grass,
                               raster_path=path_dem_in,
                               output_nm=dem + "_big")
    ###Use polygon to define a smaller region
    # use big dem define region first and then change it by vector mask
    grass_raster_g_region(grass, dem + "_big")
    # define mask of current working enviroments
    grass_raster_r_mask(grass, raster_nm="#", vector_nm=mask)
    # define new region with this mask
    grass_raster_g_region(grass, raster_nm="#", zoom="MASK")

    # using vector define mask and clip big raster dem
    grass_raster_r_mask(grass, raster_nm="#", vector_nm=mask)
    exp = "%s = %s" % (dem, dem + "_big")
    grass_raster_r_mapcalc(grass, expression=exp)

    # using clipped dem to defing mask
    grass_raster_r_mask(grass, raster_nm=dem)

    # export dem and mask and generate mask polygon
    grass_raster_r_out_gdal(
        grass,
        input_nm=mask,
        output=os.path.join(grassdb, mask + ".tif"),
        format="GTiff",
    )
    grass_raster_r_out_gdal(
        grass,
        input_nm=dem,
        output=os.path.join(grassdb, dem + ".tif"),
        format="GTiff",
    )
    # polygonize exported mask raster, and polygonize and dissove it.
    qgis_raster_gdal_polygonize(
        processing,
        context,
        INPUT=os.path.join(grassdb, mask + ".tif"),
        OUTPUT=os.path.join(grassdb, mask + "1.shp"),
    )
    # qgis dissolve function for some reason not working here....
    qgis_vector_dissolve(
        processing,
        context,
        INPUT=os.path.join(grassdb, mask + "1.shp"),
        FIELD="DN",
        OUTPUT=os.path.join(grassdb, mask + ".shp"),
        USING_GDAL_FUNCTION=True,
    )

    PERMANENT.close()

    Qgs.exit()
def DXFImporter(uiParent, sOutForm, listDXFDatNam, zielPfadOrDatei, bZielSave, sCharSet,  bCol, bLayer, bFormatText, bUseColor4Point, bUseColor4Line, bUseColor4Poly, dblFaktor, chkTransform, DreiPassPunkte ):    
    # 23.02.17
    # Processing erst hier Laden, um den Start von QGIS zu beschleunigen
    import processing
    from processing.core.Processing import Processing

    
    # -----------------------------------------------------------------------------------------------    
    # 1. Löschen der alten Projekte und evtl.if myqtVersion == 4 Ermittlung der zu überschreibenden Dateien
    delZielDat=[]
    for i in range(listDXFDatNam.count()):
        AktDXFDatNam=listDXFDatNam.item(i).text()
        AktList,AktOpt,ProjektName, Kern =ProjDaten4Dat(AktDXFDatNam, bCol, bLayer, bZielSave)
        
        # evtl. Projektname (-gruppe) in Root löschen
        rNode=QgsProject.instance().layerTreeRoot()
        for node in rNode.children():
            if str(type(node))  == "<class 'qgis._core.QgsLayerTreeGroup'>":
                if node.name() == ProjektName:
                        rNode.removeChildNode(node)
      
        # evtl. Shape Zieldateien ermitteln und löschen
        if bZielSave:
            if sOutForm == "SHP":
                for p in AktList:
                    v = p.split(":")
                    shpdat=zielPfadOrDatei+Kern+v[0]+'.shp'
                    if os.path.exists(shpdat):
                        delZielDat.append (shpdat)
            else:
                gpkgdat=zielPfadOrDatei+Kern+'.gpkg'
                if os.path.exists(shpdat):
                    delZielDat.append (gpkgdat)
    if not DelZielDateien (delZielDat, sOutForm):
        QMessageBox.information(None, tr("Cancel"), tr("Please set target"))
        return None
    
    # -----------------------------------------------------------------------------------------------    
    # 2. evtl. Dialog zur CRS-Eingabe aufrufen und Dummylayer schreiben, um eine qprj zu erhalten
    #    Vorteil der qprj: auch UserCRS werden erkannt
    # a) CRS manuell oder automatisch je nach Einstellung
    # es gibt 3 Arten: prompt,useProject,useGlobal 
    mLay=QgsVectorLayer('LineString','' , 'memory') 
    memDat=EZUTempDir() + str(uuid.uuid4()) + '.shp'
    Antw=QgsVectorFileWriter.writeAsVectorFormat(mLay,memDat,  None, mLay.crs(), "ESRI Shapefile")
    qPrjDatName=memDat[0:-3] + 'qpj'

    # es gibt 3 Arten: prompt,useProject,useGlobal 
    # originale Einstellung merken und für den weiter Verlauf zwingend auf automatisch einstellen 
    # Name der Eigenschaft in 3.0 geändert/korrigiert
    if myqtVersion == 4:
        crsRegParam4NewLayer='/Projections/defaultBehaviour'
    else:
        crsRegParam4NewLayer='/Projections/defaultBehavior'
        
    crsArt = QSettings().value(crsRegParam4NewLayer)
    crsDefWert = QSettings().value('/Projections/layerDefaultCrs')
    
    QSettings().setValue('/Projections/layerDefaultCrs',mLay.crs().authid())  
    QSettings().setValue(crsRegParam4NewLayer,'useGlobal')

    #try:
    if True:
        # -----------------------------------------------------------------------------------------------   
        # 3a. Initialisierung    
        # manchmal bleibt (bei mehrfachnutzung oder bei crash) irgend etwas hängen,
        # die beiden nachfolgenden Zeilen haben bei einem Test das Problem gefixt - konnte aber noch nicht wiederholt werden
        # recht zeitaufwändig
        uiParent.FormRunning(True)
        uiParent.SetDatAktionGesSchritte(8)    
        uiParent.SetAktionText("")
        uiParent.SetDatAktionText(tr("process init - please wait"))
        uiParent.SetDatAktionAktSchritt(1)

        Processing.initialize()
        #Processing.updateAlgsList() # existiert nicht mehr bei 2.99

        # -----------------------------------------------------------------------------------------------    
        # 3. Abarbeitung der Dateien
        uiParent.SetDatAktionGesSchritte(listDXFDatNam.count())
        for i in range(listDXFDatNam.count()):
            AktDXFDatNam=listDXFDatNam.item(i).text()
            if myqtVersion == 5:
                uiParent.SetDatAktionText(tr("Import: " + AktDXFDatNam ))
            else:
                uiParent.SetDatAktionText(tr("Import: " + AktDXFDatNam.encode("utf8") ))
            uiParent.SetDatAktionAktSchritt(i+1)
            
            AktList,AktOpt,ProjektName, Kern = ProjDaten4Dat(AktDXFDatNam,bCol,bLayer, bZielSave)

            
            iface.mapCanvas().setRenderFlag( False )    
            # 1. Wurzel mit DXF- bzw. Projektname
                  
            # Projektname (-gruppe) in Root (neu) erstellen
            root = QgsProject.instance().layerTreeRoot()
            grpProjekt = root.addGroup( ProjektName)
            #grpProjekt = iface.legendInterface().addGroup( ProjektName, False)
            grpProjekt.setExpanded(True)
            #iface.legendInterface().setGroupExpanded( grpProjekt, True )  
           
            #msgbox ("Bearbeite '" + AktDXFDatNam + "'")
            okTransform=chkTransform
            if chkTransform and DreiPassPunkte == None:
                # Einpassdaten müssen aus wld kommen
                wldDat=os.path.splitext(AktDXFDatNam)[0] + ".wld"
                if os.path.exists(wldDat):
                    p=[[],[],[]]
                    p[0], p[1], Fehler = ReadWldDat(wldDat)
                    if Fehler == None:
                        # restliche Punkte per Helmert ermitteln
                        if p[1] == None:
                            # 2. Punkt ermitteln
                            p[0], p[1], p[2] = Helmert4Points(p[0], None)
                        # (immer) 3. Punkt ermitteln
                        p[0], p[1], p[2] = Helmert4Points(p[0],p[1])
                        DreiPassPunkte = p
                    else:
                        okTransform=False
                        addFehler (wldDat + ": " + Fehler)
                else:
                    okTransform=False
                    addFehler(wldDat + ": " + tr("file not found"))
                

            Antw = EineDXF (uiParent, mLay.crs(), bZielSave, sOutForm, grpProjekt, AktList, Kern, AktOpt, AktDXFDatNam, zielPfadOrDatei, qPrjDatName, sCharSet, bLayer, bFormatText, bUseColor4Point,bUseColor4Line,bUseColor4Poly, dblFaktor, okTransform, DreiPassPunkte)
    # Ausgangswerte wieder herstellen
    QSettings().setValue(crsRegParam4NewLayer,crsArt)
    QSettings().setValue('/Projections/layerDefaultCrs',crsDefWert)

    if len(getFehler()) > 0:
        errbox("\n\n".join(getFehler()))
        resetFehler()
    if len(getHinweis()) > 0:
        hinweislog("\n\n".join(getHinweis()))
        resetHinweis()        
    
    uiParent.FormRunning(False)
Exemple #27
0
    def calculate(self, process_path):

        qgs = QgsApplication([], False)

        qgs.initQgis()
        Processing.initialize()
        QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms())

        gdal.AllRegister()

        inputLayer = self.input_file
        process_path = process_path
        outPath = self.output_file
        cellSize = self.cellSize
        Elevation = self.elevation
        lista_table = self.rattings

        for file in glob.glob(os.path.dirname(inputLayer) + "/o.*"):
            copyfile(file, process_path + os.path.basename(file))

        inputLayer = process_path + os.path.basename(inputLayer)

        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)

        # read fields and add a new column with the indexes
        fields = layer.fields()
        new_field = QgsField("Indexes", QVariant.Double)
        layer_new = vectorlayer_vector.addAttributes([new_field])
        layer.updateFields()
        newFieldIndex = vectorlayer_vector.fieldNameIndex(new_field.name())
        allAttrs = vectorlayer_vector.attributeIndexes()
        # editing the new column
        #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())]

        # list of description on tool table
        #lista_table = lista

        field_names = [field.name() for field in fields]
        n = len(field_names)
        lista_attrib = []
        for i in range(0, n):
            f = field_names[i]
            if f == str(Elevation):
                number = i
                for feat in layer.getFeatures():
                    attrb = feat.attributes()
                    attribute_read = attrb[number]
                    lista_attrib = lista_attrib + [str(attribute_read)]
        # list of description on attribute table of shapefile
        lista_attributes = lista_attrib
        #QMessageBox.about(self, "teste", str(lista_attributes))

        # obtain the indexes of the description of shapefile attribute table
        description_common = set(lista_attributes).intersection(lista_table)
        listDescription = list(description_common)

        listElem = []
        listElements = []
        for j in range(0, len(listDescription)):
            elem = lista_table.index(listDescription[j])
            listElements = listElements + [elem]

            elem_index = lista_table[int(elem + 1)]
            listElem = listElem + [float(elem_index)]

        for l in range(0, len(listElem)):
            layer.startEditing()
            exp = QgsExpression(str(listElem[l]))

            #exp.prepare()
            elemDescription = lista_table[listElements[l]]
            for f in layer.getFeatures():
                # get attributes of column defined by the user
                attrb_elem = f[number]
                if attrb_elem == elemDescription:
                    f[newFieldIndex] = exp.evaluate()
                    layer.updateFeature(f)
            layer.commitChanges()
        list_attrb_newField = []
        for features in layer.getFeatures():
            attrb_newField = features.attributes()
            attrb_newField_read = attrb_newField[number + 1]

        # update and read the new field
        fieldsNew = layer.fields()
        field_names_new = [newField.name() for newField in fieldsNew]
        parameter_indexes = field_names_new[newFieldIndex]

        Processing.initialize()
        calculate = process_path + "/result.tif"
        #soil = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/soil.sdat"
        Processing.runAlgorithm(
            "grass7:v.to.rast", {
                'input': inputLayer,
                'type': [0, 1, 3],
                'where': '',
                'use': 0,
                'attribute_column': parameter_indexes,
                'rgb_column': None,
                'label_column': None,
                'value': None,
                'memory': 300,
                'output': calculate,
                '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
            })

        out_raster = gdal.Open(calculate)
        gdal.Warp(outPath, out_raster, dstSRS="EPSG:3857")
Exemple #28
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()
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 that called this function.
    :type parent_dialog: QProgressDialog

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

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

        output_raster = processing.runalg(
        'gdalogr:gridinvdist',
        layer,
        'minutes',
        2, 0, 0, 0, 0, 0, 0, 0, 5,
        "[temporary file]")

        output_file = output_raster['OUTPUT']
        file_info = QFileInfo(output_file)
        base_name = file_info.baseName()

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

        raster_layer = QgsRasterLayer(output_file, base_name)

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

    if raster_layer:
        if raster_layer.isValid():
            color_shader = QgsColorRampShader()
            color_shader.setColorRampType(QgsColorRampShader.INTERPOLATED)
            colors = {
                'deep_green': '#1a9641',
                'light_green': '#a6d96a',
                'pale_yellow': '#ffffc0',
                'light_red': '#fdae61',
                'red': '#d7191c'
            }
            provider = raster_layer.dataProvider()
            stats = provider.bandStatistics(
                1,
                QgsRasterBandStats.All,
                raster_layer.extent(),
                0)

            values = {}

            if stats:
                min = stats.minimumValue
                max = stats.maximumValue
                stat_range = max - min
                add = stat_range / 4
                values[0] = min
                value = min
                for index in range(1, 4):
                    value += add
                    values[index] = value
                values[4] = max
            else:
                display_warning_message_box(
                    parent_dialog,
                    parent_dialog.tr(
                        'Error'),
                    parent_dialog.tr('Error loading isochrone map'
                                     ' Problem indexing the isochrones map'))

            color_list = [
                QgsColorRampShader.ColorRampItem(
                    values[0],
                    QColor(colors['deep_green'])),
                QgsColorRampShader.ColorRampItem(
                    values[1],
                    QColor(colors['light_green'])),
                QgsColorRampShader.ColorRampItem(
                    values[2],
                    QColor(colors['pale_yellow'])),
                QgsColorRampShader.ColorRampItem(
                    values[3],
                    QColor(colors['light_red'])),
                QgsColorRampShader.ColorRampItem(
                    values[4],
                    QColor(colors['red']))
            ]

            color_shader.setColorRampItemList(color_list)
            raster_shader = QgsRasterShader()
            raster_shader.setRasterShaderFunction(color_shader)

            renderer = QgsSingleBandPseudoColorRenderer(
                raster_layer.dataProvider(),
                1,
                raster_shader)
            raster_layer.setRenderer(renderer)

        else:
            if parent_dialog:
                display_warning_message_box(
                    parent_dialog,
                    parent_dialog.tr(
                        'Problem'),
                    parent_dialog.tr('Problem styling the isochrone map'))
            else:
                display_warning_message_box(
                    parent_dialog,
                    'Problem',
                    'Problem styling the isochrone map')

        QgsMapLayerRegistry.instance().addMapLayers([raster_layer])

    else:
        if parent_dialog:

            display_warning_message_box(
                parent_dialog,
                parent_dialog.tr(
                    'Error'),
                parent_dialog.tr('Error loading isochrone map '
                                 'Could not load interpolated file!'))
        else:
            display_warning_message_box(
                parent_dialog,
                'Error',
                'Error loading isochrone map '
                'Could not load interpolated file!')

    return raster_layer
import zipfile
import tempfile

os.chdir('/projectnb/landsat/projects/Colombia/vector/')

# Initialize QGIS Application
QgsApplication.setPrefixPath("/share/pkg/qgis/2.6.1/install/bin/qgis", True)
qgs = QgsApplication([], False)
qgs.initQgis()

# Add the path to Processing framework
sys.path.append('/share/pkg/qgis/2.6.1/install/share/qgis/python/plugins')

# Import and initialize Processing framework
from processing.core.Processing import Processing
Processing.initialize()
import processing

# Load vector
layerpath = "C:\OneDrive\Lab\Base layers\scene_overlap.shp"
layerpath = "/projectnb/landsat/projects/Colombia/vector/scene_overlap.shp"

# To extract basename from the path if needed (THIS IS NOR WORKING CORRECTLY)
path = os.path.splitext(layerpath)[0]
filename = os.path.basename(path)

layer = QgsVectorLayer(layerpath, 'scene_overlap', "ogr")
if not layer.isValid():
    print "Layer failed to load!"

# Get layer data provider (starting edition session may be required after this)
Exemple #31
0
 def setUpClass(cls):
     # start_app()
     from processing.core.Processing import Processing
     Processing.initialize()
Exemple #32
0
def reproject_clip_vectors_by_polygon(grassdb, grass_location,
                                      qgis_prefix_path, mask, path_polygon,
                                      ply_name):

    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)

    crs_id = qgis_vector_return_crs_id(processing,
                                       context,
                                       mask,
                                       Input_Is_Feature_In_Mem=False)

    qgis_vector_reproject_layers(
        processing,
        context,
        INPUT=path_polygon,
        TARGET_CRS=crs_id,
        OUTPUT=os.path.join(grassdb, ply_name + "_project.shp"),
    )
    # lake polygon sometime has error in geometry
    try:
        qgis_vector_ectract_by_location(
            processing,
            context,
            INPUT=os.path.join(grassdb, ply_name + "_project.shp"),
            INTERSECT=mask,
            OUTPUT=os.path.join(grassdb, ply_name + ".shp"),
        )
        if ply_name == 'kc_zone':
            processing.run(
                "native:clip", {
                    'INPUT': os.path.join(grassdb, ply_name + "_project.shp"),
                    'OVERLAY': mask,
                    'OUTPUT': os.path.join(grassdb, ply_name + "_clip.shp")
                })

    except:
        print("Need fix lake boundary geometry to speed up")
        qgis_vector_fix_geometries(
            processing,
            context,
            INPUT=os.path.join(grassdb, ply_name + "_project.shp"),
            OUTPUT=os.path.join(grassdb, ply_name + "_fixgeo.shp"),
        )
        qgis_vector_fix_geometries(
            processing,
            context,
            INPUT=mask,
            OUTPUT=os.path.join(grassdb, "mask_fixgeo.shp"),
        )

        qgis_vector_ectract_by_location(
            processing,
            context,
            INPUT=os.path.join(grassdb, ply_name + "_fixgeo.shp"),
            INTERSECT=os.path.join(grassdb, "mask_fixgeo.shp"),
            OUTPUT=os.path.join(grassdb, ply_name + ".shp"),
        )

        if ply_name == 'kc_zone':
            processing.run(
                "native:clip", {
                    'INPUT': os.path.join(grassdb, ply_name + "_fixgeo.shp"),
                    'OVERLAY': os.path.join(grassdb, "mask_fixgeo.shp"),
                    'OUTPUT': os.path.join(grassdb, ply_name + "_clip.shp")
                })

    Qgs.exit()
Exemple #33
0
 def setUpClass(cls):
     start_app()
     from processing.core.Processing import Processing
     Processing.initialize()
     cls.cleanup_paths = []
Exemple #34
0
    def convert(self):
        self.buttonBox.button(QDialogButtonBox.Ok).setDefault(False)
        # read D raster
        inputLayer = self.inputLayerCombo.currentText()
        bn_inputLayer = str(os.path.splitext(os.path.basename(inputLayer))[0])
        teste = str(bn_inputLayer) + '@1\''
        QMessageBox.about(self, "Seepage", str(teste))
        # read R raster
        inputLayer2 = self.inputLayerCombo2.currentText()
        bn_inputLayer2 = str(
            os.path.splitext(os.path.basename(inputLayer2))[0])

        # read A raster
        inputLayer3 = self.inputLayerCombo3.currentText()
        bn_inputLayer3 = str(
            os.path.splitext(os.path.basename(inputLayer3))[0])

        # read S raster
        inputLayer4 = self.inputLayerCombo4.currentText()
        bn_inputLayer4 = str(
            os.path.splitext(os.path.basename(inputLayer4))[0])

        # read T raster
        inputLayer5 = self.inputLayerCombo5.currentText()
        bn_inputLayer5 = str(
            os.path.splitext(os.path.basename(inputLayer5))[0])

        # read I raster
        inputLayer6 = self.inputLayerCombo6.currentText()
        bn_inputLayer6 = str(
            os.path.splitext(os.path.basename(inputLayer6))[0])

        # read C raster
        inputLayer7 = self.inputLayerCombo7.currentText()
        bn_inputLayer7 = str(
            os.path.splitext(os.path.basename(inputLayer7))[0])

        # outpath
        outPath = self.outputLayerCombo.text()

        gdal.AllRegister()

        # sum of the raster = Seepage
        # D
        gdalRaster = gdal.Open(str(inputLayer))
        # # multiply by weight
        # depth_weight = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/depth_weight"
        x = gdalRaster.RasterXSize
        y = gdalRaster.RasterYSize
        geo = gdalRaster.GetGeoTransform()
        # band = gdalRaster.GetRasterBand(1)
        # data = band.ReadAsArray(0,0,x,y)
        # mul = numpy.multiply(data, int(self.lineWeightD.value()))
        # # Create an output imagedriver with the reclassified values multiplied by the weight
        # driver = gdal.GetDriverByName( "GTiff" )
        # outData = driver.Create(str(depth_weight), x,y,1, gdal.GDT_Float32)
        # outData.GetRasterBand(1).WriteArray(mul)
        # outData.SetGeoTransform(geo)
        # outData = None
        #
        # geo = gdalRaster.GetGeoTransform()
        # # pixel size
        pixelSize = geo[1]
        # extent
        minx = geo[0]
        maxy = geo[3]
        maxx = minx + geo[1] * x
        miny = maxy + geo[5] * y
        extent = str(minx) + "," + str(maxx) + "," + str(miny) + "," + str(
            maxy)
        band = gdalRaster.GetRasterBand(1)
        # data_d = band.ReadAsArray(0,0,x,y)

        Processing.initialize()

        resamp_d = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path(
        ) + "/resamp_d_Seepage.sdat"
        # Processing.runAlgorithm("saga:resampling", None, recharge_weight, True, 0, 0, extent, pixelSize, resamp_r)
        Processing.runAlgorithm(
            "saga:resampling", {
                'INPUT':
                inputLayer,
                'KEEP_TYPE':
                True,
                'SCALE_UP':
                0,
                'SCALE_DOWN':
                0,
                'TARGET_USER_XMIN TARGET_USER_XMAX TARGET_USER_YMIN TARGET_USER_YMAX':
                extent + '[EPSG:3763]',
                'TARGET_USER_SIZE':
                pixelSize,
                'TARGET_USER_FITS':
                0,
                'TARGET_TEMPLATE':
                None,
                'OUTPUT':
                resamp_d
            })

        resamp_r = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path(
        ) + "/resamp_r_Seepage.sdat"
        # Processing.runAlgorithm("saga:resampling", None, recharge_weight, True, 0, 0, extent, pixelSize, resamp_r)
        Processing.runAlgorithm(
            "saga:resampling", {
                'INPUT':
                inputLayer2,
                'KEEP_TYPE':
                True,
                'SCALE_UP':
                0,
                'SCALE_DOWN':
                0,
                'TARGET_USER_XMIN TARGET_USER_XMAX TARGET_USER_YMIN TARGET_USER_YMAX':
                extent + '[EPSG:3763]',
                'TARGET_USER_SIZE':
                pixelSize,
                'TARGET_USER_FITS':
                0,
                'TARGET_TEMPLATE':
                None,
                'OUTPUT':
                resamp_r
            })

        resamp_a = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path(
        ) + "/resamp_a_Seepage.sdat"
        # Processing.runAlgorithm("saga:resampling", None, recharge_weight, True, 0, 0, extent, pixelSize, resamp_r)
        Processing.runAlgorithm(
            "saga:resampling", {
                'INPUT':
                inputLayer3,
                'KEEP_TYPE':
                True,
                'SCALE_UP':
                0,
                'SCALE_DOWN':
                0,
                'TARGET_USER_XMIN TARGET_USER_XMAX TARGET_USER_YMIN TARGET_USER_YMAX':
                extent + '[EPSG:3763]',
                'TARGET_USER_SIZE':
                pixelSize,
                'TARGET_USER_FITS':
                0,
                'TARGET_TEMPLATE':
                None,
                'OUTPUT':
                resamp_a
            })

        resamp_s = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path(
        ) + "/resamp_s_Seepage.sdat"
        # Processing.runAlgorithm("saga:resampling", None, recharge_weight, True, 0, 0, extent, pixelSize, resamp_r)
        Processing.runAlgorithm(
            "saga:resampling", {
                'INPUT':
                inputLayer4,
                'KEEP_TYPE':
                True,
                'SCALE_UP':
                0,
                'SCALE_DOWN':
                0,
                'TARGET_USER_XMIN TARGET_USER_XMAX TARGET_USER_YMIN TARGET_USER_YMAX':
                extent + '[EPSG:3763]',
                'TARGET_USER_SIZE':
                pixelSize,
                'TARGET_USER_FITS':
                0,
                'TARGET_TEMPLATE':
                None,
                'OUTPUT':
                resamp_s
            })

        resamp_t = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path(
        ) + "/resamp_t_Seepage.sdat"
        # Processing.runAlgorithm("saga:resampling", None, recharge_weight, True, 0, 0, extent, pixelSize, resamp_r)
        Processing.runAlgorithm(
            "saga:resampling", {
                'INPUT':
                inputLayer5,
                'KEEP_TYPE':
                True,
                'SCALE_UP':
                0,
                'SCALE_DOWN':
                0,
                'TARGET_USER_XMIN TARGET_USER_XMAX TARGET_USER_YMIN TARGET_USER_YMAX':
                extent + '[EPSG:3763]',
                'TARGET_USER_SIZE':
                pixelSize,
                'TARGET_USER_FITS':
                0,
                'TARGET_TEMPLATE':
                None,
                'OUTPUT':
                resamp_t
            })

        resamp_i = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path(
        ) + "/resamp_t_Seepage.sdat"
        # Processing.runAlgorithm("saga:resampling", None, recharge_weight, True, 0, 0, extent, pixelSize, resamp_r)
        Processing.runAlgorithm(
            "saga:resampling", {
                'INPUT':
                inputLayer6,
                'KEEP_TYPE':
                True,
                'SCALE_UP':
                0,
                'SCALE_DOWN':
                0,
                'TARGET_USER_XMIN TARGET_USER_XMAX TARGET_USER_YMIN TARGET_USER_YMAX':
                extent + '[EPSG:3763]',
                'TARGET_USER_SIZE':
                pixelSize,
                'TARGET_USER_FITS':
                0,
                'TARGET_TEMPLATE':
                None,
                'OUTPUT':
                resamp_i
            })

        resamp_c = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path(
        ) + "/resamp_t_Seepage.sdat"
        # Processing.runAlgorithm("saga:resampling", None, recharge_weight, True, 0, 0, extent, pixelSize, resamp_r)
        Processing.runAlgorithm(
            "saga:resampling", {
                'INPUT':
                inputLayer7,
                'KEEP_TYPE':
                True,
                'SCALE_UP':
                0,
                'SCALE_DOWN':
                0,
                'TARGET_USER_XMIN TARGET_USER_XMAX TARGET_USER_YMIN TARGET_USER_YMAX':
                extent + '[EPSG:3763]',
                'TARGET_USER_SIZE':
                pixelSize,
                'TARGET_USER_FITS':
                0,
                'TARGET_TEMPLATE':
                None,
                'OUTPUT':
                resamp_c
            })

        #
        #
        # gdalRaster_d = gdal.Open(str(depth_weight))
        # x_d = gdalRaster_d.RasterXSize
        # y_d = gdalRaster_d.RasterYSize
        # geo_d = gdalRaster_d.GetGeoTransform()
        # band_d = gdalRaster_d.GetRasterBand(1)
        # data_d = band_d.ReadAsArray(0,0,x_d,y_d)
        #
        #
        # # R
        # # resampling R raster
        # gdalRaster2 = gdal.Open(str(inputLayer2))
        # # multiply by weight
        # recharge_weight = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/recharge_weight"
        # x2 = gdalRaster2.RasterXSize
        # y2 = gdalRaster2.RasterYSize
        # geo2 = gdalRaster2.GetGeoTransform()
        # band2 = gdalRaster2.GetRasterBand(1)
        # data2 = band2.ReadAsArray(0,0,x2,y2)
        # mul2 = numpy.multiply(data2, int(self.lineWeightR.value()))
        # # Create an output imagedriver with the reclassified values multiplied by the weight
        # driver2 = gdal.GetDriverByName( "GTiff" )
        # outData2 = driver2.Create(str(recharge_weight), x2,y2,1, gdal.GDT_Float32)
        # outData2.GetRasterBand(1).WriteArray(mul2)
        # outData2.SetGeoTransform(geo2)
        # outData2 = None
        #
        # Processing.initialize()
        # resamp_r = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/resamp_r.sdat"
        # Processing.runAlgorithm("saga:resampling", None, recharge_weight, True, 0, 0, extent, pixelSize,0, None,3, resamp_r)
        # #resamp_r_dir = resamp_r + "." + "tif"
        # # R
        # gdalRaster_r = gdal.Open(str(resamp_r))
        # x_r = gdalRaster_r.RasterXSize
        # y_r = gdalRaster_r.RasterYSize
        # geo_r = gdalRaster_r.GetGeoTransform()
        # band_r = gdalRaster_r.GetRasterBand(1)
        # data_r = band_r.ReadAsArray(0,0,x_r,y_r)
        #
        # # A
        # # resampling A raster
        # gdalRaster3 = gdal.Open(str(inputLayer3))
        # # multiply by weight
        # aquifer_weight = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/aquifer_weight"
        # x3 = gdalRaster3.RasterXSize
        # y3 = gdalRaster3.RasterYSize
        # geo3 = gdalRaster3.GetGeoTransform()
        # band3 = gdalRaster3.GetRasterBand(1)
        # data3 = band3.ReadAsArray(0,0,x3,y3)
        # mul3 = numpy.multiply(data3, int(self.lineWeightA.value()))
        # # Create an output imagedriver with the reclassified values multiplied by the weight
        # driver3 = gdal.GetDriverByName( "GTiff" )
        # outData3 = driver3.Create(str(aquifer_weight), x3,y3,1, gdal.GDT_Float32)
        # outData3.GetRasterBand(1).WriteArray(mul3)
        # outData3.SetGeoTransform(geo3)
        # outData3 = None
        # resamp_a = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/resamp_a.sdat"
        # Processing.runAlgorithm("saga:resampling", None, aquifer_weight, True, 0, 0, extent, pixelSize,0, None,3, resamp_a)
        #
        # # A
        # gdalRaster_a = gdal.Open(str(resamp_a))
        # x_a = gdalRaster_a.RasterXSize
        # y_a = gdalRaster_a.RasterYSize
        # geo_a = gdalRaster_a.GetGeoTransform()
        # band_a = gdalRaster_a.GetRasterBand(1)
        # data_a = band_a.ReadAsArray(0,0,x_a,y_a)
        #
        #
        # # S
        # # resampling S raster
        # gdalRaster4 = gdal.Open(str(inputLayer4))
        # # multiply by weight
        # soil_weight = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/soil_weight"
        # x4 = gdalRaster4.RasterXSize
        # y4 = gdalRaster4.RasterYSize
        # geo4 = gdalRaster4.GetGeoTransform()
        # band4 = gdalRaster4.GetRasterBand(1)
        # data4 = band4.ReadAsArray(0,0,x4,y4)
        # mul4 = numpy.multiply(data4, int(self.lineWeightS.value()))
        # # Create an output imagedriver with the reclassified values multiplied by the weight
        # driver4 = gdal.GetDriverByName( "GTiff" )
        # outData4 = driver4.Create(str(soil_weight), x4,y4,1, gdal.GDT_Float32)
        # outData4.GetRasterBand(1).WriteArray(mul4)
        # outData4.SetGeoTransform(geo4)
        # outData4 = None
        #
        # # find nodata values
        # if self.lineWeightS.value()==2:
        #     error = -299997
        #
        # # soil_weight_correct = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/soil_weight_correct.sdat"
        # # # reclassify no data values
        # # Processing.initialize()
        # # Processing.runAlgorithm("saga:reclassifygridvalues", None, soil_weight, 0, error, 0, 0, 0.0, 1.0, 2.0, 0, "0,0,0,0,0,0,0,0,0", 0, True, 0.0, False, 0.0, soil_weight_correct)
        # #
        #
        #
        # resamp_s = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/resamp_s.sdat"
        # Processing.runAlgorithm("saga:resampling", None, soil_weight, True, 0, 0, extent, pixelSize,0, None,3, resamp_s)
        #
        # # S
        # gdalRaster_s = gdal.Open(str(resamp_s))
        # x_s = gdalRaster_s.RasterXSize
        # y_s = gdalRaster_s.RasterYSize
        # geo_s = gdalRaster_s.GetGeoTransform()
        # band_s = gdalRaster_s.GetRasterBand(1)
        # data_s = band_s.ReadAsArray(0,0,x_s,y_s)
        #
        # # T
        # # resampling T raster
        # gdalRaster5 = gdal.Open(str(inputLayer5))
        # # multiply by weight
        # topography_weight = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/topography_weight"
        # x5 = gdalRaster5.RasterXSize
        # y5 = gdalRaster5.RasterYSize
        # geo5 = gdalRaster5.GetGeoTransform()
        # band5 = gdalRaster5.GetRasterBand(1)
        # data5 = band5.ReadAsArray(0,0,x5,y5)
        # mul5 = numpy.multiply(data5, int(self.lineWeightT.value()))
        # # Create an output imagedriver with the reclassified values multiplied by the weight
        # driver5 = gdal.GetDriverByName( "GTiff" )
        # outData5 = driver5.Create(str(topography_weight), x5,y5,1, gdal.GDT_Float32)
        # outData5.GetRasterBand(1).WriteArray(mul5)
        # outData5.SetGeoTransform(geo5)
        # outData5 = None
        # resamp_t = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/resamp_t.sdat"
        # Processing.runAlgorithm("saga:resampling", None, topography_weight, True, 0, 0, extent, pixelSize,0, None,3, resamp_t)
        #
        # # T
        # gdalRaster_t = gdal.Open(str(resamp_t))
        # x_t = gdalRaster_t.RasterXSize
        # y_t = gdalRaster_t.RasterYSize
        # geo_t = gdalRaster_t.GetGeoTransform()
        # band_t = gdalRaster_t.GetRasterBand(1)
        # data_t = band_t.ReadAsArray(0,0,x_t,y_t)
        # #QMessageBox.about(self, "Seepage", str(data_t))
        #
        # # I
        # # resampling I raster
        # gdalRaster6 = gdal.Open(str(inputLayer6))
        # # multiply by weight
        # impact_weight = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/impact_weight"
        # x6 = gdalRaster6.RasterXSize
        # y6 = gdalRaster6.RasterYSize
        # geo6 = gdalRaster6.GetGeoTransform()
        # band6 = gdalRaster6.GetRasterBand(1)
        # data6 = band6.ReadAsArray(0,0,x6,y6)
        # mul6 = numpy.multiply(data6, int(self.lineWeightI.value()))
        # # Create an output imagedriver with the reclassified values multiplied by the weight
        # driver6 = gdal.GetDriverByName( "GTiff" )
        # outData6 = driver6.Create(str(impact_weight), x6,y6,1, gdal.GDT_Float32)
        # outData6.GetRasterBand(1).WriteArray(mul6)
        # outData6.SetGeoTransform(geo6)
        # outData6 = None
        # resamp_i = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/resamp_i.sdat"
        # Processing.runAlgorithm("saga:resampling", None, impact_weight, True, 0, 0, extent, pixelSize, 0, None,3,resamp_i)
        #
        # # I
        # gdalRaster_i = gdal.Open(str(resamp_i))
        # x_i = gdalRaster_i.RasterXSize
        # y_i = gdalRaster_i.RasterYSize
        # geo_i = gdalRaster_i.GetGeoTransform()
        # band_i = gdalRaster_i.GetRasterBand(1)
        # data_i = band_i.ReadAsArray(0,0,x_i,y_i)
        #
        # # C
        # # resampling C raster
        # gdalRaster7 = gdal.Open(str(inputLayer7))
        # # multiply by weight
        # hydraulic_weight = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/hydraulic_weight"
        # x7 = gdalRaster7.RasterXSize
        # y7 = gdalRaster7.RasterYSize
        # geo7 = gdalRaster7.GetGeoTransform()
        # band7 = gdalRaster7.GetRasterBand(1)
        # data7 = band7.ReadAsArray(0,0,x7,y7)
        # mul7 = numpy.multiply(data7, int(self.lineWeightC.value()))
        # # Create an output imagedriver with the reclassified values multiplied by the weight
        # driver7 = gdal.GetDriverByName( "GTiff" )
        # outData7 = driver7.Create(str(hydraulic_weight), x7,y7,1, gdal.GDT_Float32)
        # outData7.GetRasterBand(1).WriteArray(mul7)
        # outData7.SetGeoTransform(geo7)
        # outData7 = None
        # resamp_c = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/resamp_c.sdat"
        # Processing.runAlgorithm("saga:resampling", None, hydraulic_weight, True, 0, 0, extent, pixelSize, 0, None,3, resamp_c)
        #
        # # C
        # gdalRaster_c = gdal.Open(str(resamp_c))
        # x_c = gdalRaster_c.RasterXSize
        # y_c = gdalRaster_c.RasterYSize
        # geo_c = gdalRaster_c.GetGeoTransform()
        # band_c = gdalRaster_c.GetRasterBand(1)
        # data_c = band_c.ReadAsArray(0,0,x_c,y_c)

        # list_raster = []
        # list_raster = list_raster + [inputLayer2]+[inputLayer3]+[inputLayer4]+[inputLayer5]+[inputLayer6]+[inputLayer7]
        # listt = ';'.join(list_raster)
        #
        # sum

        # first5 = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/first5"
        # Processing.runAlgorithm("gdal:rastercalculator",
        #                         {'INPUT_A': inputLayer, 'BAND_A': 1, 'INPUT_B': inputLayer2, 'BAND_B': 1,
        #                          'INPUT_C': inputLayer3, 'BAND_C': 1, 'INPUT_D': inputLayer4,
        #                          'BAND_D': 1, 'INPUT_E': inputLayer5, 'BAND_E': 1, 'INPUT_F': inputLayer6, 'BAND_F': 1,
        #                          'FORMULA': "A+B+C+D+E+F", 'NO_DATA': None, 'RTYPE': 5,
        #                          'EXTRA': '', 'OPTIONS': '',
        #                          'OUTPUT': first5})
        # Processing.runAlgorithm("gdal:rastercalculator",
        #                         {'INPUT_A': first5, 'BAND_A': 1, 'INPUT_B': inputLayer7, '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': outPath})

        # QMessageBox.about(self, "Seepage", str('\\"' + str(bn_inputLayer3) + '@1\'' + '\\"' + str(bn_inputLayer7) + '@1\' + '\\"' + str(bn_inputLayer) + '@1\'' + '\"' + str(bn_inputLayer6) + '@1\'' + '\"' + str(bn_inputLayer2) + '@1\'' + '\"' + str(bn_inputLayer4) + '@1\'' + '\"' + str(bn_inputLayer5) + '@1\''))
        drasti = QFileInfo(
            QgsApplication.qgisUserDatabaseFilePath()).path() + "/drasti.sdat"

        Processing.runAlgorithm(
            "gdal:rastercalculator", {
                'INPUT_A': resamp_d,
                'BAND_A': 1,
                'INPUT_B': resamp_r,
                'BAND_B': 1,
                'INPUT_C': resamp_a,
                'BAND_C': 1,
                'INPUT_D': resamp_s,
                'BAND_D': 1,
                'INPUT_E': resamp_t,
                'BAND_E': 1,
                'INPUT_F': resamp_i,
                'BAND_F': 1,
                'FORMULA': 'A+B+C+D+E+F',
                'NO_DATA': None,
                'RTYPE': 5,
                'EXTRA': '',
                'OPTIONS': '',
                'OUTPUT': drasti
            })

        Processing.runAlgorithm(
            "gdal:rastercalculator", {
                'INPUT_A': drasti,
                'BAND_A': 1,
                'INPUT_B': resamp_c,
                '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': outPath
            })

        # summ = data_d + data_r + data_a + data_s + data_t + data_i + data_c
        #
        # sum_nodata = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/sum_nodata"
        # sum_nodata_rec = sum_nodata + "." + "tif"
        #
        # # Create an output imagedriver with the reclassified values multiplied by the weight
        # driver_sum = gdal.GetDriverByName( "GTiff" )
        # outData_sum = driver_sum.Create(str(sum_nodata), x,y,1, gdal.GDT_Float32)
        # outData_sum.GetRasterBand(1).WriteArray(summ)
        # outData_sum.SetGeoTransform(geo)
        # outData_sum = None

        # reclassify no data values
        # Processing.runAlgorithm("saga:reclassifygridvalues", None, sum_nodata, 0, -10000100352, 0, 0, 0.0, 1.0, 2.0, 0, "0,0,0,0,0,0,0,0,0", 0, True, 0.0, False, 0.0, outPath)

        if self.checkSeepage.isChecked():
            # 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("Seepage completed."))

        self.buttonBox.button(QDialogButtonBox.Ok).setDefault(True)
Exemple #35
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()
Exemple #36
0
 def initProcessing(self):
     if not self.initialized:
         self.initialized = True
         Processing.initialize()
Exemple #37
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()
Exemple #38
0
    def setUpClass(cls):
        """Run before all tests"""
        QCoreApplication.setOrganizationName("QGIS_Test")
        QCoreApplication.setOrganizationDomain(
            "QGIS_TestPyQgsPackageLayers.com")
        QCoreApplication.setApplicationName("QGIS_TestPyQgsPackageLayers")
        QgsSettings().clear()
        Processing.initialize()
        QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms())
        cls.registry = QgsApplication.instance().processingRegistry()
        cls.tmp_dir = QTemporaryDir()
        cls.temp_path = os.path.join(cls.tmp_dir.path(), 'package_layers.gpkg')
        cls.temp_export_path = os.path.join(cls.tmp_dir.path(), 'package_layers_export.gpkg')

        # Create test DB

        """
        Test data:

        Region 1
            Province 1
                City 1
                City 2
            Province 2
                City 3
        Region 2
            Province 3
            Province 4
                City 4
        """

        ds = ogr.GetDriverByName('GPKG').CreateDataSource(cls.temp_path)
        lyr = ds.CreateLayer('region', geom_type=ogr.wkbNone)
        lyr.CreateField(ogr.FieldDefn('name', ogr.OFTString))
        f = ogr.Feature(lyr.GetLayerDefn())
        f['name'] = 'region one'
        lyr.CreateFeature(f)
        f = ogr.Feature(lyr.GetLayerDefn())
        f['name'] = 'region two'
        lyr.CreateFeature(f)

        lyr = ds.CreateLayer('province', geom_type=ogr.wkbNone)
        lyr.CreateField(ogr.FieldDefn('name', ogr.OFTString))
        lyr.CreateField(ogr.FieldDefn('region', ogr.OFTInteger))
        f = ogr.Feature(lyr.GetLayerDefn())
        f['name'] = 'province one'
        f['region'] = 1
        lyr.CreateFeature(f)
        f = ogr.Feature(lyr.GetLayerDefn())
        f['name'] = 'province two'
        f['region'] = 1
        lyr.CreateFeature(f)
        f = ogr.Feature(lyr.GetLayerDefn())
        f['name'] = 'province three'
        f['region'] = 2
        lyr.CreateFeature(f)
        f = ogr.Feature(lyr.GetLayerDefn())
        f['name'] = 'province four'
        f['region'] = 2
        lyr.CreateFeature(f)

        lyr = ds.CreateLayer('city', geom_type=ogr.wkbNone)
        lyr.CreateField(ogr.FieldDefn('name', ogr.OFTString))
        lyr.CreateField(ogr.FieldDefn('province', ogr.OFTInteger))
        f = ogr.Feature(lyr.GetLayerDefn())
        f['name'] = 'city one'
        f['province'] = 1
        lyr.CreateFeature(f)
        f = ogr.Feature(lyr.GetLayerDefn())
        f['name'] = 'city two'
        f['province'] = 1
        lyr.CreateFeature(f)
        f = ogr.Feature(lyr.GetLayerDefn())
        f['name'] = 'city three'
        f['province'] = 2
        lyr.CreateFeature(f)
        f = ogr.Feature(lyr.GetLayerDefn())
        f['name'] = 'city four'
        f['province'] = 4
        lyr.CreateFeature(f)

        f = None
        ds = None

        region = QgsVectorLayer(cls.temp_path + '|layername=region', 'region')
        province = QgsVectorLayer(cls.temp_path + '|layername=province', 'province')
        city = QgsVectorLayer(cls.temp_path + '|layername=city', 'city')

        QgsProject.instance().addMapLayers([region, province, city])

        relMgr = QgsProject.instance().relationManager()

        rel = QgsRelation()
        rel.setId('rel1')
        rel.setName('province -> region')
        rel.setReferencingLayer(province.id())
        rel.setReferencedLayer(region.id())
        rel.addFieldPair('region', 'fid')
        assert rel.isValid()

        relMgr.addRelation(rel)

        rel = QgsRelation()
        rel.setId('rel2')
        rel.setName('city -> province')
        rel.setReferencingLayer(city.id())
        rel.setReferencedLayer(province.id())
        rel.addFieldPair('province', 'fid')
        assert rel.isValid()

        relMgr.addRelation(rel)
 def setUpClass(cls):
     start_app()
     from processing.core.Processing import Processing
     Processing.initialize()
     cls.cleanup_paths = []
Exemple #40
0
 def setUpClass(cls):
     # start_app()
     from processing.core.Processing import Processing
     Processing.initialize()
    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()
        # read fields and add a new column with the indexes
        fields = layer.fields()
        new_field = QgsField("Indexes", QVariant.Double)
        layer_new = vectorlayer_vector.addAttributes([new_field])
        layer.updateFields()
        newFieldIndex = vectorlayer_vector.fieldNameIndex(new_field.name())
        allAttrs = vectorlayer_vector.attributeIndexes()
        # editing the new column
        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())]

        # list of description on tool table
        lista_table = lista

        field_names = [field.name() for field in fields]
        n = len(field_names)
        lista_attrib = []
        for i in range(0, n):
            f = field_names[i]
            if f == str(Elevation):
                number = i
                for feat in layer.getFeatures():
                    attrb = feat.attributes()
                    attribute_read = attrb[number]
                    lista_attrib = lista_attrib + [str(attribute_read)]
        # list of description on attribute table of shapefile
        lista_attributes = lista_attrib

        # obtain the indexes of the description of shapefile attribute table
        description_common = set(lista_attributes).intersection(lista_table)
        listDescription = list(description_common)

        listElem = []
        listElements = []
        for j in range(0, len(listDescription)):
            elem = lista_table.index(listDescription[j])
            listElements = listElements + [elem]

            elem_index = lista_table[int(elem + 1)]
            listElem = listElem + [float(elem_index)]

        for l in range(0, len(listElem)):
            layer.startEditing()
            exp = QgsExpression(str(listElem[l]))
            # exp.prepare(fields)
            elemDescription = lista_table[listElements[l]]
            for f in layer.getFeatures():
                # get attributes of column defined by the user
                attrb_elem = f[number]
                if attrb_elem == elemDescription:
                    f[newFieldIndex] = exp.evaluate()
                    layer.updateFeature(f)
            layer.commitChanges()
        list_attrb_newField = []
        for features in layer.getFeatures():
            attrb_newField = features.attributes()
            attrb_newField_read = attrb_newField[number + 1]

        # update and read the new field
        fieldsNew = layer.fields()
        field_names_new = [newField.name() for newField in fieldsNew]
        parameter_indexes = field_names_new[newFieldIndex]

        Processing.initialize()
        # aquifer = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/aquifer"
        Processing.runAlgorithm("grass7:v.to.rast", {'input': inputLayer, 'type': [0, 1, 3], 'where': '', 'use': 0,
                                                     'attribute_column': parameter_indexes, 'rgb_column': None,
                                                     'label_column': None, 'value': None, 'memory': 300,
                                                     'output': outPath, '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})

        # aquifer_complete = aquifer + "." + "tif"

        # Processing.runAlgorithm("grass:r.surf.idw", None,aquifer_complete , 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( "Aquifer media completed." ) )

        self.buttonBox.button(QDialogButtonBox.Ok).setDefault(True)
Exemple #42
0
 def __init__(self, iface):
     interface.iface = iface
     Processing.initialize()
    def responseComplete(self):
        QgsMessageLog.logMessage("wpsFilter.responseComplete")
        request = self.serverInterface().requestHandler()
        params = request.parameterMap()
        service = params.get('SERVICE', '')
        if service and service.upper() == 'WPS':
            # prepare query
            inputQuery = '&'.join(["%s=%s" % (k, params[k]) for k in params if k.lower() != 'map' and k.lower() != 'config' and k.lower != 'request_body'])
            request_body = params.get('REQUEST_BODY', '')
            
            # get config
            configPath = os.getenv("PYWPS_CFG")
            if not configPath and 'config' in params :
                configPath = params['config']
            elif not configPath and 'CONFIG' in params :
                configPath = params['CONFIG']
            QgsMessageLog.logMessage("configPath "+str(configPath))
            
            if configPath :
                os.environ["PYWPS_CFG"] = configPath
            pywpsConfig.loadConfiguration()
                
            try:
                providerList = ''
                algList = ''
                algsFilter = ''
                if pywpsConfig.config.has_section( 'qgis' ) :
                    # get the providers to publish
                    if pywpsConfig.config.has_option( 'qgis', 'providers' ) :
                        providerList = pywpsConfig.getConfigValue( 'qgis', 'providers' )
                        if providerList :
                            providerList = providerList.split(',')
                    # get the algorithm list to publish
                    if pywpsConfig.config.has_option( 'qgis', 'algs' ) :
                        algList = pywpsConfig.getConfigValue( 'qgis', 'algs' )
                        if algList :
                            algList = algList.split(',')
                    # get the algorithm filter
                    if pywpsConfig.config.has_option( 'qgis', 'algs_filter' ) :
                        algsFilter = pywpsConfig.getConfigValue( 'qgis', 'algs_filter' )
                    
                
                # init Processing
                Processing.initialize()
                # modify processes path and reload algorithms
                if pywpsConfig.config.has_section( 'qgis' ) and pywpsConfig.config.has_option( 'qgis', 'processing_folder' ) :
                    processingPath = pywpsConfig.getConfigValue( 'qgis', 'processing_folder' )
                    if os.path.exists( processingPath ) and os.path.isdir( processingPath ) :
                        ProcessingConfig.setSettingValue( 'MODELS_FOLDER', os.path.join( processingPath, 'models' ) )
                        ProcessingConfig.setSettingValue( 'SCRIPTS_FOLDER', os.path.join( processingPath, 'scripts' ) )
                        ProcessingConfig.setSettingValue( 'R_FOLDER', os.path.join( processingPath, 'rscripts' ) )
                        # Reload algorithms
                        Processing.loadAlgorithms()

                # get QGIS project path
                projectPath = os.getenv("QGIS_PROJECT_FILE")
                if not projectPath and 'map' in params :
                    projectPath = params['map']
                elif not projectPath and 'MAP' in params :
                    projectPath = params['MAP']
                #projectFolder
                projectFolder = ''
                if projectPath and os.path.exists( projectPath ) :
                    projectFolder = os.path.dirname( projectPath )
                QgsMessageLog.logMessage("projectPath "+str(projectPath))
                rasterLayers = []
                vectorLayers = []
                crsList = []
                if projectPath and os.path.exists( projectPath ) :
                    p_dom = minidom.parse( projectPath )
                    for ml in p_dom.getElementsByTagName('maplayer') :
                        l= {'type':ml.attributes["type"].value,
                            'name':ml.getElementsByTagName('layername')[0].childNodes[0].data,
                            'datasource':ml.getElementsByTagName('datasource')[0].childNodes[0].data,
                            'provider':ml.getElementsByTagName('provider')[0].childNodes[0].data,
                            'crs':ml.getElementsByTagName('srs')[0].getElementsByTagName('authid')[0].childNodes[0].data,
                            'proj4':ml.getElementsByTagName('srs')[0].getElementsByTagName('proj4')[0].childNodes[0].data
                        }
                        # Update relative path
                        if l['provider'] in ['ogr','gdal'] and str(l['datasource']).startswith('.'):
                            l['datasource'] = os.path.abspath( os.path.join( projectFolder, l['datasource'] ) )
                            if not os.path.exists( l['datasource'] ) :
                                continue
                        elif l['provider'] in ['gdal'] and str(l['datasource']).startswith('NETCDF:'):
                            theURIParts = l['datasource'].split( ":" );
                            src = theURIParts[1]
                            src = src.replace( '"', '' );
                            if src.startswith('.') :
                                src = os.path.abspath( os.path.join( projectFolder, src ) )
                            theURIParts[1] = '"' + src + '"'
                            l['datasource'] = ':'.join( theURIParts )
                            
                        if l['type'] == "raster" :
                            rasterLayers.append( l )
                        elif l['type'] == "vector" :
                            l['geometry'] = ml.attributes["geometry"].value
                            vectorLayers.append( l )
                    deafultCrs = ''
                    for mapcanvas in p_dom.getElementsByTagName('mapcanvas'):
                        for destinationsrs in mapcanvas.getElementsByTagName('destinationsrs'):
                            for authid in destinationsrs.getElementsByTagName('authid'):
                                defaultCrs = authid.childNodes[0].data
                                crsList.append( defaultCrs )
                    for wmsCrsList in p_dom.getElementsByTagName('WMSCrsList') :
                        for wmsCrs in wmsCrsList.getElementsByTagName('value') :
                            wmsCrsValue = wmsCrs.childNodes[0].data
                            if wmsCrsValue and wmsCrsValue != defaultCrs:
                                crsList.append( wmsCrsValue )
                
                        
                processes = [None] # if no processes found no processes return (deactivate default pywps process)
                identifier = params.get('IDENTIFIER', '').lower()
                for i in Processing.algs :
                    if providerList and i not in providerList :
                        continue
                    QgsMessageLog.logMessage("provider "+i+" "+str(len(Processing.algs[i])))
                    for m in Processing.algs[i]:
                        if identifier and identifier != m :
                            continue
                        if algList and m not in algList :
                            continue
                        if algsFilter :
                            alg = Processing.getAlgorithm( m )
                            if algsFilter.lower() not in alg.name.lower() and algsFilter.lower() not in m.lower():
                                continue
                        #QgsMessageLog.logMessage("provider "+i+" "+m)
                        processes.append(QGISProcessFactory(m, projectPath, vectorLayers, rasterLayers, crsList))
                
                #pywpsConfig.setConfigValue("server","outputPath", '/tmp/wpsoutputs')
                #pywpsConfig.setConfigValue("server","logFile", '/tmp/pywps.log')
                
                qgisaddress = self.serverInterface().getEnv('SERVER_NAME')+self.serverInterface().getEnv('SCRIPT_NAME')
                if self.serverInterface().getEnv('HTTPS') :
                    qgisaddress = 'https://'+qgisaddress
                else :
                    qgisaddress = 'http://'+qgisaddress
                qgisaddress = qgisaddress+'?'
                if 'map' in params :
                    qgisaddress = qgisaddress +'map='+ params['map'] +'&'
                elif 'MAP' in params :
                    qgisaddress = qgisaddress +'MAP='+ params['MAP'] +'&'
                if 'config' in params :
                    qgisaddress = qgisaddress +'config='+ params['config'] +'&'
                elif 'CONFIG' in params :
                    qgisaddress = qgisaddress +'CONFIG='+ params['CONFIG'] +'&'
                #pywpsConfig.setConfigValue("wps","serveraddress", qgisaddress)
                #QgsMessageLog.logMessage("qgisaddress "+qgisaddress)
                #pywpsConfig.setConfigValue("qgis","qgisserveraddress", qgisaddress)
                
                # init wps
                method = 'GET'
                if request_body :
                    method = 'POST'
                wps = pywps.Pywps(method)
                
                # create the request file for POST request
                if request_body :
                    tmpPath=pywpsConfig.getConfigValue("server","tempPath")
                    requestFile = open(os.path.join(tmpPath, "request-"+str(wps.UUID)),"w")
                    requestFile.write(str(request_body))
                    requestFile.close()
                    requestFile = open(os.path.join(tmpPath, "request-"+str(wps.UUID)),"r")
                    inputQuery = requestFile
                    
                if wps.parseRequest(inputQuery):
                    response = wps.performRequest(processes=processes)
                    if response:
                        request.clearHeaders()
                        request.clearBody()
                        #request.setHeader('Content-type', 'text/xml')
                        request.setInfoFormat(wps.request.contentType)
                        resp = wps.response
                        if wps.request.contentType == 'application/xml':
                            import re
                            import xml.sax.saxutils as saxutils
                            resp = re.sub(r'Get xlink:href=".*"', 'Get xlink:href="'+saxutils.escape(qgisaddress)+'"', resp)
                            resp = re.sub(r'Post xlink:href=".*"', 'Post xlink:href="'+saxutils.escape(qgisaddress)+'"', resp)
                        # test response type
                        if isinstance( resp, str ):
                            request.appendBody(resp)
                        elif isinstance( resp, file ) :
                            request.appendBody(resp.read())
            except WPSException,e:
                        request.clearHeaders()
                        #request.setHeader('Content-type', 'text/xml')
                        request.clearBody()
                        request.setInfoFormat('text/xml')
                        request.appendBody(e.__str__())
 def on_buttonBox_accepted(self):
     self.copyFiles(self.scriptsList, self.scripts, os.path.join(currentPath, '..', '..', '..', '..', 'processing', 'scripts'))
     Processing.initialize()
     self.copyFiles(self.modelsList, self.models, os.path.join(currentPath, '..', '..', '..', '..', 'processing', 'models'))
     Processing.initialize()
Exemple #45
0
 def __init__(self, iface):
     self.iface = iface
     Processing.initialize()
 def initProcessing(self):
     if not self.initialized:
         self.initialized = True
         Processing.initialize()
    def __init__(self, interface, workerThread):
        QDialog.__init__(self, interface.mainWindow())

        # QGIS interface
        self.iface = interface
        # QGIS map canvas
        self.canvas = self.iface.mapCanvas()
        # Threading
        self.workerThread = workerThread
        
        # Setup GUI of SEILAPLAN (import from ui_seilaplanDialog.py)
        self.setupUi(self)
        
        # Interaction with canvas, is used to draw onto map canvas
        self.drawTool = ProfiletoolMapTool(self.canvas, self.draw, self.buttonShowProf)
        # Connect emited signals
        self.drawTool.sig_clearMap.connect(self.clearMap)
        self.drawTool.sig_createProfile.connect(self.createProfile)
        self.drawTool.sig_changeCoord.connect(self.changeLineCoordinates)

        # Define some important paths and locations
        self.userHomePath = os.path.join(os.path.expanduser('~'))
        self.homePath = os.path.dirname(__file__)
        # Config file 'params.txt' stores parameters of cable types
        self.paramPath = os.path.join(self.homePath, 'config', 'params.txt')
        # Config file 'commonPaths.txt' stores previous output folders
        self.commonPathsFile = os.path.join(self.homePath, 'config',
                                            'commonPaths.txt')
        self.commonPaths, outputOpt = self.createCommonPathList()
        # Get the preferences for output options
        self.outputOpt = {'outputPath': self.commonPaths[-1],   # last used output path
                          'report': outputOpt[0],
                          'plot': outputOpt[1],
                          'geodata': outputOpt[2],
                          'coords': outputOpt[3]}
        self.projName = None

        # Initialize cable parameters
        self.param = None               # All parameters of a certain cable type
        self.paramOrder = None          # Order of parameters
        self.paramSet = None            # Name of cable type
        self.settingFields = {}         # Dictionary of all GUI setting fields

        # GUI fields and variables handling coordinate information
        self.coordFields = {}
        self.linePoints = {
            'A': QgsPointXY(-100, -100),
            'E': QgsPointXY(-100, -100)
        }
        self.azimut = 0
        self.coordStateA = 'yellow'
        self.coordStateE = 'yellow'
        
        # Organize parameter GUI fields in dictionary
        self.groupFields()

        # Dictionary containing information about selected elevation model
        self.dhm = {}
        # User defined fixed intermediate support
        self.fixStue = {}

        # Dialog with explanatory images
        self.imgBox = DialogWithImage(self.iface)

        # Additional GIS-Layers
        self.osmLyrButton.setEnabled(False)
        self.contourLyrButton.setEnabled(False)
        
        # Connect GUI elements from dialog window with functions
        self.connectGuiElements()
        
        # Set initial sate of some buttons
        # Button to show profile
        self.buttonShowProf.setEnabled(False)
        # Button that activates drawing on map
        self.draw.setEnabled(False)
        # Button stays down when pressed
        self.draw.setCheckable(True)
        
        # Dialog window with height profile
        self.profileWin = None

        # Dialog windows with output options
        self.optionWin = DialogOutputOptions(self.iface, self, self.outputOpt)
        self.optionWin.fillInDropDown(self.commonPaths)

        Processing.initialize()
        QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms())
 def __init__(self, iface):
     self.iface = iface
     Processing.initialize()
    def convert(self):
        self.buttonBox.button(QDialogButtonBox.Ok).setDefault(False)
        inputLayer = self.inputLayerCombo.currentText()
        # layer information
        layer = QgsVectorLayer(
            unicode(inputLayer).encode('utf8'), 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()
        # read fields and add a new column with the indexes
        fields = layer.pendingFields()
        new_field = QgsField("Indexes", QVariant.Double)
        layer_new = vectorlayer_vector.addAttributes([new_field])
        layer.updateFields()
        newFieldIndex = vectorlayer_vector.fieldNameIndex(new_field.name())
        allAttrs = vectorlayer_vector.attributeIndexes()
        # editing the new column
        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())]

        # list of description on tool table
        lista_table = lista

        field_names = [field.name() for field in fields]
        n = len(field_names)
        lista_attrib = []
        for i in range(0, n):
            f = field_names[i]
            if f == str(Elevation):
                number = i
                for feat in layer.getFeatures():
                    attrb = feat.attributes()
                    attribute_read = attrb[number]
                    lista_attrib = lista_attrib + [str(attribute_read)]
        # list of description on attribute table of shapefile
        lista_attributes = lista_attrib

        # obtain the indexes of the description of shapefile attribute table
        description_common = set(lista_attributes).intersection(lista_table)
        listDescription = list(description_common)

        listElem = []
        listElements = []
        for j in range(0, len(listDescription)):
            elem = lista_table.index(listDescription[j])
            listElements = listElements + [elem]

            elem_index = lista_table[int(elem + 1)]
            listElem = listElem + [float(elem_index)]

        for l in range(0, len(listElem)):
            layer.startEditing()
            exp = QgsExpression(str(listElem[l]))
            exp.prepare(fields)
            elemDescription = lista_table[listElements[l]]
            for f in layer.getFeatures():
                # get attributes of column defined by the user
                attrb_elem = f[number]
                if attrb_elem == elemDescription:
                    f[newFieldIndex] = exp.evaluate(f)
                    layer.updateFeature(f)
            layer.commitChanges()
        list_attrb_newField = []
        for features in layer.getFeatures():
            attrb_newField = features.attributes()
            attrb_newField_read = attrb_newField[number + 1]

        # update and read the new field
        fieldsNew = layer.pendingFields()
        field_names_new = [newField.name() for newField in fieldsNew]
        parameter_indexes = field_names_new[newFieldIndex]

        Processing.initialize()
        soil = QFileInfo(
            QgsApplication.qgisUserDbFilePath()).path() + "/soil.sdat"
        Processing.runAlgorithm("grass7:v.to.rast.attribute", None, inputLayer,
                                0, parameter_indexes, extent, cellSize, -1,
                                0.0001, 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
        QMessageBox.information(self, self.tr("Finished"),
                                self.tr("Aquifer media completed."))

        self.buttonBox.button(QDialogButtonBox.Ok).setDefault(True)