def accept(self, *args, **kwargs):
        if not self.validate():
            return False
        try:
            rast_sym = rs.RASTER_SYMBOLOGY[self.cboType.currentText()]
            QtGui.qApp.setOverrideCursor(QtGui.QCursor(QtCore.Qt.WaitCursor))
            if rast_sym['type'] == 'unique':
                rs.raster_apply_unique_value_renderer(
                    self.mcboTargetLayer.currentLayer(),
                    1,
                    color_ramp=rast_sym['colour_ramp'],
                    invert=rast_sym['invert'])
            else:

                rs.raster_apply_classified_renderer(
                    self.mcboTargetLayer.currentLayer(),
                    rend_type=rast_sym['type'],
                    num_classes=rast_sym['num_classes'],
                    color_ramp=rast_sym['colour_ramp'])

            QtGui.qApp.restoreOverrideCursor()
            self.iface.mainWindow().statusBar().clearMessage()
            return super(RasterSymbologyDialog, self).accept(*args, **kwargs)

        except Exception as err:
            QtGui.qApp.restoreOverrideCursor()
            self.cleanMessageBars(True)
            self.iface.mainWindow().statusBar().clearMessage()

            self.send_to_messagebar(str(err),
                                    level=QgsMessageBar.CRITICAL,
                                    duration=0,
                                    addToLog=True,
                                    exc_info=sys.exc_info())
            return False  # leave dialog open
Example #2
0
    def run_wholeOfBlockAnalysis(self):
        """Run method for the fit to block grid dialog"""
        # https://gis.stackexchange.com/a/160146

        result = check_R_dependency()
        if result is not True:
            self.iface.messageBar().pushMessage("R configuration", result,
                                                level=QgsMessageBar.WARNING, duration=15)
            return

        proc_alg_mess = ProcessingAlgMessages(self.iface)
        QgsMessageLog.instance().messageReceived.connect(proc_alg_mess.processingCatcher)

        # Then get the algorithm you're interested in (for instance, Join Attributes):
        alg = Processing.getAlgorithm("r:wholeofblockanalysis")
        if alg is None:
            self.iface.messageBar().pushMessage("Whole-of-block analysis algorithm could not"
                                                " be found", level=QgsMessageBar.CRITICAL)
            return
        # Instantiate the commander window and open the algorithm's interface
        cw = CommanderWindow(self.iface.mainWindow(), self.iface.mapCanvas())
        if alg is not None:
            cw.runAlgorithm(alg)

        # if proc_alg_mess.alg_name == '' then cancel was clicked

        if proc_alg_mess.error:
            self.iface.messageBar().pushMessage("Whole-of-block analysis", proc_alg_mess.error_msg,
                                                level=QgsMessageBar.CRITICAL, duration=0)
        elif proc_alg_mess.alg_name != '':
            data_column = proc_alg_mess.parameters['Data_Column']

            # load rasters into qgis as grouped layers.
            for key, val in proc_alg_mess.output_files.items():

                grplyr = os.path.join('Whole-of-block {}'.format(data_column),  val['title'])

                for ea_file in val['files']:
                    removeFileFromQGIS(ea_file)
                    raster_layer = addRasterFileToQGIS(ea_file, group_layer_name=grplyr, atTop=False)
                    if key in ['p_val']:
                        raster_apply_unique_value_renderer(raster_layer)

            self.iface.messageBar().pushMessage("Whole-of-block analysis Completed Successfully!",
                                                level=QgsMessageBar.INFO, duration=15)

        del proc_alg_mess
