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
Пример #2
0
    def processFinishedVesper(self, exitCode, exitStatus):  # connected to process.finished slot
        """When VESPER is complete, import the results to TIFF and QGIS"""
        currentTask = self.vesper_queue[0]

        if exitCode == 0 and exitStatus == QProcess.NormalExit:
            self.processVesper.close()
            self.processVesper = None

            if currentTask['epsg'] > 0:
                try:
                    out_PredTif, out_SETif, out_CITxt = vesper_text_to_raster(currentTask['control_file'],
                                                                              currentTask['epsg'])

                    raster_sym = RASTER_SYMBOLOGY['Yield']

                    removeFileFromQGIS(out_PredTif)
                    rasterLyr = addRasterFileToQGIS(out_PredTif, atTop=False)
                    raster_apply_classified_renderer(rasterLyr,
                                    rend_type=raster_sym['type'],
                                    num_classes=raster_sym['num_classes'],
                                    color_ramp=raster_sym['colour_ramp'])

                    removeFileFromQGIS(out_SETif)
                    addRasterFileToQGIS(out_SETif, atTop=False)

                except Exception as err:
                    message = "Could not import from VESPER to raster TIFF possibly due to a " \
                              "VESPER error.\n{}".format(os.path.basename(currentTask['control_file']))

                    LOGGER.error(message)

            message = "Completed VESPER kriging for {}\t Duration H:M:SS - {dur}".format(
                        os.path.basename(currentTask['control_file']),
                        dur=datetime.timedelta(seconds=time.time() - self.vesper_run_time))
            self.iface.messageBar().pushMessage(message, level=QgsMessageBar.INFO, duration=15)
            LOGGER.info(message)

        else:
            message = "Error occurred with VESPER kriging for {}".format(currentTask['control_file'])
            self.iface.messageBar().pushMessage(message, level=QgsMessageBar.CRITICAL, duration=0)
            LOGGER.error(message)

        self.vesper_queue = self.vesper_queue[1:]  # remove the recently finished one which will always be at position 0

        self.lblVesperQueue.setText('{} tasks in VESPER queue'.format(len(self.vesper_queue)))

        if len(self.vesper_queue) > 0:
            self.vesper_run_time = time.time()
            self.processRunVesper()

        else:
            self.vesper_queue = []
            self.vesper_run_time = ''
            self.queueStatusBarHide()

        return
Пример #3
0
    def accept(self, *args, **kwargs):
        """Run the processing"""
        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)

            selectedIndices = [
                x.text() for x in self.chkgrpIndices.buttons()
                if x.isChecked()
            ]

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

            settingsStr += '\n    {:20}\t{}'.format(
                'Image layer:',
                self.mcboRasterLayer.currentLayer().name())
            settingsStr += '\n    {:20}\t{}'.format('Image nodata value:',
                                                    self.spnNoDataVal.value())

            if self.chkUsePoly.isChecked():
                if self.chkUseSelected.isChecked():
                    settingsStr += '\n    {:20}\t{} with {} selected features'.format(
                        'Layer:',
                        self.mcboPolygonLayer.currentLayer().name(),
                        len(self.mcboPolygonLayer.currentLayer().
                            selectedFeatures()))
                else:
                    settingsStr += '\n    {:20}\t{}'.format(
                        'Boundary layer:',
                        self.mcboPolygonLayer.currentLayer().name())

                if self.mFieldComboBox.currentField():
                    settingsStr += '\n    {:20}\t{}'.format(
                        'Block ID field:', self.mFieldComboBox.currentField())

            settingsStr += '\n    {:20}\t{}'.format('Resample pixel size: ',
                                                    self.dsbPixelSize.value())

            for k, v in self.band_mapping.iteritems():
                if v > 0:
                    settingsStr += '\n    {:20}\t{}'.format(
                        '{} Band:'.format(k.title()), v)

            settingsStr += '\n    {:20}\t{}'.format('Calculate Indices: ',
                                                    ', '.join(selectedIndices))
            settingsStr += '\n    {:30}\t{}'.format(
                'Output Coordinate System:', self.lblOutCRS.text())
            settingsStr += '\n    {:30}\t{}\n'.format(
                'Output Folder:', self.lneOutputFolder.text())

            LOGGER.info(settingsStr)

            lyrRaster = self.mcboRasterLayer.currentLayer()

            if self.chkUsePoly.isChecked():
                lyrBoundary = self.mcboPolygonLayer.currentLayer()

                if self.chkUseSelected.isChecked():
                    savePlyName = lyrBoundary.name() + '_poly.shp'
                    filePoly = os.path.join(TEMPDIR, savePlyName)
                    if os.path.exists(filePoly): removeFileFromQGIS(filePoly)

                    QgsVectorFileWriter.writeAsVectorFormat(lyrBoundary,
                                                            filePoly,
                                                            "utf-8",
                                                            lyrBoundary.crs(),
                                                            "ESRI Shapefile",
                                                            onlySelected=True)

                    if self.DISP_TEMP_LAYERS:
                        addVectorFileToQGIS(filePoly,
                                            layer_name=os.path.splitext(
                                                os.path.basename(filePoly))[0],
                                            group_layer_name='DEBUG',
                                            atTop=True)
                else:
                    filePoly = lyrBoundary.source()

            files = calc_indices_for_block(
                lyrRaster.source(),
                self.dsbPixelSize.value(),
                self.band_mapping,
                self.lneOutputFolder.text(),
                indices=selectedIndices,
                image_epsg=int(lyrRaster.crs().authid().replace('EPSG:', '')),
                image_nodata=self.spnNoDataVal.value(),
                polygon_shapefile=filePoly
                if self.chkUsePoly.isChecked() else None,
                groupby=self.mFieldComboBox.currentField()
                if self.mFieldComboBox.currentField() else None,
                out_epsg=int(self.outQgsCRS.authid().replace('EPSG:', '')))

            if self.chkAddToDisplay.isChecked():
                for ea_file in files:
                    raster_sym = RASTER_SYMBOLOGY[
                        'Image Indices (ie PCD, NDVI)']
                    raster_lyr = addRasterFileToQGIS(
                        ea_file,
                        atTop=False,
                        group_layer_name=os.path.basename(
                            os.path.dirname(ea_file)))
                    raster_apply_classified_renderer(
                        raster_lyr,
                        rend_type=raster_sym['type'],
                        num_classes=raster_sym['num_classes'],
                        color_ramp=raster_sym['colour_ramp'])

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

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

        except Exception as err:

            QtGui.qApp.restoreOverrideCursor()
            self.iface.mainWindow().statusBar().clearMessage()
            self.cleanMessageBars(True)
            self.fraMain.setDisabled(False)

            self.send_to_messagebar(str(err),
                                    level=QgsMessageBar.CRITICAL,
                                    duration=0,
                                    addToLog=True,
                                    core_QGIS=False,
                                    showLogPanel=True,
                                    exc_info=sys.exc_info())

            return False  # leave dialog open