def accept(self, *args, **kwargs): if not self.validate(): return False try: self.cleanMessageBars(True) QApplication.setOverrideCursor(QtCore.Qt.WaitCursor) self.iface.mainWindow().statusBar().showMessage('Processing {}'.format(self.windowTitle())) # Add settings to log LOGGER.info('{st}\nProcessing {}'.format(self.windowTitle(), st='*' * 50)) settingsStr = 'Parameters:---------------------------------------' settingsStr += '\n {:30}\t{}'.format('Vesper Control File:', self.lneInVesperCtrlFile.text()) settingsStr += '\n {:30}\t{}'.format('Coordinate System:', self.vesper_qgscrs.authid(), self.vesper_qgscrs.description()) settingsStr += '\n {:30}\t{}'.format('Run Vesper', self.chkRunVesper.isChecked()) LOGGER.info(settingsStr) if self.chkRunVesper.isChecked(): # if epsg is in the vesp queue, then run vesper to raster if self.vesper_qgscrs is not None: epsg = int(self.vesper_qgscrs.authid().replace('EPSG:', '')) self.vesp_dict = {'control_file': self.lneInVesperCtrlFile.text(), 'epsg': epsg} else: out_PredTif, out_SETif, out_CITxt = vesper_text_to_raster(self.lneInVesperCtrlFile.text(), int(self.vesper_qgscrs.authid().replace( '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']) addRasterFileToQGIS(out_SETif, atTop=False) QApplication.restoreOverrideCursor() self.iface.mainWindow().statusBar().clearMessage() return super(PostVesperDialog, self).accept(*args, **kwargs) except Exception as err: QApplication.restoreOverrideCursor() self.cleanMessageBars(True) self.iface.mainWindow().statusBar().clearMessage() 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
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
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
def accept(self, *args, **kwargs): if not self.validate(): return False try: QtGui.qApp.setOverrideCursor(QtGui.QCursor(QtCore.Qt.WaitCursor)) write_setting(PLUGIN_NAME + "/" + self.toolKey + "/LastSize", self.dsbSize.value()) LOGGER.info('{st}\nProcessing {}'.format(self.windowTitle(), st='*' * 50)) self.iface.mainWindow().statusBar().showMessage('Processing {}'.format(self.windowTitle())) # Add settings to log settingsStr = 'Parameters:---------------------------------------' settingsStr += '\n {:30}\t{}'.format('Sample Size:', self.dsbSize.value()) settingsStr += '\n {:30}\t{}'.format('Layer:', self.mcboTargetLayer.currentLayer().name()) settingsStr += '\n {:30}\t{}'.format('Output Shapefile:', self.lneSaveFile.text()) LOGGER.info(settingsStr) lyrTarget = self.mcboTargetLayer.currentLayer() removeFileFromQGIS(self.lneSaveFile.text()) raster_file = lyrTarget.source() rasterCRS = pyprecag_crs.getCRSfromRasterFile(raster_file) if rasterCRS.epsg is None: rasterCRS.getFromEPSG(lyrTarget.crs().authid()) with rasterio.open(os.path.normpath(raster_file)) as src: processing.random_pixel_selection(src, rasterCRS, int(self.dsbSize.value()), self.lneSaveFile.text()) lyrPts = addVectorFileToQGIS(self.lneSaveFile.text(), atTop=True, layer_name=os.path.splitext(os.path.basename(self.lneSaveFile.text()))[0]) QtGui.qApp.restoreOverrideCursor() self.iface.mainWindow().statusBar().clearMessage() return super(RandomPixelSelectionDialog, self).accept(*args, **kwargs) except Exception as err: QtGui.qApp.restoreOverrideCursor() self.iface.mainWindow().statusBar().clearMessage() self.cleanMessageBars(True) self.send_to_messagebar(str(err), level=QgsMessageBar.CRITICAL, duration=0, addToLog=True, exc_info=sys.exc_info()) 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() 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()) ] selectedStats = [ x.text() for x in self.chkgrpStatistics.buttons() if x.isChecked() ] statsFunctions = [ self.statsMapping[x.lower()] for x in selectedStats ] # Add settings to log settingsStr = 'Parameters:---------------------------------------' if self.chkUseSelected.isChecked(): settingsStr += '\n {:20}\t{} with {} selected features'.format( 'Layer:', self.mcboPointsLayer.currentLayer().name(), len(self.mcboPointsLayer.currentLayer().selectedFeatures()) ) else: settingsStr += '\n {:20}\t{}'.format( 'Layer:', self.mcboPointsLayer.currentLayer().name()) 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( 'Use Current Pixel Value: ', self.chkCurrentVal.isChecked()) settingsStr += '\n {:20}\t{}'.format( 'Neighbourhood Size: ', self.btgrpSize.checkedButton().text().replace('\n', '')) settingsStr += '\n {:20}\t{}'.format('Statistics: ', ', '.join(selectedStats)) settingsStr += '\n {:20}\t{}\n'.format( 'Output CSV File:', self.lneSaveCSVFile.text()) LOGGER.info(settingsStr) layerPts = self.mcboPointsLayer.currentLayer() stepTime = time.time() if layerPts.providerType() == 'delimitedtext' or os.path.splitext(layerPts.source())[-1] == '.vrt' or \ self.chkUseSelected.isChecked(): filePoints = os.path.join( TEMPDIR, "{}_GEpoints.shp".format(layerPts.name())) if self.chkUseSelected.isChecked(): filePoints = os.path.join( TEMPDIR, "{}_selected_GEpoints.shp".format(layerPts.name())) if os.path.exists(filePoints): removeFileFromQGIS(filePoints) ptsMemLayer = copyLayerToMemory( layerPts, layerPts.name() + "_memory", bAddUFI=True, bOnlySelectedFeat=self.chkUseSelected.isChecked()) _writer = QgsVectorFileWriter.writeAsVectorFormat( ptsMemLayer, filePoints, "utf-8", layerPts.crs(), "ESRI Shapefile") LOGGER.info('{:<30} {:<15} {}'.format( 'Save layer/selection to file', datetime.timedelta(seconds=time.time() - stepTime), filePoints)) stepTime = time.time() # reset field to match truncated field in the saved shapefile. del ptsMemLayer, _writer if self.DISP_TEMP_LAYERS: addVectorFileToQGIS(filePoints, group_layer_name='DEBUG', atTop=True) else: filePoints = layerPts.source() ptsDesc = describe.VectorDescribe(filePoints) gdfPoints = ptsDesc.open_geo_dataframe() # assign a coordinate system if required based on the layer crs. if ptsDesc.crs.srs is None: ptsDesc.crs.getFromEPSG(layerPts.crs().authid()) gdfPoints.crs = ptsDesc.crs.epsg sizeList = [] if self.chkCurrentVal.isChecked(): sizeList = [1] sizeList.append(int(self.btgrpSize.checkedButton().text()[0])) _ = processing.extract_pixel_statistics_for_points( gdfPoints, ptsDesc.crs, rasterSource, function_list=statsFunctions, size_list=sizeList, output_csvfile=self.lneSaveCSVFile.text()) self.cleanMessageBars(True) self.fraMain.setDisabled(False) self.iface.mainWindow().statusBar().clearMessage() self.iface.messageBar().popWidget() QtGui.qApp.restoreOverrideCursor() return super(GridExtractDialog, 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.lneSaveCSVFile.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): 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) # Add settings to log settingsStr = 'Parameters:---------------------------------------' settingsStr += '\n {:20}\t{}'.format( 'Image layer:', self.mcboRasterLayer.currentLayer().name()) settingsStr += '\n {:20}\t{}'.format('Image Band:', self.cboBand.currentText()) 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()) else: settingsStr += '\n {:20}\t{}'.format('Boundary layer:', '') settingsStr += '\n {:20}\t{}'.format('Block ID field:', '') settingsStr += '\n {:20}\t{}'.format('Resample pixel size: ', self.dsbPixelSize.value()) 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() band_num = [int(self.cboBand.currentText().replace('Band ', ''))] files = resample_bands_to_block( lyrRaster.source(), self.dsbPixelSize.value(), self.lneOutputFolder.text(), band_nums=band_num, 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: removeFileFromQGIS(ea_file) addRasterFileToQGIS(ea_file, group_layer_name=os.path.basename( os.path.dirname(ea_file)), atTop=False) self.cleanMessageBars(True) self.fraMain.setDisabled(False) self.iface.mainWindow().statusBar().clearMessage() self.iface.messageBar().popWidget() QtGui.qApp.restoreOverrideCursor() return super(ResampleImageToBlockDialog, 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
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) # Add settings to log settingsStr = 'Parameters:---------------------------------------' if self.chkUseSelected.isChecked(): settingsStr += '\n {:20}\t{} with {} selected features'.format( 'Strip points layer:', self.mcboPointsLayer.currentLayer().name(), self.mcboPointsLayer.currentLayer().selectedFeatureCount()) else: settingsStr += '\n {:20}\t{}'.format( 'Strip points layer:', self.mcboPointsLayer.currentLayer().name()) settingsStr += '\n {:20}\t{}'.format( 'Strip values raster:', self.mcboRasterLayer.currentLayer().name()) control_file, zone_file = ['', ''] if self.mcboCtrlRasterLayer.currentLayer() is not None: settingsStr += '\n {:20}\t{}'.format( 'Control values raster:', self.mcboCtrlRasterLayer.currentLayer().name()) control_file = get_layer_source( self.mcboCtrlRasterLayer.currentLayer()) if self.mcboZoneRasterLyr.currentLayer() is not None: settingsStr += '\n {:20}\t{}'.format( 'Control values raster:', self.mcboZoneRasterLyr.currentLayer().name()) zone_file = get_layer_source( self.mcboZoneRasterLyr.currentLayer()) settingsStr += '\n {:20}\t{}'.format( 'Moving window size: ', self.dsbMovingWinSize.value()) settingsStr += '\n {:30}\t{}\n'.format( 'Output folder:', self.lneOutputFolder.text()) LOGGER.info(settingsStr) lyrPoints = self.mcboPointsLayer.currentLayer() if self.chkUseSelected.isChecked() or lyrPoints.providerType( ) == 'delimitedtext': savePtsName = lyrPoints.name() + '_strippts.shp' fileStripPts = os.path.join(TEMPDIR, savePtsName) if os.path.exists(fileStripPts): removeFileFromQGIS(fileStripPts) QgsVectorFileWriter.writeAsVectorFormat( lyrPoints, fileStripPts, "utf-8", lyrPoints.crs(), driverName="ESRI Shapefile", onlySelected=self.chkUseSelected.isChecked()) if self.DISP_TEMP_LAYERS: addVectorFileToQGIS(fileStripPts, layer_name=os.path.splitext( os.path.basename(fileStripPts))[0], group_layer_name='DEBUG', atTop=True) else: fileStripPts = get_layer_source(lyrPoints) points_desc = describe.VectorDescribe(fileStripPts) gdf_pts = points_desc.open_geo_dataframe() df_table = ttest_analysis(gdf_pts, points_desc.crs, get_layer_source( self.mcboRasterLayer.currentLayer()), self.lneOutputFolder.text(), zone_file, control_file, size=self.dsbMovingWinSize.value()) self.cleanMessageBars(True) self.fraMain.setDisabled(False) self.iface.mainWindow().statusBar().clearMessage() self.iface.messageBar().popWidget() QApplication.restoreOverrideCursor() return super(tTestAnalysisDialog, self).accept(*args, **kwargs) except Exception as err: QApplication.restoreOverrideCursor() self.iface.mainWindow().statusBar().clearMessage() self.cleanMessageBars(True) self.fraMain.setDisabled(False) self.send_to_messagebar(str(err), level=Qgis.Critical, duration=0, addToLog=True, core_QGIS=False, showLogPanel=True, exc_info=sys.exc_info()) 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
def accept(self, *args, **kwargs): if not self.validate(): return False try: # disable form via a frame, this will still allow interaction with the message bar self.stackedWidget.setDisabled(True) # clean gui and Qgis messagebars self.cleanMessageBars(True) # self.iface.messageBar().clearWidgets() # Change cursor to Wait cursor QApplication.setOverrideCursor(QtCore.Qt.WaitCursor) self.iface.mainWindow().statusBar().showMessage('Processing {}'.format(self.windowTitle())) 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) gp_layer_name = '' LOGGER.info('{st}\nProcessing {}'.format(self.windowTitle(), st='*' * 50)) # Add settings to log settingsStr = 'Parameters:---------------------------------------' if self.optFile.isChecked(): settingsStr += '\n {:30}\t{}'.format('File:', self.lneInCSVFile.text()) settingsStr += '\n {:30}\t{}, {}'.format('Geometry Fields:', self.cboXField.currentText(), self.cboYField.currentText()) settingsStr += '\n {:30}\t{} - {}'.format('CSV Coordinate System:', self.qgsCRScsv.crs().authid(), self.qgsCRScsv.crs().description()) else: 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()) crs_units = QgsUnitTypes.toString(self.mCRSoutput.crs().mapUnits()) settingsStr += '\n {:30}\t{} {}'.format('Thinning Distance:', self.dsbThinDist.value(),crs_units) settingsStr += '\n {:30}\t{} {}'.format("Aggregate Distance:", self.dsbAggregateDist.value(),crs_units) settingsStr += '\n {:30}\t{} {}'.format("Buffer Distance:", self.dsbBufferDist.value(),crs_units) settingsStr += '\n {:30}\t{} {}'.format("Shrink Distance:", self.dsbShrinkDist.value(),crs_units) settingsStr += '\n {:30}\t{}'.format('Output Polygon Shapefile:', self.lneSavePolyFile.text()) if self.lneSavePointsFile.text() == '': settingsStr += '\n {:30}\t{}'.format('Saved Points Shapefile:', self.lneSavePointsFile.text()) settingsStr += '\n {:30}\t{} - {}\n\n'.format('Output Projected Coordinate System:', self.mCRSoutput.crs().authid(), self.mCRSoutput.crs().description()) LOGGER.info(settingsStr) stepTime = time.time() if self.optFile.isChecked(): in_epsg = int(self.qgsCRScsv.crs().authid().replace('EPSG:','')) in_crs = self.qgsCRScsv.crs() else: in_epsg =self.mcboTargetLayer.currentLayer().crs().authid().replace('EPSG:','') in_crs = self.mcboTargetLayer.currentLayer().crs() out_epsg = int(self.mCRSoutput.crs().authid().replace('EPSG:','')) filePoly = None gdfPoints = None filePoints = None if self.optFile.isChecked(): if self.DEBUG: filePoints = os.path.join(TEMPDIR, os.path.splitext(os.path.basename(self.lneSavePolyFile.text()))[0] + '_table2pts.shp') if os.path.splitext(self.lneInCSVFile.text())[-1] == '.csv': gdfPoints, gdfPtsCrs = convert.convert_csv_to_points(self.lneInCSVFile.text() , out_shapefilename=filePoints, coord_columns=[self.cboXField.currentText(), self.cboYField.currentText()], coord_columns_epsg=in_epsg) elif os.path.splitext(self.lneInCSVFile.text())[-1] in ['.xls', '.xlsx', '.ods']: xls_file = pd.ExcelFile(self.lneInCSVFile.text()) pdfxls = xls_file.parse(self.sheet(), skiprows=self.linesToIgnore() - 1) del xls_file gdfPoints, gdfPtsCrs = convert.add_point_geometry_to_dataframe(pdfxls, coord_columns=[ self.cboXField.currentText(), self.cboYField.currentText()], coord_columns_epsg=in_epsg) del pdfxls LOGGER.info('{:<30} {d:<15} {}'.format('Add Geometry to Table','', d=str(timedelta(seconds=time.time() - stepTime)))) stepTime = time.time() if filePoints is not None: describe.save_geopandas_tofile(gdfPoints, filePoints) #, file_encoding=self.file_encoding) if self.DISP_TEMP_LAYERS and filePoints is not None: addVectorFileToQGIS(filePoints, layer_name=os.path.splitext(os.path.basename(filePoints))[0], group_layer_name='DEBUG', atTop=True) else: layerPts = self.mcboTargetLayer.currentLayer() if layerPts.providerType() == 'delimitedtext' or \ os.path.splitext(get_layer_source(layerPts))[-1] == '.vrt' or \ self.chkUseSelected.isChecked() or self.optFile.isChecked(): filePoints = os.path.join(TEMPDIR, "{}_points.shp".format(layerPts.name())) if self.chkUseSelected.isChecked(): filePoints = os.path.join(TEMPDIR, "{}_selected_points.shp".format(layerPts.name())) if os.path.exists(filePoints): removeFileFromQGIS(filePoints) ptsLayer = copyLayerToMemory(layerPts, layerPts.name() + "_memory", bAddUFI=True, bOnlySelectedFeat=self.chkUseSelected.isChecked()) _writer = QgsVectorFileWriter.writeAsVectorFormat(ptsLayer, filePoints, "utf-8", self.mCRSoutput.crs(), driverName="ESRI Shapefile") LOGGER.info('{:<30} {d:<15} {}'.format('Save layer/selection to file',filePoints, d=str(timedelta(seconds=time.time() - stepTime) ))) stepTime = time.time() del ptsLayer if self.DISP_TEMP_LAYERS: addVectorFileToQGIS(filePoints, layer_name=os.path.splitext(os.path.basename(filePoints))[0], group_layer_name='DEBUG', atTop=True) else: filePoints = get_layer_source(layerPts) if gdfPoints is None: ptsDesc = describe.VectorDescribe(filePoints) gdfPtsCrs = ptsDesc.crs gdfPoints = ptsDesc.open_geo_dataframe() if in_crs.authid() != self.mCRSoutput.crs().authid(): gdfPoints = gdfPoints.to_crs(epsg=out_epsg) gdfPtsCrs = pyprecag_crs.crs() gdfPtsCrs.getFromEPSG(out_epsg) LOGGER.info('{:<30} {d:<15} {} to {}'.format('Reproject points', in_crs.authid(), self.mCRSoutput.crs().authid(), d=str(timedelta(seconds=time.time() - stepTime)))) if self.DEBUG: filePoints = os.path.join(TEMPDIR, os.path.basename(self.lneSavePolyFile.text().replace('.csv', '_ptsprj.shp'))) removeFileFromQGIS(filePoints) describe.save_geopandas_tofile(gdfPoints, filePoints) if self.DISP_TEMP_LAYERS: if self.DEBUG: addVectorFileToQGIS(filePoints, layer_name=os.path.splitext(os.path.basename(filePoints))[0], group_layer_name='DEBUG', atTop=True) else: addVectorFileToQGIS(filePoints, layer_name=os.path.splitext(os.path.basename(filePoints))[0], atTop=True) stepTime = time.time() result = processing.create_polygon_from_point_trail(gdfPoints, gdfPtsCrs, out_filename=self.lneSavePolyFile.text(), thin_dist_m=self.dsbThinDist.value(), aggregate_dist_m=self.dsbAggregateDist.value(), buffer_dist_m=self.dsbBufferDist.value(), shrink_dist_m=self.dsbShrinkDist.value()) addVectorFileToQGIS(self.lneSavePolyFile.text(), atTop=True) self.cleanMessageBars(True) self.stackedWidget.setDisabled(False) QApplication.restoreOverrideCursor() self.iface.messageBar().popWidget() self.iface.mainWindow().statusBar().clearMessage() if result is not None: self.fraMain.setDisabled(False) self.send_to_messagebar(result, level=Qgis.Warning, duration=0, addToLog=False) return False # leave dialog open return super(PointTrailToPolygonDialog, self).accept(*args, **kwargs) except Exception as err: QApplication.restoreOverrideCursor() self.iface.mainWindow().statusBar().clearMessage() self.cleanMessageBars(True) self.stackedWidget.setDisabled(False) self.send_to_messagebar(str(err), level=Qgis.Critical, duration=0, addToLog=True, core_QGIS=False, showLogPanel=True, exc_info=sys.exc_info()) 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 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) # Add settings to log settingsStr = 'Parameters:---------------------------------------' settingsStr += '\n {:20}\t{}'.format( 'Line layer:', self.mcboLineLayer.currentLayer().name()) settingsStr += '\n {:20}\t{}'.format( 'Distance between points (m):', self.dsbDistBtwnPoints.value()) settingsStr += '\n {:20}\t{}'.format( 'Line offset distance (m):', self.dsbLineOffsetDist.value()) if self.chkUseSelected.isChecked(): settingsStr += '\n {:20}\t{} with {} selected features'.format( 'Layer:', self.mcboLineLayer.currentLayer().name(), self.mcboLineLayer.currentLayer().selectedFeatureCount()) settingsStr += '\n {:30}\t{} - {}'.format( 'Output coordinate system:', self.mCRSoutput.crs().authid(), self.mCRSoutput.crs().description()) settingsStr += '\n {:30}\t{}'.format( 'Output points :', self.lneSavePointsFile.text()) if self.lneSaveLinesFile.text() == '': settingsStr += '\n {:30}\t{}\n'.format( 'Output lines:', self.lneSaveLinesFile.text()) LOGGER.info(settingsStr) lyr_line = self.mcboLineLayer.currentLayer() if self.chkUseSelected.isChecked(): line_shapefile = os.path.join(TEMPDIR, lyr_line.name() + '_lines.shp') if os.path.exists(line_shapefile): removeFileFromQGIS(line_shapefile) QgsVectorFileWriter.writeAsVectorFormat( lyr_line, line_shapefile, "utf-8", self.mCRSoutput.crs(), driverName="ESRI Shapefile", onlySelected=True) if self.DISP_TEMP_LAYERS: addVectorFileToQGIS( line_shapefile, layer_name=os.path.splitext( os.path.basename(line_shapefile))[0], group_layer_name='DEBUG', atTop=True) else: line_shapefile = get_layer_source(lyr_line) lines_desc = describe.VectorDescribe(line_shapefile) gdf_lines = lines_desc.open_geo_dataframe() epsgOut = int(self.mCRSoutput.crs().authid().replace('EPSG:', '')) out_lines = None if self.lneSaveLinesFile.text() == '': out_lines = self.lneSaveLinesFile.text() _ = create_points_along_line( gdf_lines, lines_desc.crs, self.dsbDistBtwnPoints.value(), self.dsbLineOffsetDist.value(), epsgOut, out_points_shapefile=self.lneSavePointsFile.text(), out_lines_shapefile=out_lines) out_lyr_points = addVectorFileToQGIS( self.lneSavePointsFile.text(), atTop=True, layer_name=os.path.splitext( os.path.basename(self.lneSavePointsFile.text()))[0]) vector_apply_unique_value_renderer(out_lyr_points, 'Strip_Name') if self.lneSaveLinesFile.text() == '': out_lyr_lines = addVectorFileToQGIS( self.lneSaveLinesFile.text(), atTop=True, layer_name=os.path.splitext( os.path.basename(self.lneSaveLinesFile.text()))[0]) vector_apply_unique_value_renderer(out_lyr_lines, 'Strip_Name') self.cleanMessageBars(True) self.fraMain.setDisabled(False) self.iface.mainWindow().statusBar().clearMessage() self.iface.messageBar().popWidget() QApplication.restoreOverrideCursor() return super(StripTrialPointsDialog, self).accept(*args, **kwargs) except Exception as err: QApplication.restoreOverrideCursor() self.iface.mainWindow().statusBar().clearMessage() self.cleanMessageBars(True) self.fraMain.setDisabled(False) self.send_to_messagebar(str(err), level=Qgis.Critical, duration=0, addToLog=True, core_QGIS=False, showLogPanel=True, exc_info=sys.exc_info()) return False # leave dialog open
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 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) 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.lblNoDataVal.text()) if self.mcboPolygonLayer.currentLayer() is not None: if self.chkUseSelected.isChecked(): settingsStr += '\n {:20}\t{} with {} selected features'.format('Layer:', self.mcboPolygonLayer.currentLayer().name(), self.mcboPolygonLayer.currentLayer().selectedFeatureCount()) 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.items(): 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.mCRSoutput.crs().authid(), self.mCRSoutput.crs().description()) settingsStr += '\n {:30}\t{}\n'.format('Output Folder:', self.lneOutputFolder.text()) LOGGER.info(settingsStr) lyrRaster = self.mcboRasterLayer.currentLayer() filePoly=None if self.mcboPolygonLayer.currentLayer() is not None: 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(), driverName="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 = get_layer_source(lyrBoundary) # convert string to float or int without knowing which x = self.lneNoDataVal.text() nodata_val = int(float(x)) if int(float(x)) == float(x) else float(x) files = calc_indices_for_block(get_layer_source(lyrRaster), self.dsbPixelSize.value(), self.band_mapping, self.lneOutputFolder.text(), indices=selectedIndices, image_epsg=int(lyrRaster.crs().authid().replace('EPSG:', '')), image_nodata=nodata_val, polygon_shapefile=filePoly, groupby=self.mFieldComboBox.currentField() if self.mFieldComboBox.currentField() else None, out_epsg=int(self.mCRSoutput.crs().authid().replace('EPSG:', ''))) if self.chkAddToDisplay.isChecked(): for ea_file in files: raster_sym = RASTER_SYMBOLOGY['Image Indices (ie PCD, NDVI)'] group_name = os.path.basename(os.path.dirname(ea_file)) if self.mFieldComboBox.currentField(): group_name = os.path.basename(ea_file).split('_')[0] + ' - ' + os.path.basename(os.path.dirname(ea_file)) raster_lyr = addRasterFileToQGIS(ea_file,atTop=False, group_layer_name=group_name) 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() QApplication.restoreOverrideCursor() return super(CalculateImageIndicesDialog, self).accept(*args, **kwargs) except Exception as err: QApplication.restoreOverrideCursor() self.iface.mainWindow().statusBar().clearMessage() self.cleanMessageBars(True) self.fraMain.setDisabled(False) self.send_to_messagebar(str(err), level=Qgis.Critical, duration=0, addToLog=True, core_QGIS=False, showLogPanel=True, exc_info=sys.exc_info()) return False # leave dialog open
def accept(self, *args, **kwargs): if not self.validate(): return False try: QApplication.setOverrideCursor(QtCore.Qt.WaitCursor) LOGGER.info('{st}\nProcessing {} Raster'.format( self.cboMethod.currentText(), st='*' * 50)) self.iface.mainWindow().statusBar().showMessage( 'Processing {} Raster'.format(self.cboMethod.currentText())) # Add settings to log settingsStr = 'Parameters:---------------------------------------' settingsStr += '\n {:30}\t{}'.format( 'Layer:', self.mcboTargetLayer.currentLayer().name()) settingsStr += '\n {:30}\t{}'.format('For Band: ', self.cboBand.currentText()) settingsStr += '\n {:30}\t{}'.format( 'Method: ', self.cboMethod.currentText()) if self.cboMethod.currentText() == 'Rescale': settingsStr += '\n {:30}\t{} - {}'.format( 'Between:', self.dsbRescaleLower.value(), self.dsbRescaleUpper.value()) settingsStr += '\n {:30}\t{}'.format( 'Output Raster File:', self.lneSaveRasterFile.text()) LOGGER.info(settingsStr) lyrTarget = self.mcboTargetLayer.currentLayer() rasterOut = self.lneSaveRasterFile.text() removeFileFromQGIS(rasterOut) rasterIn = get_layer_source(lyrTarget) # need this to maintain correct wkt otherwise gda/mga defaults to utm zonal in_crswkt = lyrTarget.crs().toWkt() band_num = int(self.cboBand.currentText().replace('Band ', '')) with rasterio.open(os.path.normpath(rasterIn)) as src: if self.cboMethod.currentText() == 'Rescale': rast_result = rescale(src, self.dsbRescaleLower.value(), self.dsbRescaleUpper.value(), band_num=band_num, ignore_nodata=True) else: rast_result = normalise(src, band_num=band_num, ignore_nodata=True) meta = src.meta.copy() meta['crs'] = str(in_crswkt) meta['count'] = 1 meta['dtype'] = rasterio.float32 with rasterio.open(os.path.normpath(rasterOut), 'w', **meta) as dst: dst.write_band(1, rast_result) rasterLyr = addRasterFileToQGIS(rasterOut, atTop=False) QApplication.restoreOverrideCursor() self.iface.mainWindow().statusBar().clearMessage() return super(RescaleNormaliseDialog, self).accept(*args, **kwargs) except Exception as err: QApplication.restoreOverrideCursor() self.cleanMessageBars(True) self.iface.mainWindow().statusBar().clearMessage() self.send_to_messagebar(str(err), level=Qgis.Critical, duration=0, addToLog=True, exc_info=sys.exc_info()) return False # leave dialog open