Example #3
0
    def accept(self, *args, **kwargs):
        try:
            if not self.validate():
                return False

            # disable form via a frame, this will still allow interaction with the message bar
            self.fraMain.setDisabled(True)

            # clean gui and Qgis messagebars
            self.cleanMessageBars(True)

            # Change cursor to Wait cursor
            QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
            self.iface.mainWindow().statusBar().showMessage(
                'Processing {}'.format(self.windowTitle()))
            LOGGER.info('{st}\nProcessing {}'.format(self.windowTitle(),
                                                     st='*' * 50))

            self.send_to_messagebar(
                "Please wait.. QGIS will be locked... See log panel for progress.",
                level=Qgis.Warning,
                duration=0,
                addToLog=False,
                core_QGIS=False,
                showLogPanel=True)

            registry = QgsProject.instance()
            rasterSource = [
                registry.mapLayer(self.tabList.item(row, 0).text()).source()
                for row in range(0, self.tabList.rowCount())
            ]

            rasterLyrNames = [
                registry.mapLayer(self.tabList.item(row, 0).text()).name()
                for row in range(0, self.tabList.rowCount())
            ]

            # Add settings to log
            settingsStr = 'Parameters:---------------------------------------'

            if len(rasterSource) == 1:
                settingsStr += '\n    {:20}\t{}'.format(
                    'Rasters: ', rasterLyrNames[0])
            else:
                settingsStr += '\n    {:20}\t{}'.format(
                    'Rasters: ', len(rasterLyrNames))
                settingsStr += '\n\t\t' + '\n\t\t'.join(rasterLyrNames)

            settingsStr += '\n    {:20}\t{}'.format('Number of Clusters ',
                                                    self.spnClusters.value())
            settingsStr += '\n    {:20}\t{}\n'.format('Output TIFF File:',
                                                      self.lneSaveFile.text())

            LOGGER.info(settingsStr)
            _ = processing.kmeans_clustering(rasterSource,
                                             self.lneSaveFile.text(),
                                             self.spnClusters.value())
            csv_file = self.lneSaveFile.text().replace('.tif',
                                                       '_statistics.csv')
            vect_layer = addVectorFileToQGIS(csv_file,
                                             os.path.basename(csv_file),
                                             atTop=True)

            raster_sym = RASTER_SYMBOLOGY['Zones']
            raster_layer = addRasterFileToQGIS(self.lneSaveFile.text(),
                                               atTop=False)
            raster_apply_unique_value_renderer(
                raster_layer,
                1,
                color_ramp=raster_sym['colour_ramp'],
                invert=raster_sym['invert'])
            self.cleanMessageBars(True)
            self.fraMain.setDisabled(False)

            self.iface.mainWindow().statusBar().clearMessage()
            self.iface.messageBar().popWidget()
            QApplication.restoreOverrideCursor()

            return super(KMeansClusterDialog, self).accept(*args, **kwargs)

        except Exception as err:
            self.iface.mainWindow().statusBar().clearMessage()
            self.cleanMessageBars(True)
            self.fraMain.setDisabled(False)
            err_mess = str(err)
            exc_info = sys.exc_info()

            if isinstance(err,
                          IOError) and err.filename == self.lneSaveFile.text():
                err_mess = 'Output File in Use - IOError {} '.format(
                    err.strerror)
                exc_info = None

            self.send_to_messagebar(err_mess,
                                    level=Qgis.Critical,
                                    duration=0,
                                    addToLog=True,
                                    showLogPanel=True,
                                    exc_info=exc_info)
            QApplication.restoreOverrideCursor()
            return False  # leave dialog open
    def accept(self, *args, **kwargs):
        try:

            if not self.validate():
                return False

            # disable form via a frame, this will still allow interaction with
            # the message bar
            self.fraMain.setDisabled(True)

            # clean gui and Qgis messagebars
            self.cleanMessageBars(True)

            # Change cursor to Wait cursor
            QtGui.qApp.setOverrideCursor(QtGui.QCursor(QtCore.Qt.WaitCursor))
            self.iface.mainWindow().statusBar().showMessage(
                'Processing {}'.format(self.windowTitle()))
            LOGGER.info('{st}\nProcessing {}'.format(self.windowTitle(),
                                                     st='*' * 50))

            self.send_to_messagebar(
                "Please wait.. QGIS will be locked... "
                "See log panel for progress.",
                level=QgsMessageBar.WARNING,
                duration=0,
                addToLog=False,
                core_QGIS=False,
                showLogPanel=True)

            registry = QgsMapLayerRegistry.instance()
            upper_src = [
                registry.mapLayer(self.tabUpper.item(row, 0).text()).source()
                for row in range(0, self.tabUpper.rowCount())
            ]
            upper_names = [
                registry.mapLayer(self.tabUpper.item(row, 0).text()).name()
                for row in range(0, self.tabUpper.rowCount())
            ]

            lower_src = [
                registry.mapLayer(self.tabLower.item(row, 0).text()).source()
                for row in range(0, self.tabLower.rowCount())
            ]

            lower_names = [
                registry.mapLayer(self.tabLower.item(row, 0).text()).name()
                for row in range(0, self.tabLower.rowCount())
            ]

            # Add settings to log
            settingsStr = 'Parameters:---------------------------------------'
            settingsStr += '\n    {:20}\t{}'.format(
                'Persistor Method: ', self.cboMethod.currentText())

            if self.cboMethod.currentText() == 'Target Probability':
                settingsStr += '\n    {:20}\t{}'.format(
                    'Upper Category: ',
                    'Count of rasters:{}'.format(len(upper_names)))

                settingsStr += '\n\t\t    ' + '\n\t\t    '.join(upper_names)

                settingsStr += '\n    {:20}\t{}'.format(
                    '     Target Probability: ',
                    self.cboUpperProb.currentText())

                settingsStr += '\n    {:20}\t{}'.format(
                    '     Target Percentage: ',
                    self.cboUpperPerc.currentText())

                # ------------------------------------------------------
                settingsStr += '\n    {:20}\t{}'.format(
                    'Lower Category: ',
                    'Count of rasters:{}'.format(len(upper_names)))

                settingsStr += '\n\t\t    ' + '\n\t\t    '.join(upper_names)

                settingsStr += '\n    {:20}\t{}'.format(
                    '     Target Probability: ',
                    self.cboLowerProb.currentText())

                settingsStr += '\n    {:20}\t{}'.format(
                    '     Target Percentage: ',
                    self.cboLowerPerc.currentText())
            else:
                settingsStr += '\n    {:20}\t{}'.format(
                    '     Rasters: ', len(upper_names))
                settingsStr += '\n\t\t' + '\n\t\t'.join(upper_names)

                settingsStr += '\n    {:20}\t{}'.format(
                    'Greater Than: ', self.optGreaterThan.isChecked())
                settingsStr += '\n    {:20}\t{}'.format(
                    'Target Percentage: ',
                    self.cboAllYearTargetPerc.currentText())

            settingsStr += '\n    {:20}\t{}\n'.format('Output TIFF File:',
                                                      self.lneSaveFile.text())

            LOGGER.info(settingsStr)

            stepTime = time.time()

            if self.cboMethod.currentText() == 'Target Probability':
                _ = persistor_target_probability(
                    upper_src, int(self.cboUpperPerc.currentText().strip('%')),
                    int(self.cboUpperProb.currentText().strip('%')), lower_src,
                    int(self.cboLowerPerc.currentText().strip('%')),
                    int(self.cboLowerProb.currentText().strip('%')),
                    self.lneSaveFile.text())
                raster_sym = rs.RASTER_SYMBOLOGY[
                    'Persistor - Target Probability']

            else:
                _ = persistor_all_years(
                    upper_src, self.lneSaveFile.text(),
                    self.optGreaterThan.isChecked(),
                    int(self.cboAllYearTargetPerc.currentText().strip('%')))

                raster_sym = rs.RASTER_SYMBOLOGY['Persistor - All Years']

            rasterLyr = addRasterFileToQGIS(self.lneSaveFile.text(),
                                            atTop=False)
            rs.raster_apply_unique_value_renderer(
                rasterLyr,
                1,
                color_ramp=raster_sym['colour_ramp'],
                invert=raster_sym['invert'])

            self.cleanMessageBars(True)
            self.fraMain.setDisabled(False)

            self.iface.mainWindow().statusBar().clearMessage()
            self.iface.messageBar().popWidget()
            QtGui.qApp.restoreOverrideCursor()
            return super(PersistorDialog, self).accept(*args, **kwargs)

        except Exception as err:
            self.iface.mainWindow().statusBar().clearMessage()
            self.cleanMessageBars(True)
            self.fraMain.setDisabled(False)
            err_mess = str(err)
            exc_info = sys.exc_info()

            if isinstance(err,
                          IOError) and err.filename == self.lneSaveFile.text():
                err_mess = 'Output CSV File in Use - IOError {} '.format(
                    err.strerror)
                exc_info = None

            self.send_to_messagebar(err_mess,
                                    level=QgsMessageBar.CRITICAL,
                                    duration=0,
                                    addToLog=True,
                                    showLogPanel=True,
                                    exc_info=exc_info)
            QtGui.qApp.restoreOverrideCursor()
            return False  # leave dialog open
    def accept(self, *args, **kwargs):
        if not self.validate():
            return False

        try:
            QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)

            self.iface.mainWindow().statusBar().showMessage('Processing {}'.format(self.windowTitle()))
            LOGGER.info('{st}\nProcessing {}'.format(self.windowTitle(), st='*' * 50))

            # Add settings to log.
            settingsStr = 'Parameters:---------------------------------------'
            if self.chkUseSelected.isChecked():
                settingsStr += '\n    {:30}\t{} with {} selected features'.format('Layer:',
                                                                                  self.mcboTargetLayer.currentLayer().name(),
                                                                                  self.mcboTargetLayer.currentLayer().selectedFeatureCount())
            else:
                settingsStr += '\n    {:30}\t{}'.format('Layer:', self.mcboTargetLayer.currentLayer().name())

            settingsStr += '\n    {:30}\t{}'.format('Output Raster File:', self.lneSaveRasterFile.text())
            settingsStr += '\n    {:30}\t{}'.format('Pixel Size:', self.dsbPixelSize.value())
            settingsStr += '\n    {:30}\t{}'.format('No Data Value:', self.spnNoDataVal.value())
            settingsStr += '\n    {:30}\t{}'.format('Snap To Extent:', self.chkSnapExtent.isChecked())
            settingsStr += '\n Derived Parameters:---------------------------------------'
            settingsStr += '\n    {:30}\t{}'.format('Output Vesper File:',
                                                        os.path.splitext(self.lneSaveRasterFile.text())[0] + '_v.txt')
            settingsStr += '\n    {:30}\t{} - {}\n'.format('Output Projected Coordinate System:',
                                                              self.mCRSoutput.crs().authid(),
                                                              self.mCRSoutput.crs().description())

            LOGGER.info(settingsStr)

            lyrTarget = self.mcboTargetLayer.currentLayer()

            rasterFile = self.lneSaveRasterFile.text()
            removeFileFromQGIS(rasterFile)

            if self.chkUseSelected.isChecked():
                polyFile = os.path.join(TEMPDIR, '{}_selection.shp'.format(lyrTarget.name()))
                removeFileFromQGIS(polyFile)
                writer = QgsVectorFileWriter.writeAsVectorFormat(lyrTarget,
                                                                 polyFile,
                                                                 "utf-8",
                                                                 lyrTarget.crs(),
                                                                 driverName="ESRI Shapefile",
                                                                 onlySelected=True)

                LOGGER.info('{:<30} {:<15} {}'.format('Save layer/selection to file', polyFile, ''))
                if self.DISP_TEMP_LAYERS:
                    addVectorFileToQGIS(polyFile, group_layer_name='DEBUG', atTop=True)

            else:
                polyFile = get_layer_source(lyrTarget)

            processing.block_grid(in_shapefilename=polyFile,
                                  pixel_size=self.dsbPixelSize.value(),
                                  out_rasterfilename=rasterFile,
                                  out_vesperfilename=os.path.splitext(rasterFile)[0] + '_v.txt',
                                  nodata_val=self.spnNoDataVal.value(),
                                  snap=self.chkSnapExtent.isChecked(),
                                  out_epsg=int(self.mCRSoutput.crs().authid().replace("EPSG:",'')),
                                  overwrite=True)  # The saveAS dialog takes care of the overwrite issue.

            if self.chkDisplayResults.isChecked():
                raster_layer = addRasterFileToQGIS(rasterFile, atTop=False)
                raster_sym = RASTER_SYMBOLOGY['Block Grid']
                raster_apply_unique_value_renderer(raster_layer,1,
                                               color_ramp=raster_sym['colour_ramp'],
                                               invert=raster_sym['invert'])


            #QApplication.restoreOverrideCursor()
            QApplication.restoreOverrideCursor()
            self.iface.mainWindow().statusBar().clearMessage()

            return super(BlockGridDialog, self).accept(*args, **kwargs)

        except Exception as err:
            QApplication.restoreOverrideCursor()
            self.iface.mainWindow().statusBar().clearMessage()
            self.cleanMessageBars(True)
            self.send_to_messagebar(str(err), level=Qgis.Critical, duration=0, addToLog=True,
                                    showLogPanel=True, exc_info=sys.exc_info())
            return False  # leave dialog open