def calculTOA8(self): V_sunElevation = float(self.dlg.lbl_sunelevangle.text()) V_reflectanceMult = float( str(self.dlg.tableWidget_MetaData.item(1, 3).text())) V_reflectanceAdd = float( str(self.dlg.tableWidget_MetaData.item(1, 4).text())) input_raster = QgsRasterLayer( '/SatDownloaded/image2/LC08_L1TP_201035_20190107_20190130_01_T1/LC08_L1TP_201035_20190107_20190130_01_T1_B2.TIF', 'Raster') QgsProject.instance().addMapLayer(input_raster) output_raster = '/SatDownloaded/image2/imageTOAB2_2.TIF' parameters = { 'INPUT_A': input_raster, 'BAND_A': 1, 'FORMULA': "((({0}*A)+{1})/sin(radians({2})))".format(V_reflectanceMult, V_reflectanceAdd, V_sunElevation), 'OUTPUT': output_raster } processing.runAndLoadResults('gdal:rastercalculator', parameters)
def calculTOA7(self): V_sunDistance = float(self.dlg.lbl_earthsundistance.text()) V_sunElevation = float(self.dlg.lbl_sunelevangle.text()) V_Pi = pi V_Esun = float(str(self.dlg.tableWidget_MetaData.item(1, 11).text())) print("V_sund,V_sunelev,V_pi,V_Esun", V_sunDistance, V_sunElevation, V_Pi, V_Esun) #A=float(193) #var=({0}*A*pow({1},2))/({2}+cos(radians(90-{3}))).format(V_Pi,V_sunDistance,V_Esun,V_sunElevation) #var=(V_Pi*193*pow(V_sunDistance,2))/(V_Esun*sin(radians(V_sunElevation))) #print(var) input_raster = QgsRasterLayer( '/SatDownloaded/image3/imageRadiance7B2_1.TIF', 'Raster') QgsProject.instance().addMapLayer(input_raster) output_raster = '/SatDownloaded/image3/imageTOA7B2_1.TIF' parameters = { 'INPUT_A': input_raster, 'BAND_A': 1, 'FORMULA': "({0}*A*pow({1},2))/({2}*sin(radians({3})))".format( V_Pi, V_sunDistance, V_Esun, V_sunElevation), 'OUTPUT': output_raster } processing.runAndLoadResults('gdal:rastercalculator', parameters)
def calculradiance5(self): V_lmax = float(str(self.dlg.tableWidget_MetaData.item(5, 7).text())) V_lmin = float(str(self.dlg.tableWidget_MetaData.item(5, 8).text())) V_Qcalmax = float(str(self.dlg.tableWidget_MetaData.item(5, 9).text())) V_Qcalmin = float(str( self.dlg.tableWidget_MetaData.item(5, 10).text())) print('qlmax qlmin lmax lmin', V_Qcalmax, V_Qcalmin, V_lmax, V_lmin) #V_lmax=float(193) #V_lmin=float(-1.52) #V_Qcalmax=float(255) #V_Qcalmin=float(1) #print("eval((((({0}-{1})*(255-{3}))/({2}-{3}))+{1})".format(V_lmax,V_lmin,V_Qcalmax,V_Qcalmin))) #'FORMULA': "((((((193 + 1.52) * A)/ 255 )) - 1.52))" #'FORMULA': "(((((({0} - {1}) * A)/ {2} )) + {1}))".format(V_lmax,V_lmin,V_Qcalmax), #'FORMULA': "(( ( ({0} - {1}) * (A-{3}) )/ ({2}-{3})) + {1})".format(V_lmax,V_lmin,V_Qcalmax,V_Qcalmin) input_raster = QgsRasterLayer( '/SatDownloaded/image2/LC08_L1TP_201035_20190107_20190130_01_T1/LC08_L1TP_201035_20190107_20190130_01_T1_B2.TIF', 'Raster') QgsProject.instance().addMapLayer(input_raster) output_raster = '/SatDownloaded/image2/imageRadiance8B2_1.TIF' parameters = { 'INPUT_A': input_raster, 'BAND_A': 1, 'FORMULA': "((((({0}-{1})/({2}-{3})) * (A-{3})))+{1})".format( V_lmax, V_lmin, V_Qcalmax, V_Qcalmin), 'OUTPUT': output_raster } processing.runAndLoadResults('gdal:rastercalculator', parameters)
def canvasPressEvent(self, e): DEPARR = ( "DEPARTURE" if self.action.widget.deparrComboBox.currentIndex() == 0 else "ARRIVAL" ) input_layer = pointToLayer(self.toMapCoordinates(self.canvas.mouseLastXY())) time = self.action.widget.dateTimeEdit.dateTime().toUTC().toString(Qt.ISODate) travel_time = self.action.widget.travelTimeSpinBox.value() * 60 transpt_type = self.action.widget.transptTypeComboBox.currentText() params = { "INPUT_" + DEPARR + "_SEARCHES": input_layer, "INPUT_" + DEPARR + "_TIME": "'" + time + "'", "INPUT_" + DEPARR + "_TRAVEL_TIME": travel_time, "INPUT_" + DEPARR + "_TRNSPT_TYPE": "'" + transpt_type + "'", "OUTPUT": "memory:", } feedback = Feedback() try: # TODO : use QgsProcessingAlgRunnerTask to do this as a bg task processing.runAndLoadResults("ttp_v4:time_map", params, feedback=feedback) except QgsProcessingException as e: self.action.main.iface.messageBar().pushMessage( "Error", ", ".join(feedback.fatal_errors), level=Qgis.Critical )
def calculradiance7(self): V_lmax = float(str(self.dlg.tableWidget_MetaData.item(5, 7).text())) V_lmin = float(str(self.dlg.tableWidget_MetaData.item(5, 8).text())) V_Qcalmax = float(str(self.dlg.tableWidget_MetaData.item(5, 9).text())) V_Qcalmin = float(str( self.dlg.tableWidget_MetaData.item(5, 10).text())) print('qlmax qlmin lmax lmin', V_Qcalmax, V_Qcalmin, V_lmax, V_lmin) input_raster = QgsRasterLayer( '/SatDownloaded/image3/LE07_L1TP_201035_20030103_20170214_01_T1_B6_VCID_1.TIF', 'Raster') QgsProject.instance().addMapLayer(input_raster) output_raster = '/SatDownloaded/image3/imageRadiance7B6_1_4.TIF' parameters = { 'INPUT_A': input_raster, 'BAND_A': 1, 'FORMULA': "((((({0}-{1})/({2}-{3})) * (A-{3})))+{1})".format( V_lmax, V_lmin, V_Qcalmax, V_Qcalmin), 'OUTPUT': output_raster } processing.runAndLoadResults('gdal:rastercalculator', parameters)
def make_hillshade(raster, path): layers = QgsProject.instance().mapLayers( ) #returns a dict, values = layer object hs_name = 'hs_' + raster.name() for layer in layers.values(): if layer.name() == hs_name: QgsProject.instance().removeMapLayer(layer) hs_param = { 'INPUT': "", 'BAND': 1, 'COMPUTE_EDGES': False, 'ZEVENBERGEN': False, 'Z_FACTOR': 1.0, 'SCALE': 1, #111120, # should automate this setting to match the coordinate system 'AZIMUTH': 315, 'COMBINED': False, 'ALTITUDE': 45, 'MULTIDIRECTIONAL': False, 'OUTPUT': "" } hs_param['INPUT'] = raster.name() hs_param['OUTPUT'] = path + hs_name + '.tif' processing.runAndLoadResults('gdal:hillshade', hs_param) return QgsProject.instance().mapLayersByName(hs_name)[0]
def execute_processing(self, get_active_layer=True): tools_log.log_info("execute_processing") if get_active_layer: layer = global_vars.iface.activeLayer() else: filename = 'geopackage.gpkg' filepath = os.path.join(global_vars.plugin_dir, 'data', filename) if not os.path.exists(filepath): tools_qgis.show_warning(f"File not found: {filepath}") return layer = f"{filepath}|layername=cities" if layer is None: tools_qgis.show_warning("Any layer selected") return # Execute 'buffer' from processing toolbox params = { 'INPUT': layer, 'DISTANCE': 10, 'SEGMENTS': 5, 'END_CAP_STYLE': 0, 'JOIN_STYLE': 0, 'MITER_LIMIT': 2, 'DISSOLVE': False, 'OUTPUT': 'memory:' } processing.runAndLoadResults("native:buffer", params)
def total_households(self, household, boundary, field, fields, summary, outname): ''' Number of households Perform join attributes by location (summary) [count] ''' outfield = "{field}_HOUSEHOLDS".format(field=field) field_expression = 'IF("{outfield}" IS NULL, 0, "{outfield}")'.format( outfield=outfield) parameters = { 'INPUT': boundary, 'JOIN': household, 'PREDICATE': [0], 'JOIN_FIELDS': fields, 'SUMMARIES': [0], 'DISCARD_NONMATCHING': False, 'OUTPUT': 'memory:' } processing.runAndLoadResults("qgis:joinbylocationsummary", parameters) layer_1 = QgsProject.instance().mapLayersByName("Joined layer")[0] refactor_fields(layer_1, [["{}_count".format(field), outfield]]) QgsProject.instance().removeMapLayers([layer_1.id()]) layer = QgsProject.instance().mapLayersByName("Refactored")[0] layer.setName(outname) # self.add_symbology(layer, outfield) add_ranged_symbology(layer, field_expression, COUNT_HH_COLORS) add_labels(layer, field_expression)
def tool_clicked(self, point): params = self.make_params(point) class Feedback(QgsProcessingFeedback): def __init__(self): super().__init__() self.fatal_errors = [] def reportError(self, error, fatalError=False): log(error) if fatalError: self.fatal_errors.append(error) feedback = Feedback() try: # TODO : use QgsProcessingAlgRunnerTask to do this as a bg task processing.runAndLoadResults(self._algorithm, params, feedback=feedback) except QgsProcessingException as e: print(e) self.main.iface.messageBar().pushMessage( "Error", ", ".join(feedback.fatal_errors), level=Qgis.Critical, duration=0, )
def runProcessingModel(self, parametersData): doc = QDomDocument() doc.setContent(parametersData['model_xml']) model = core.QgsProcessingModelAlgorithm() model.loadVariant(core.QgsXmlUtils.readVariant( doc.firstChildElement())) processing.runAndLoadResults(model, {}) return "<p style=\"color:green\">{0}</p>".format( 'Rotina executada com sucesso!')
def load_trees_layer(): uri = "file://{}/trees.csv?type=csv&detectTypes=yes&xField=lon&yField=lat&crs=EPSG:4326&spatialIndex=no&subsetIndex=no&watchFile=no".format(os.getcwd()) vlayer = QgsVectorLayer(uri, 'trees', 'delimitedtext') project.addMapLayer(vlayer) processing.runAndLoadResults("native:reprojectlayer", {'INPUT': 'trees', 'TARGET_CRS': 'EPSG:3857', 'OUTPUT': 'trees3857'}) remove_layer('trees') rename_layer('Reprojected', 'trees')
def select_by_location(zone_name): """ Selects parcels from all_2019_parcels which are within the spatial boundary of a given zone """ parameters = { 'INPUT': 'dbname=\'BRE_2019_Test\' host=localhost port=5432 sslmode=disable key=\'id_1\' srid=2264 type=MultiPolygon checkPrimaryKeyUnicity=\'1\' table=\"public\".\"All_Parcels_2019\" (geom)', 'INTERSECT': f'postgres://dbname=\'BRE_2019_Test\' host=localhost port=5432 sslmode=disable key=\'id_2\' srid=2264 type=MultiPolygon checkPrimaryKeyUnicity=\'1\' table=\"public\".\"{zone_name}\" (geom)', 'METHOD': 0, 'PREDICATE': [6] } processing.runAndLoadResults('native:selectbylocation', parameters)
def create_join(): # processing.algorithmHelp("qgis:joinbylocationsummary") parameters = { 'INPUT': 'grid', 'JOIN': 'trees', 'PREDICATE': 0, # intersects 'JOIN_FIELDS': 'damage', 'SUMMARIES': 6, # mean 'DISCARD_NONMATCHING': True, 'OUTPUT': 'mean_damage_index' } processing.runAndLoadResults( "qgis:joinbylocationsummary", parameters) rename_layer('Joined layer', 'mean_damage_index')
def postprocess(self, inputs, response): csv_uri = 'file:///' + response.filepath + '?delimiter=,' csv = QgsVectorLayer(csv_uri, "process {} output".format('d-rain-csv'), 'delimitedtext') QgsProject.instance().addMapLayer(csv) layer = None layerField = None csvField = None for param, widget in inputs.items(): if isinstance(widget, QgsMapLayerComboBox): # TODO check input type and export into it (GML, GeoPackage, etc.) layer = widget.currentLayer() elif isinstance(widget, QgsFieldComboBox): layerField = widget.currentField() csvField = csv.fields()[0].name() if layer is not None and layerField is not None and csv is not None and csvField is not None: import processing parameters = { 'DISCARD_NONMATCHING': False, 'FIELD': layerField, 'FIELDS_TO_COPY': [], 'FIELD_2': csvField, 'INPUT': layer.source(), 'INPUT_2': csv.source(), 'METHOD': 1, 'OUTPUT': 'TEMPORARY_OUTPUT', 'PREFIX': '' } result = processing.runAndLoadResults('qgis:joinattributestable', parameters)
def count_overlap(layer, out): """ :param layer: the polygon footprint :param out: the output :return: return layer """ params_join = { 'INPUT': layer, 'JOIN': layer, 'PREDICATE': [2], 'JOIN_FIELDS': [], 'SUMMARIES': [0], 'DISCARD_NONMATCHING': False, 'PREFIX': '', 'OUTPUT': 'TEMPORARY_OUTPUT' } result = processing.run("qgis:joinbylocationsummary", params_join) params_delete = {'INPUT': result['OUTPUT'], 'OUTPUT': 'TEMPORARY_OUTPUT'} if out == []: params_delete['OUTPUT'] = out result = processing.runAndLoadResults("qgis:deleteduplicategeometries", params_delete)
def testRunAndLoadResults(self): QgsProject.instance().removeAllMapLayers() context = QgsProcessingContext() # try running an alg using processing.runAndLoadResults - ownership of result layer should be transferred to # project, and layer should be present in project res = processing.runAndLoadResults( 'qgis:buffer', { 'DISTANCE': 1, 'INPUT': points(), 'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT }, context=context) self.assertIn('OUTPUT', res) # output should be the layer path self.assertIsInstance(res['OUTPUT'], str) self.assertEqual( context.layersToLoadOnCompletion()[res['OUTPUT']].project, QgsProject.instance()) layer = QgsProject.instance().mapLayer(res['OUTPUT']) self.assertIsInstance(layer, QgsVectorLayer) # Python should NOT have ownership self.assertFalse(sip.ispyowned(layer))
def CalculBrightness8(self): V_K1 = float(str(self.dlg.tableWidget_MetaData.item(9, 5).text())) V_K2 = float(str(self.dlg.tableWidget_MetaData.item(9, 6).text())) print("V_1,V_2", V_K1, V_K2) input_raster = QgsRasterLayer( '/SatDownloaded/image2/imageRadiance8B10_1.TIF', 'Raster') QgsProject.instance().addMapLayer(input_raster) output_raster = '/SatDownloaded/image2/BT_L8_B10.TIF' parameters = { 'INPUT_A': input_raster, 'BAND_A': 1, 'FORMULA': "((({0})/(log(({1}/A)+1)))-273.15)".format(V_K2, V_K1), 'OUTPUT': output_raster } processing.runAndLoadResults('gdal:rastercalculator', parameters)
def moyenne(self): input_rasterA = QgsRasterLayer( '/SatDownloaded/image3/imageTraiteeBT77Celcius.TIF', 'Raster1') QgsProject.instance().addMapLayer(input_rasterA) input_rasterB = QgsRasterLayer( '/SatDownloaded/image3/imageTraiteeBT88Celcius.TIF', 'Raster2') QgsProject.instance().addMapLayer(input_rasterB) output_raster = '/SatDownloaded/image3/imageRadianceMoy.TIF' parameters = { 'INPUT_A': input_rasterA, 'INPUT_B': input_rasterB, 'BAND_A': 1, 'BAND_B': 1, 'FORMULA': "((A+B)/2)", 'OUTPUT': output_raster } processing.runAndLoadResults('gdal:rastercalculator', parameters)
def clipLayer(bottomLayer, overlayLayer): clipLineLayer = ComparisonController.checkVectorLayer( ComparisonController.lineLayerName + ' clipped', None, False) if clipLineLayer is None: # Create clip processing.runAndLoadResults( 'qgis:clip', { "INPUT": bottomLayer, "OVERLAY": overlayLayer, "OUTPUT": 'memory:clip' }) # Update layer name and symbology clipLineLayer = ComparisonController.getActiveLayer() clipLineLayer.setName(ComparisonController.lineLayerName + ' clipped') ComparisonController.showMessage( "%s clipped to the extent of the %s." % (ComparisonController.lineLayerName, ComparisonController.refLayerName), Qgis.Info) return clipLineLayer
def calculradiance8(self): V_radianceMult = float( str(self.dlg.tableWidget_MetaData.item(9, 1).text())) V_radianceAdd = float( str(self.dlg.tableWidget_MetaData.item(9, 2).text())) print('vradmult,vradadd', V_radianceMult, V_radianceAdd) #Formula------------------ input_raster = QgsRasterLayer( '/SatDownloaded/image2/LC08_L1TP_201035_20190107_20190130_01_T1/LC08_L1TP_201035_20190107_20190130_01_T1_B10.TIF', 'Raster') QgsProject.instance().addMapLayer(input_raster) output_raster = '/SatDownloaded/image2/imageRadiance8B10_1.TIF' parameters = { 'INPUT_A': input_raster, 'BAND_A': 1, 'FORMULA': "(({0} * A)+{1})".format(V_radianceMult, V_radianceAdd), 'OUTPUT': output_raster } processing.runAndLoadResults('gdal:rastercalculator', parameters)
def postprocess(self, inputs, response): process_identifier = os.path.splitext(os.path.basename(__file__))[0] try: csv_uri = 'file:///' + response.output[ 'output'].filepath + '?delimiter=,' csv = QgsVectorLayer(csv_uri, "{} output".format(process_identifier), 'delimitedtext') QgsProject.instance().addMapLayer(csv) layer = None layerField = None csvField = None for param, widget in inputs.items(): if isinstance(widget, QgsMapLayerComboBox): layer = widget.currentLayer() elif isinstance(widget, QgsFieldComboBox): layerField = widget.currentField() csvField = csv.fields()[0].name() if layer is not None and layerField is not None and csv is not None and csvField is not None: parameters = { 'DISCARD_NONMATCHING': False, 'FIELD': layerField, 'FIELDS_TO_COPY': [], 'FIELD_2': csvField, 'INPUT': layer.source(), 'INPUT_2': csv.source(), 'METHOD': 1, 'OUTPUT': 'TEMPORARY_OUTPUT', 'PREFIX': '' } processing.runAndLoadResults('qgis:joinattributestable', parameters) except Exception as e: print(e) return None return 0
def canvasPressEvent(self, e): if self.point_a is None: self.point_a = self.toMapCoordinates(self.canvas.mouseLastXY()) self.marker = QgsVertexMarker(self.canvas) self.marker.setCenter(self.point_a) return DEPARR = ( "DEPARTURE" if self.action.widget.deparrComboBox.currentIndex() == 0 else "ARRIVAL" ) input_layer = pointToLayer(self.point_a) locations_layer = pointToLayer(self.toMapCoordinates(self.canvas.mouseLastXY())) time = self.action.widget.dateTimeEdit.dateTime().toUTC().toString(Qt.ISODate) transpt_type = self.action.widget.transptTypeComboBox.currentText() params = { "INPUT_" + DEPARR + "_SEARCHES": input_layer, "INPUT_LOCATIONS": locations_layer, "INPUT_" + DEPARR + "_TIME": time, "INPUT_" + DEPARR + "_TRNSPT_TYPE": "'" + transpt_type + "'", "OUTPUT_RESULT_TYPE": 1, "OUTPUT": "memory:", } feedback = Feedback() try: # TODO : use QgsProcessingAlgRunnerTask to do this as a bg task processing.runAndLoadResults("ttp_v4:routes", params, feedback=feedback) except QgsProcessingException as e: self.action.main.iface.messageBar().pushMessage( "Error", ", ".join(feedback.fatal_errors), level=Qgis.Critical ) self.cleanup()
def CalculBrightness7(self): V_K1 = float(str(self.dlg.tableWidget_MetaData.item(5, 5).text())) V_K2 = float(str(self.dlg.tableWidget_MetaData.item(5, 6).text())) print("V_1,V_2", V_K1, V_K2) var = ((1260.56) / (log((607.76 / 8.492) + 1))) print(var) #var=({0}*A*pow({1},2))/({2}+cos(radians(90-{3}))).format(V_Pi,V_sunDistance,V_Esun,V_sunElevation) #var=(V_Pi*193*pow(V_sunDistance,2))/(V_Esun*sin(radians(V_sunElevation))) #print(var) input_raster = QgsRasterLayer( '/SatDownloaded/image3/imageRadiance7B6_1_4.TIF', 'Raster') QgsProject.instance().addMapLayer(input_raster) output_raster = '/SatDownloaded/image3/imageTraiteeBT88Celcius.TIF' parameters = { 'INPUT_A': input_raster, 'BAND_A': 1, 'FORMULA': "((({0})/(log(({1}/A)+1)))-273.15)".format(V_K2, V_K1), 'OUTPUT': output_raster } processing.runAndLoadResults('gdal:rastercalculator', parameters)
def merge_tracks(): project = QgsProject.instance() layers_to_be_included = [] layerList = project.layerTreeRoot().findLayers() for layer in layerList: name = layer.name() if name.endswith('.geojson'): layers_to_be_included.append(name) processing.runAndLoadResults("native:mergevectorlayers", {'LAYERS': layers_to_be_included, 'CRS': QgsCoordinateReferenceSystem('EPSG:3857'), 'OUTPUT': 'memory:'}) processing.runAndLoadResults('native:simplifygeometries', {'INPUT': 'Merged', 'METHOD': 0, 'TOLERANCE': 10, 'OUTPUT': 'tracks'}) to_be_renamed = project.mapLayersByName('Simplified')[0] to_be_renamed.setName('tracks') layer = project.mapLayersByName('tracks')[0] layer.renderer().symbol().setWidth(1) layer.renderer().symbol().setColor(QColor('#ff0000')) layer.triggerRepaint()
def refactor_fields(layer, names): """Rename field""" fields = [{ 'name': f.name(), 'type': f.type(), 'length': f.length(), 'precision': f.precision(), 'expression': '"{}"'.format(f.name()) } for f in layer.fields()] oldnames = [n[0] for n in names] newnames = [n[1] for n in names] for f in fields: if f['name'] in oldnames: i = oldnames.index(f['name']) f['name'] = newnames[i] parameters = { 'INPUT': layer, 'FIELDS_MAPPING': fields, 'OUTPUT': 'memory:' } processing.runAndLoadResults("qgis:refactorfields", parameters)
def bufferLayer(layer, layerName, bufferSize): bufferedLayer = ComparisonController.checkVectorLayer( layerName + ' buffered', None, False) if bufferedLayer is None: # Create buffer processing.runAndLoadResults( 'qgis:buffer', { "INPUT": layer, "DISTANCE": bufferSize, "SEGMENTS": 5, "DISSOLVE": True, "END_CAP_STYLE": 0, "JOIN_STYLE": 0, "MITER_LIMIT": 2, "OUTPUT": 'memory:buffer' }) # Update layer name and symbology bufferedLayer = ComparisonController.getActiveLayer() bufferedLayer.setName(layerName + ' buffered') ComparisonController.showMessage( "%s buffered with %.2fm." % (layerName, bufferSize), Qgis.Info) return bufferedLayer
def run(self): """Run method that performs all the real work""" # Create the dialog with elements (after translation) and keep reference # Only create GUI ONCE in callback, so that it will only load when the plugin is started if self.first_start == True: self.first_start = False self.dlg = DissolveAndClipDialog() # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: # Do something useful here - delete the line containing pass and # substitute with your code. vector = self.dlg.dLayer.currentLayer() raster = self.dlg.cLayer.currentLayer() dissolve = processing.run("native:dissolve", { 'FIELD' : [], 'INPUT' : vector, 'OUTPUT' : 'memory' }) clip = processing.runAndLoadResults("gdal:cliprasterbymasklayer", { 'ALPHA_BAND' : False, 'CROP_TO_CUTLINE' : True, 'DATA_TYPE' : 0, 'EXTRA' : '', 'INPUT' :raster, 'KEEP_RESOLUTION' : False, 'MASK' : dissolve['OUTPUT'], 'MULTITHREADING' : False, 'NODATA' : None, 'OPTIONS' : '', 'OUTPUT' : 'TEMPORARY_OUTPUT', 'SET_RESOLUTION' : False, 'SOURCE_CRS' : None, 'TARGET_CRS' : None, 'X_RESOLUTION' : None, 'Y_RESOLUTION' : None })
def testRunAndLoadResults(self): QgsProject.instance().removeAllMapLayers() context = QgsProcessingContext() # try running an alg using processing.runAndLoadResults - ownership of result layer should be transferred to # project, and layer should be present in project res = processing.runAndLoadResults('qgis:buffer', {'DISTANCE': 1, 'INPUT': points(), 'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT}, context=context) self.assertIn('OUTPUT', res) # output should be the layer path self.assertIsInstance(res['OUTPUT'], str) self.assertEqual(context.layersToLoadOnCompletion()[res['OUTPUT']].project, QgsProject.instance()) layer = QgsProject.instance().mapLayer(res['OUTPUT']) self.assertIsInstance(layer, QgsVectorLayer) # Python should NOT have ownership self.assertFalse(sip.ispyowned(layer))
def postprocess(self, inputs, response): try: # print("POSTPROCESSING") # print(inputs) # print(response) csv_uri = 'file:///' + response.filepath + '?delimiter=,' # print(csv_uri) csv = QgsVectorLayer(csv_uri, "process {} output".format('d-rain-csv'), 'delimitedtext') QgsProject.instance().addMapLayer(csv) layer = None layerField = None csvField = None for param, widget in inputs.items(): if isinstance(widget, QgsMapLayerComboBox): layer = widget.currentLayer() elif isinstance(widget, QgsFieldComboBox): layerField = widget.currentField() csvField = csv.fields()[0].name() if layer is not None and layerField is not None and csv is not None and csvField is not None: parameters = { 'DISCARD_NONMATCHING': False, 'FIELD': layerField, 'FIELDS_TO_COPY': [], 'FIELD_2': csvField, 'INPUT': layer.source(), 'INPUT_2': csv.source(), 'METHOD': 1, 'OUTPUT': 'TEMPORARY_OUTPUT', 'PREFIX': '' } result = processing.runAndLoadResults( 'qgis:joinattributestable', parameters) return result else: return None except: return None
def overlay(self): measure = self.dlg.fcbMeasure.layer() area = self.dlg.fcbArea.layer() params = { 'INPUT': measure, 'OVERLAY': area, 'OUTPUT': "memory:land_water", 'INTERSECTION': "memory:land_water" } QgsApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.iface.messageBar().pushMessage("Atitude correction", "Running overlay", level=Qgis.Info, duration=3) output = processing.runAndLoadResults("qgis:intersection", params) QgsApplication.restoreOverrideCursor() self.iface.messageBar().pushMessage("Atitude correction", "Overlay finished", level=Qgis.Success, duration=3) self.overlaylayer = QgsProject.instance().mapLayer(output['OUTPUT']) self.dlg.lcbOverlay.setLayer(self.overlaylayer)
def processAlgorithm(self, parameters, context, feedback): """ the processing """ # Get Input footprint = self.parameterAsVectorLayer(parameters, self.INPUT, context) # Get Output output = self.parameterAsOutputLayer(parameters, self.OUTPUT, context) feedback.pushInfo('Join Attributes by Location Summary') result = processing.run("qgis:joinbylocationsummary", { 'INPUT': footprint, 'JOIN': footprint, 'PREDICATE': [2], 'JOIN_FIELDS': [], 'SUMMARIES': [0], 'DISCARD_NONMATCHING': False, 'PREFIX': '', 'OUTPUT': 'TEMPORARY_OUTPUT' }, context=context, feedback=feedback) feedback.pushInfo('Delete Duplicate Geometries') result = processing.runAndLoadResults("qgis:deleteduplicategeometries", { 'INPUT': result['OUTPUT'], 'OUTPUT': output }, context=context, feedback=feedback) return {self.OUTPUT: result['OUTPUT']}
layerPath = "C:\\myworld\\cgis\\adkforests\\cugir-10m-all-adk\\" counter = 1 for layerName in dems: #print(os.path.basename(path)) fullPath = layerPath + layerName rasterLyr = QgsRasterLayer(fullPath, layerName) layerIsValid = rasterLyr.isValid() if layerIsValid: print("Valid Raster") outputPath = layerPath + layerName + "_hillshade.tif" print(outputPath) parameters = {'INPUT': rasterLyr, 'BAND': 1, 'COMPUTE_EDGES': False, 'ZEVENBERGEN': False, 'Z_FACTOR': 1.0, 'SCALE': 1.0, 'AZIMUTH': 315, 'COMBINED': False, 'ALTITUDE': 45, 'MULTIDIRECTIONAL': False, 'OUTPUT': outputPath} processing.runAndLoadResults('gdal:hillshade',parameters) counter = counter + 1 else: print("Invalid Raster")