def setUpClass(cls): """Run before all tests""" QCoreApplication.setOrganizationName("QGIS_Test") QCoreApplication.setOrganizationDomain( "QGIS_TestPyQgsProcessingCheckValidity.com") QCoreApplication.setApplicationName( "QGIS_TestPyQgsProcessingCheckValidity") QgsSettings().clear() Processing.initialize() QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) cls.registry = QgsApplication.instance().processingRegistry()
def setUpClass(cls): start_app() from processing.core.Processing import Processing Processing.initialize() ProcessingConfig.setSettingValue( ModelerUtils.MODELS_FOLDER, os.path.join(os.path.dirname(__file__), 'models')) QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) cls.cleanup_paths = [] cls.in_place_layers = {} cls.vector_layer_params = {} cls._original_models_folder = ProcessingConfig.getSetting( ModelerUtils.MODELS_FOLDER)
def run_qgis_algorithm(algorithm_id, algorithm_parameters): import sys import qgis.utils from qgis.core import ( QgsApplication, QgsProcessingFeedback, QgsVectorLayer, QgsProcessingProvider, QgsProcessingRegistry, ) from qgis.analysis import QgsNativeAlgorithms # See https://gis.stackexchange.com/a/155852/4972 for details about the prefix QgsApplication.setPrefixPath('/usr', True) qgs = QgsApplication([], False) qgs.initQgis() # # Append the path where processing plugin can be found sys.path.append('/usr/share/qgis/python/plugins/') import processing from processing.core.Processing import Processing Processing.initialize() QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) print('You are using QGIS version: %s ', qgis.utils.Qgis.QGIS_VERSION) print('You are running: %s ', algorithm_id) provider = NDVIProvider() provider.loadAlgorithms() QgsApplication.processingRegistry().addProvider(provider) # Checking if the algorithm is added # last_alg = QgsApplication.processingRegistry().algorithms()[-1] # print(last_alg.name()) # print(last_alg.id()) # last_alg = QgsApplication.processingRegistry().algorithms()[-2] # print(last_alg.name()) # print(last_alg.id()) # Show help for the algorithm processing.algorithmHelp(algorithm_id) print('Running algorithm') result = processing.run(algorithm_id, algorithm_parameters) print('### Result:') print(result) qgs.exitQgis() return result
def convertRasterToPointVector(self, inp, outp, bandNumber): sys.path.append('/usr/share/qgis/python/plugins/') import processing from processing.core.Processing import Processing Processing.initialize() QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) processing.run( "native:pixelstopoints", { 'INPUT_RASTER': inp, 'RASTER_BAND': bandNumber, 'FIELD_NAME': 'VALUE', 'OUTPUT': outp }) print('contour')
def setUpClass(self): Processing.initialize() QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) print("\nINFO: Setting up copy CSV points to DB validation...") self.qgis_utils = QGISUtils() self.db_connection = get_dbconn('test_ladm_col') self.db_connection_3d = get_dbconn('test_ladm_col_3d') result = self.db_connection.test_connection() print('test_connection', result) if not result[1]: print('The test connection is not working') return restore_schema('test_ladm_col') restore_schema('test_ladm_col_3d')
def setUpClass(cls): """Run before all tests""" QCoreApplication.setOrganizationName("QGIS_Test") QCoreApplication.setOrganizationDomain( "QGIS_TestPyQgsProcessingInPlace.com") QCoreApplication.setApplicationName("QGIS_TestPyQgsProcessingInPlace") QgsSettings().clear() Processing.initialize() QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) cls.registry = QgsApplication.instance().processingRegistry() fields = QgsFields() fields.append(QgsField('int_f', QVariant.Int)) cls.vl = QgsMemoryProviderUtils.createMemoryLayer( 'mylayer', fields, QgsWkbTypes.Point, QgsCoordinateReferenceSystem(4326)) f1 = QgsFeature(cls.vl.fields()) f1['int_f'] = 1 f1.setGeometry(QgsGeometry.fromWkt('Point(9 45)')) f2 = QgsFeature(cls.vl.fields()) f2['int_f'] = 2 f2.setGeometry(QgsGeometry.fromWkt('Point(9.5 45.6)')) cls.vl.dataProvider().addFeatures([f1, f2]) assert cls.vl.isValid() assert cls.vl.featureCount() == 2 # Multipolygon layer cls.multipoly_vl = QgsMemoryProviderUtils.createMemoryLayer( 'mymultiplayer', fields, QgsWkbTypes.MultiPolygon, QgsCoordinateReferenceSystem(4326)) f3 = QgsFeature(cls.multipoly_vl.fields()) f3.setGeometry( QgsGeometry.fromWkt( 'MultiPolygon (((2.81856297539240419 41.98170998812887689, 2.81874467773035464 41.98167537995160359, 2.81879535908157752 41.98154066615795443, 2.81866433873670452 41.98144056064155905, 2.81848263699778379 41.98147516865246587, 2.81843195500470811 41.98160988234612034, 2.81856297539240419 41.98170998812887689)),((2.81898589063455907 41.9815711567298635, 2.81892080450418803 41.9816030048432367, 2.81884192631866437 41.98143737613141724, 2.8190679469505846 41.98142270931093378, 2.81898589063455907 41.9815711567298635)))' )) f4 = QgsFeature(cls.multipoly_vl.fields()) f4.setGeometry( QgsGeometry.fromWkt( 'MultiPolygon (((2.81823679385631332 41.98133290154246566, 2.81830770255185703 41.98123540208609228, 2.81825871989355159 41.98112524362621656, 2.81813882853970243 41.98111258462271422, 2.81806791984415872 41.98121008407908761, 2.81811690250246416 41.98132024253896333, 2.81823679385631332 41.98133290154246566)),((2.81835835162010895 41.98123286963267731, 2.8183127674586852 41.98108725356146209, 2.8184520523963692 41.98115436357689134, 2.81835835162010895 41.98123286963267731)))' )) cls.multipoly_vl.dataProvider().addFeatures([f3, f4]) assert cls.multipoly_vl.isValid() assert cls.multipoly_vl.featureCount() == 2 QgsProject.instance().addMapLayers([cls.vl, cls.multipoly_vl])
def setUpClass(cls): """Run before all tests""" QCoreApplication.setOrganizationName("QGIS_Test") QCoreApplication.setOrganizationDomain( "QGIS_TestPyQgsExportToPostgis.com") QCoreApplication.setApplicationName("QGIS_TestPyQgsExportToPostgis") QgsSettings().clear() Processing.initialize() QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) cls.registry = QgsApplication.instance().processingRegistry() # Create DB connection in the settings settings = QgsSettings() settings.beginGroup('/PostgreSQL/connections/qgis_test') settings.setValue('service', 'qgis_test') settings.setValue('database', 'qgis_test')
def wrapped_func(*args,**kwargs): fold = wr_parse_arguments() # Initiate QGIS in Python without an interface ## ESTABLISH QGIS paths based on operating system if (fold.OS[0] == 1): ## Windows QGIS_PREF_PATH = fold.QGISINST[0]+u'/apps/qgis' QGIS_PLUG_PATH = fold.QGISINST[0]+u'/apps/qgis/python/plugins' else if (fold.OS[1] == 2): QGIS_PREF_PATH = fold.QGISINST[0]+u'/MacOS' QGIS_PLUG_PATH = fold.QGISINST[0]+u'/Plugins' QgsApplication.setPrefixPath(QGIS_PREF_PATH,True) qgs = QgsApplication([],False) qgs.initQgis() print(">> QGIS initialized.") # Import `processing` modules sys.path.append(QGIS_PLUG_PATH) import processing from processing.core.Processing import Processing ## from processing.tools.general import runAndLoadresults Processing.initialize() print(">> Processing initialized.") # Add Native QGIS algorithms - Need to be after initializing Processing ## This loads: `qgis:interesection`, an algorithm needed later qgs.processingRegistry().addProvider(QgsNativeAlgorithms()) print(">> Native algorithms added.") # Start with a blank project project = QgsProject.instance() project.clear() # RUN THE MAIN FUNCTION! exitFlag = function(fold, qgs, project) print(">> Finished with main function.") # Close QGIS in Python qgs.exitQgis() print(">> Exited from QGIS.") # Wait before exiting print("5 seconds before closing this window.") time.sleep(5) return exitFlag
def initialize_qgis_processor(): """ Initialize the QGIS processor environment (to call and run QGIS algorithms). Returns: The initialized qgis processor object. """ pr = Processing.Processing() pr.initialize() # Allows the GeoProcessor to use the native algorithms # REF: https://gis.stackexchange.com/questions/279874/ # using-qgis3-processing-algorithms-from-standalone-pyqgis-scripts-outside-of-gui/279937 QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) return pr
def initialize(): if "model" in [ p.id() for p in QgsApplication.processingRegistry().providers() ]: return with QgsRuntimeProfiler.profile('Initialize'): # add native provider if not already added if "native" not in [ p.id() for p in QgsApplication.processingRegistry().providers() ]: QgsApplication.processingRegistry().addProvider( QgsNativeAlgorithms(QgsApplication.processingRegistry())) # add 3d provider if available and not already added if "3d" not in [ p.id() for p in QgsApplication.processingRegistry().providers() ]: try: from qgis._3d import Qgs3DAlgorithms QgsApplication.processingRegistry().addProvider( Qgs3DAlgorithms(QgsApplication.processingRegistry())) except ImportError: # no 3d library available pass # Add the basic providers for c in [ QgisAlgorithmProvider, Grass7AlgorithmProvider, GdalAlgorithmProvider, OtbAlgorithmProvider, SagaAlgorithmProvider, ScriptAlgorithmProvider, ModelerAlgorithmProvider, ProjectProvider ]: p = c() if QgsApplication.processingRegistry().addProvider(p): Processing.BASIC_PROVIDERS.append(p) # And initialize ProcessingConfig.initialize() ProcessingConfig.readSettings() RenderingStyles.loadStyles()
def __init__(self, network=None, constrains=None, res_folder=None, project=None, use='plugin'): """ Constrictor :param network to find intersections :param constrains the optional sight lines :param res_folder storing the results :param project loading the layers into :param use to identify who call that class - plugin or standalone """ # general attributes self.use = use # Initiate QgsApplication in case of standalone app if self.use == "standalone": self.app = QGuiApplication([]) QgsApplication.setPrefixPath( r'C:\Program Files\QGIS 3.0\apps\qgis', True) QgsApplication.processingRegistry().addProvider( QgsNativeAlgorithms()) QgsApplication.initQgis() # These attributes are input from the user self.network = self.upload_new_layer(network, "_network") self.constrain = self.upload_new_layer(constrains, "_constrain") self.feedback = QgsProcessingFeedback() self.res_folder = res_folder # These will be used latter self.res = [] # layers[0] = intersections # layers[1] = edges self.layers = [] # attributes to create QgsVectorLayer in memory self.vl = QgsVectorLayer() # QgsVectorDataProvider self.lines = None # QgsProject.instance() self.project = project
def generateContour(self, inp, outp, bandNumber, interval): sys.path.append('/usr/share/qgis/python/plugins/') import processing from processing.core.Processing import Processing Processing.initialize() QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) processing.run( "gdal:contour", { 'INPUT': inp, 'BAND': bandNumber, 'INTERVAL': interval, 'FIELD_NAME': 'ELEV', 'CREATE_3D': False, 'CREATE_3D': False, 'IGNORE_NODATA': False, 'NODATA': None, 'OFFSET': 0, 'OPTIONS': '', 'OUTPUT': outp })
def main(): QtCore.qInstallMessageHandler(handler) QgsApplication.setPrefixPath("C:\\OSGeo4W64\\apps\\qgis", True) app = QgsApplication([], False) app.initQgis() Processing.initialize() QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) firstWindow = Welcome() firstWindow.show() QtTest.QTest.qWait(5000) firstWindow.close() secondWindow = SWAMain() secondWindow.show() app.exec_() app.deleteLater() QgsApplication.exitQgis()
def generateHillShade(self, inp, outp): sys.path.append('/usr/share/qgis/python/plugins/') import processing from processing.core.Processing import Processing Processing.initialize() QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) processing.run( "gdal:hillshade", { 'INPUT': inp, 'BAND': 1, 'Z_FACTOR': 1.571e-05, 'SCALE': 1, 'AZIMUTH': 315, 'ALTITUDE': 40, 'COMPUTE_EDGES': False, 'ZEVENBERGEN': False, 'COMBINED': False, 'MULTIDIRECTIONAL': False, 'OPTIONS': '', 'OUTPUT': outp })
def distance_to_nearest_hub(): app = QGuiApplication([]) QgsApplication.setPrefixPath(r'C:\Program Files\QGIS 3.0\apps\qgis', True) QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) QgsApplication.initQgis() feedback = QgsProcessingFeedback() """Upload input data""" input_path = r'C:\Users\achituv\AppData\Roaming\QGIS\QGIS3\profiles\default\python\plugins\visibilitysyntax' \ r'\test\POI\results_file/cliped.shp' input = upload_new_layer(input_path, "test_input") hubs_path = r'C:\Users\achituv\AppData\Roaming\QGIS\QGIS3\profiles\default\python\plugins\visibilitysyntax' \ r'\test\POI\results_file/points_along.shp' hubs = upload_new_layer(hubs_path, "test_hubs_") output = r'C:\Users\achituv\AppData\Roaming\QGIS\QGIS3\profiles\default\python\plugins\visibilitysyntax' \ r'\test\POI\results_file/line_to_points.shp' alg = HubDistanceLines() alg.initAlgorithm() # Some preprocessing for context project = QgsProject.instance() target_crs = QgsCoordinateReferenceSystem() target_crs.createFromOgcWmsCrs(input.crs().authid()) project.setCrs(target_crs) context = QgsProcessingContext() context.setProject(project) params = { 'INPUT': input, 'HUBS': hubs, 'FIELD': 'vis_id', 'UNIT': 4, 'OUTPUT': output } alg.processAlgorithm(params, context, feedback=feedback) """For standalone application""" # Exit applications QgsApplication.exitQgis() app.exit()
def __init__(self, use, path_shp, name): # Initiate QgsApplication in case of standalone app if use == "standalone": self.app = QGuiApplication([]) QgsApplication.setPrefixPath( r'C:\Program Files\QGIS 3.0\apps\qgis', True) QgsApplication.processingRegistry().addProvider( QgsNativeAlgorithms()) QgsApplication.initQgis() self.feedback = QgsProcessingFeedback() self.shp = self.upload_new_layer(path_shp, name) # This variable is to run built tools self.shp_path = path_shp # Build Qtree object my_tree = QTree(10) my_tree = self.from_qgis_to_Qtree_list(my_tree) # Dimension for Qtree x0 = min(my_tree.points, key=lambda x: x.x).x y0 = min(my_tree.points, key=lambda x: x.y).y x1 = max(my_tree.points, key=lambda x: x.x).x y1 = max(my_tree.points, key=lambda x: x.y).y w = x1 - x0 h = y1 - y0 my_tree.add_root(x0, y0, w, h) # print(str(x0) + "," + str(y0) + "," + str(x1) + "," + str(y1)) # Build the graph my_tree.subdivide() # Add new field to the network based on which it would be dissolved self.add_new_field_and_papulate_it(my_tree.line, "group", QVariant.LongLong) # Dissolve the network self.dissolve( "group", os.path.dirname(__file__) + r'/processing/dissolve_0.shp')
def setUpClass(cls): start_app() from processing.core.Processing import Processing Processing.initialize() QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) cls.cleanup_paths = []
def calculate(self, process_path): qgs = QgsApplication([], False) qgs.initQgis() Processing.initialize() QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) gdal.AllRegister() #for alg in QgsApplication.processingRegistry().algorithms(): # print(alg.id(), "->", alg.displayName()) # read mdt data inputRaster = self.input_mdt process_path = process_path outPath2 = self.output_file gdalRaster = gdal.Open(str(inputRaster)) x = gdalRaster.RasterXSize y = gdalRaster.RasterYSize geo = gdalRaster.GetGeoTransform() minx = geo[0] maxy = geo[3] maxx = minx + geo[1]*x miny = maxy + geo[5]*y #extent_raster = str(minx) + "," + str(maxx) + "," + str(miny) + "," + str(maxy) #pixelSize = geo[1] band_mdt = gdalRaster.GetRasterBand(1) #data_mdt = band_mdt.ReadAsArray(0, 0, x, y) Processing.initialize() # mdt_interp = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/mdt_interp" # Processing.runAlgorithm("grass7:r.surf.idw", None, inputRaster, 12, False, extent_raster, pixelSize, mdt_interp) # mdt = mdt_interp + "." + "tif" # # gdalMDT = gdal.Open(str(mdt_interp) + "." + "tif") # x_mdt = gdalMDT.RasterXSize # y_mdt = gdalMDT.RasterYSize # geo_mdt = gdalMDT.GetGeoTransform() # band_mdt = gdalMDT.GetRasterBand(1) # data_mdt = band_mdt.ReadAsArray(0,0,x_mdt,y_mdt) # coeficients a and b of the regression lines, y = ax + b, used for mean monthly precipitation, y(mm), as a function of altitude, x(m) # a = 0.99 # b = 542.22 # precip_mul = numpy.multiply(data_mdt,a) # precipitat = precip_mul + b # precipitation = numpy.array(precipitat) # recharge = numpy.multiply(precipitation, 0.15) recharge_without_rec = process_path + "recharge_without_rec" #Processing.runAlgorithm("gdal:rastercalculator",{ # 'INPUT_A': inputRaster, # 'BAND_A': 1, # 'INPUT_B': None, # 'BAND_B': -1, # 'INPUT_C': None, # 'BAND_C': -1, # 'INPUT_D': None, # 'BAND_D': -1, # 'INPUT_E': None, # 'BAND_E': -1, # 'INPUT_F': None, # 'BAND_F': -1, # 'FORMULA': '(A*0.99+542.22)*0.15', # 'NO_DATA': None, # 'RTYPE': 6, # 'EXTRA': '', # 'OPTIONS': '', # 'OUTPUT':recharge_without_rec #}) Processing.runAlgorithm("grass7:r.mapcalc.simple", { 'a': str(inputRaster), 'b': None, 'c': None, 'd': None, 'e': None, 'f': None, 'expression': "((A*0.99)+542.22)*0.15", 'output': recharge_without_rec, 'GRASS_REGION_PARAMETER': None, 'GRASS_REGION_CELLSIZE_PARAMETER': 0, 'GRASS_RASTER_FORMAT_OPT': '', 'GRASS_RASTER_FORMAT_META': '' }) # Create an output imagedriver with the multiplication result # driver2 = gdal.GetDriverByName( "GTiff" ) # outData2 = driver2.Create(str(recharge_without_rec+'.'+'tif'), x,y,1, gdal.GDT_Float32) # outData2.GetRasterBand(1).WriteArray(recharge) # outData2.SetGeoTransform(geo) #outData2 = None recharge_without_rec_file = gdal.Open(recharge_without_rec) recharge_without_rec_rep = process_path + "recharge_without_rec_rep" gdal.Warp(recharge_without_rec_rep, recharge_without_rec_file, dstSRS="EPSG:3763") #Processing.runAlgorithm("gdal:assignprojection", # {'INPUT': recharge_without_rec, # 'CRS': QgsCoordinateReferenceSystem('EPSG:3763')}) # indexes for topography for the two methods #numberRows = int(self.tableWidget.rowCount()) #numberColumns = int(self.tableWidget.columnCount()) #classes = '' #lista = [] #for i in range(0,numberRows): # for j in range(0,numberColumns): # self.line = self.tableWidget.item(i,j) # lista = lista + [str(self.line.text())] # string = "," # intervalos = string.join(lista) #results = list(map(int, lista)) #QMessageBox.about(self, 'teste', str(results)) Processing.initialize() result = process_path + "/result.tif" Processing.runAlgorithm("native:reclassifybytable", { 'INPUT_RASTER': recharge_without_rec_rep, 'RASTER_BAND': 1, 'TABLE': self.rattings, 'NO_DATA': -9999, 'RANGE_BOUNDARIES': 0, 'NODATA_FOR_MISSING': False, 'DATA_TYPE': 5, 'OUTPUT': result}) # add result into canvas #file_info_norm = QFileInfo(str(outPath2)) # QMessageBox.about(self, "teste", str(file_info_norm)) #rlayer_new_norm = QgsRasterLayer(outPath2, file_info_norm.fileName(), 'gdal') # QMessageBox.about(self, "teste", str(rlayer_new_norm)) #QgsProject.instance().addMapLayer(rlayer_new_norm) #self.iface.canvas.setExtent(rlayer_new_norm.extent()) # set the map canvas layer set #self.iface.canvas.setLayers([rlayer_new_norm]) # add result into canvas # file_info_recharge = QFileInfo(outPath2) # if file_info_recharge.exists(): # layer_name_recharge = file_info_recharge.baseName() # else: # return False # rlayer_new_recharge = QgsRasterLayer(outPath2, layer_name_recharge) # if rlayer_new_recharge.isValid(): # QgsMapLayerRegistry.instance().addMapLayer(rlayer_new_recharge) # layer_prec_recharge = QgsMapCanvasLayer(rlayer_new_recharge) # layerList_recharge = [layer_prec_recharge] # extent_recharge = self.iface.canvas.setExtent(rlayer_new_recharge.extent()) # self.iface.canvas.setLayerSet(layerList_recharge) # self.iface.canvas.setVisible(True) # return True # else: # return False #QMessageBox.information(self, self.tr( "Finished" ), self.tr( "Net Recharge completed." ) ) out_raster = gdal.Open(result) gdal.Warp(outPath2, out_raster, dstSRS="EPSG:3857")
def calculate(self, process_path): qgs = QgsApplication([], False) qgs.initQgis() Processing.initialize() QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) gdal.AllRegister() #for alg in QgsApplication.processingRegistry().algorithms(): # print(alg.id(), "->", alg.displayName()) # read raster #inputRaster = input_mdt # read maximum depth #max_depth = max_depth # read distance #distance = distance # minimum size #size = min_size #outPath2 = output_path #process_path = "/home/rodrigo/data/d/process" layer_raster = QgsRasterLayer(self.input_mdt, os.path.basename(self.input_mdt), "gdal") data_mdt = layer_raster.dataProvider() extent_raster = data_mdt.extent() xmin_raster = extent_raster.xMinimum() xmax_raster = extent_raster.xMaximum() ymin_raster = extent_raster.yMinimum() ymax_raster = extent_raster.yMaximum() extent_raster_str = str(xmin_raster) + "," + str(xmax_raster) + "," + str(ymin_raster) + "," + str(ymax_raster) cellSize = layer_raster.rasterUnitsPerPixelX() #stream = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/stream.tif" stream = process_path + "/stream.tif" Processing.runAlgorithm("grass7:r.watershed",{ 'elevation': self.input_mdt, 'depression': None, 'flow': None, 'disturbed_land': None, 'blocking': None, 'threshold': self.size, 'max_slope_length': None, 'convergence': 5, 'memory': 300, '-s': False, '-m': False, '-4': False, '-a': False, '-b': False, 'accumulation': None, 'drainage': None, 'basin': None, 'stream': stream, 'half_basin': None, 'length_slope': None, 'slope_steepness': None, 'tci': None, 'spi': None, 'GRASS_REGION_PARAMETER': extent_raster_str + '[EPSG:3763]', 'GRASS_REGION_CELLSIZE_PARAMETER': cellSize, 'GRASS_RASTER_FORMAT_OPT': '', 'GRASS_RASTER_FORMAT_META': '' }) # condition stream > 1 to have the lines with value 1 #stream_ones = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/stream_ones.tif" stream_ones = process_path + "/stream_ones.tif" Processing.runAlgorithm("grass7:r.mapcalc.simple",{ 'a': str(stream), 'b': None, 'c': None, 'd': None, 'e': None, 'f': None, 'expression': 'A>1', 'output': stream_ones, 'GRASS_REGION_PARAMETER': None, 'GRASS_REGION_CELLSIZE_PARAMETER': 0, 'GRASS_RASTER_FORMAT_OPT': '', 'GRASS_RASTER_FORMAT_META': '' }) # raster distance #raster_distance = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/raster_distance.tif" raster_distance = process_path + "/raster_distance.tif" #Processing.runAlgorithm("saga:proximitygrid", None, str(stream_ones_str), 3, str(raster_distance), None, None) #Processing.runAlgorithm("saga:proximityraster", { # 'FEATURES': str(stream_ones), # 'DISTANCE': str(raster_distance), 'DIRECTION': 'TEMPORARY_OUTPUT', 'ALLOCATION': 'TEMPORARY_OUTPUT'}) Processing.runAlgorithm("grass7:r.grow.distance", { 'input': str(stream_ones), 'metric': 0, '-m': False, '-': False, 'distance': str(raster_distance), 'value': 'TEMPORARY_OUTPUT', 'GRASS_REGION_PARAMETER': None, 'GRASS_REGION_CELLSIZE_PARAMETER': 0, 'GRASS_RASTER_FORMAT_OPT': '', 'GRASS_RASTER_FORMAT_META': '' }) # condition distance >= 200, always maximum depth meters #dist_major_200 = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/dist_major_200.tif" dist_major_200 = process_path + "/dist_major_200.tif" Processing.runAlgorithm("grass7:r.mapcalc.simple", { 'a': str(raster_distance), 'b': None, 'c': None, 'd': None, 'e': None, 'f': None, 'expression': "A>="+str(self.distance), 'output': dist_major_200, 'GRASS_REGION_PARAMETER': None, 'GRASS_REGION_CELLSIZE_PARAMETER': 0, 'GRASS_RASTER_FORMAT_OPT': '', 'GRASS_RASTER_FORMAT_META': '' }) #dist_multiplication = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/dist_multiplication.tif" dist_multiplication = process_path + "/dist_multiplication.tif" Processing.runAlgorithm("grass7:r.mapcalc.simple", { 'a': str(dist_major_200), 'b': None, 'c': None, 'd': None, 'e': None, 'f': None, 'expression': "A*"+str(self.max_depth), 'output': dist_multiplication, 'GRASS_REGION_PARAMETER': None, 'GRASS_REGION_CELLSIZE_PARAMETER': 0, 'GRASS_RASTER_FORMAT_OPT': '', 'GRASS_RASTER_FORMAT_META': '' }) # condition distance < 200, inteprolation between 0 and maximum depth #dist_minor_200 = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/dist_minor_200.tif" dist_minor_200 = process_path + "/dist_minor_200.tif" Processing.runAlgorithm("grass7:r.mapcalc.simple", { 'a': str(raster_distance), 'b': None, 'c': None, 'd': None, 'e': None, 'f': None, 'expression': "A<"+str(self.distance), 'output': dist_minor_200, 'GRASS_REGION_PARAMETER': None, 'GRASS_REGION_CELLSIZE_PARAMETER': 0, 'GRASS_RASTER_FORMAT_OPT': '', 'GRASS_RASTER_FORMAT_META': '' }) # multiplication by the raster distance #dist_multiplication_dist = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/dist_multiplication_dist.tif" dist_multiplication_dist = process_path + "/dist_multiplication_dist.tif" #Processing.runAlgorithm("grass7:r.mapcalc.simple", # {'a': str(dist_minor_200), # 'b': str(dist_major_200), # 'c': None, 'd': None, 'e': None, 'f': None, # 'expression': 'A*B', # 'output': dist_multiplication_dist, 'GRASS_REGION_PARAMETER': None, # 'GRASS_REGION_CELLSIZE_PARAMETER': 0, 'GRASS_RASTER_FORMAT_OPT': '', # 'GRASS_RASTER_FORMAT_META': ''}) Processing.runAlgorithm("grass7:r.mapcalc.simple", { 'a': str(dist_minor_200), 'b': str(raster_distance), 'c': None, 'd': None, 'e': None, 'f': None, 'expression': 'A*B', 'output': dist_multiplication_dist, 'GRASS_REGION_PARAMETER': None, 'GRASS_REGION_CELLSIZE_PARAMETER': 0, 'GRASS_RASTER_FORMAT_OPT': '', 'GRASS_RASTER_FORMAT_META': '' }) # interpolation between 0 and distance #interpolation_dist = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/interpolation_dist.tif" interpolation_dist = process_path + "/interpolation_dist.tif" Processing.runAlgorithm("grass7:r.mapcalc.simple", { 'a': str(dist_multiplication_dist), 'b': None, 'c': None, 'd': None, 'e': None, 'f': None, 'expression': "A*"+str(self.max_depth)+"/"+str(self.distance), 'output': interpolation_dist, 'GRASS_REGION_PARAMETER': None, 'GRASS_REGION_CELLSIZE_PARAMETER': 0, 'GRASS_RASTER_FORMAT_OPT': '', 'GRASS_RASTER_FORMAT_META': '' }) # depth surface = sum of two conditions #depth_surface = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/depth_surface.tif" depth_surface = process_path + "/depth_surface.tif" Processing.runAlgorithm("grass7:r.mapcalc.simple", { 'a': str(dist_multiplication), 'b': str(dist_multiplication_dist), 'c': None, 'd': None, 'e': None, 'f': None, 'expression': 'A+B', 'output': depth_surface, 'GRASS_REGION_PARAMETER': None, 'GRASS_REGION_CELLSIZE_PARAMETER': 0, 'GRASS_RASTER_FORMAT_OPT': '', 'GRASS_RASTER_FORMAT_META': '' }) # indexes for topography """rattings_lista = [] for linha in ratings: for coluna in linha: rattings_lista = rattings_lista + [str(coluna)] string = "," intervalos = string.join(rattings_lista) results = list(map(float, rattings_lista)) print(results)""" #Processing.runAlgorithm("saga:reclassifyvalues",{'INPUT': depth_surface, 'METHOD':2, 'OLD':0, 'NEW':1, 'SOPERATOR':0, 'MIN':0, 'MAX':1, # 'RNEW':2, 'ROPERATOR':0, 'RETAB':results, 'TOPERATOR':0, 'NODATAOPT':True, 'NODATA':0, # 'OTHEROPT':True, 'OTHERS':0, 'RESULT':outPath2}) result = process_path + "/result.tif" Processing.runAlgorithm("native:reclassifybytable", { 'INPUT_RASTER': str(depth_surface), 'RASTER_BAND': 1, 'TABLE': self.rattings, 'NO_DATA': -9999, 'RANGE_BOUNDARIES': 0, 'NODATA_FOR_MISSING': False, 'DATA_TYPE': 5, 'OUTPUT': result }) out_raster = gdal.Open(result) gdal.Warp(self.output_file, out_raster, dstSRS="EPSG:3857")
# Bootstrap code os.environ['QGIS_PREFIX_PATH'] = '/usr' # QgsApplication.setPrefixPath('/usr') # QgsApplication.setPluginPath('/usr/lib/qgis/plugins') # QgsApplication.setPkgDataPath('/usr/share/qgis') # QgsApplication.addLibraryPath('/usr/lib/qgis/plugins') # QgsApplication.addLibraryPath('/usr/bin') # QgsApplication.addLibraryPath('/usr/lib/x86_64-linux-gnu/qt5/plugins') QgsApplication.setApplicationName('QGIS3') QgsApplication.setOrganizationName('QGIS') QgsApplication.setOrganizationDomain('qgis.org') app = start_app(False, True) registry = app.processingRegistry() Processing.initialize() providers = [c() for c in PROVIDERS] providers.append(QgsNativeAlgorithms()) for provider in providers: registry.addProvider(provider) print(app.showSettings()) # pr = QgsProviderRegistry.instance() # for provider in pr.providerList(): # print(provider) # Load models from repository ...
def calculate(self, process_path): qgs = QgsApplication([], False) qgs.initQgis() Processing.initialize() QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) gdal.AllRegister() inputLayer = self.input_file process_path = process_path outPath = self.output_file cellSize = self.cellSize Elevation = self.elevation results = self.rattings layer = QgsVectorLayer(inputLayer, inputLayer, "ogr") vectorlayer_vector = layer.dataProvider() # extent extent_rect = vectorlayer_vector.extent() xmin = extent_rect.xMinimum() xmax = extent_rect.xMaximum() ymin = extent_rect.yMinimum() ymax = extent_rect.yMaximum() extent = str(xmin) + "," + str(xmax) + "," + str(ymin) + "," + str( ymax) Processing.initialize() #conductivity = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/conductivity" conductivity = process_path + "/conductivity" Processing.runAlgorithm( "grass7:v.to.rast", { 'input': inputLayer, 'type': [0, 1, 3], 'where': '', 'use': 0, 'attribute_column': Elevation, 'rgb_column': None, 'label_column': None, 'value': None, 'memory': 300, 'output': conductivity, 'GRASS_REGION_PARAMETER': extent, 'GRASS_REGION_CELLSIZE_PARAMETER': cellSize, 'GRASS_RASTER_FORMAT_OPT': '', 'GRASS_RASTER_FORMAT_META': '', 'GRASS_SNAP_TOLERANCE_PARAMETER': -1, 'GRASS_MIN_AREA_PARAMETER': 0.0001 }) #cond_reclassify = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/cond_reclassify.sdat" #Processing.runAlgorithm("saga:reclassifyvalues", # {'INPUT': conductivity, 'METHOD': 2, 'OLD': 0, 'NEW': 1, 'SOPERATOR': 0, 'MIN': 0, # 'MAX': 1, # 'RNEW': 2, 'ROPERATOR': 0, 'RETAB': results, 'TOPERATOR': 0, 'NODATAOPT': True, # 'NODATA': 0, # 'OTHEROPT': True, 'OTHERS': 0, 'RESULT': outPath}) calculate = process_path + "/result.tif" Processing.runAlgorithm( "native:reclassifybytable", { 'INPUT_RASTER': conductivity, 'RASTER_BAND': 1, 'TABLE': results, 'NO_DATA': -9999, 'RANGE_BOUNDARIES': 0, 'NODATA_FOR_MISSING': False, 'DATA_TYPE': 5, 'OUTPUT': calculate }) out_raster = gdal.Open(calculate) gdal.Warp(outPath, out_raster, dstSRS="EPSG:3857")
sys.path.append('/usr/share/qgis/python/plugins') # import qgis core libraries from qgis.core import ( QgsApplication, # QgsProcessingFeedback ) # init qgis application QgsApplication.setPrefixPath('/usr', True) app = QgsApplication([], False) app.initQgis() # import qgis native algorithm libraries from qgis.analysis import QgsNativeAlgorithms # add native algorithms to application app.processingRegistry().addProvider(QgsNativeAlgorithms()) # import processing (needed to run algorithms) import processing from processing.core.Processing import Processing # init processing Processing.initialize() def app_clean_exit(): """Clean exit of the QGIS application by freeing resources...""" app.exitQgis()
def main_function(tif_file_name, output_file_name, input_directory=INPUT_DIRECTORY, output_directory=OUTPUT_DIRECTORY): """The main function to calculate NDVI from tif file in `tif_path` to `output_path` """ full_tif_path = os.path.join(input_directory, tif_file_name) full_output_path = os.path.join(output_directory, output_file_name) if not os.path.exists(full_tif_path): print('TIF file %s is not exist' % full_tif_path) else: print('TIF file %s is exist' % full_tif_path) #### Prepare QGIS #### import sys import qgis.utils from qgis.core import (QgsApplication, QgsProcessingFeedback, QgsVectorLayer, QgsProcessingProvider, QgsProcessingRegistry, QgsRasterLayer, QgsProject) from qgis.analysis import QgsNativeAlgorithms # See https://gis.stackexchange.com/a/155852/4972 for details about the prefix QgsApplication.setPrefixPath('/usr', True) qgs = QgsApplication([], False) qgs.initQgis() # # Append the path where processing plugin can be found sys.path.append('/usr/share/qgis/python/plugins/') import processing from processing.core.Processing import Processing Processing.initialize() QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) #### Add NDVI Provider #### provider = NDVIProvider() provider.loadAlgorithms() QgsApplication.processingRegistry().addProvider(provider) #### Run split bands algorithm #### # algorithm id: split_band_algorithm_id = 'uas:Split_bands' # parameters split_band_algorithm_parameters = { 'inputimage': full_tif_path, 'Red': os.path.join(TEMP_DIRECTORY, 'red.sdat'), 'Green': os.path.join(TEMP_DIRECTORY, 'green.sdat'), 'Blue': os.path.join(TEMP_DIRECTORY, 'nir.sdat'), 'R_conv': os.path.join(OUTPUT_DIRECTORY, 'red_conv.tif'), 'G_conv': os.path.join(OUTPUT_DIRECTORY, 'green_conv.tif'), 'B_conv': os.path.join(OUTPUT_DIRECTORY, 'nir_conv.tif'), } # Run algorithm split_band_result = processing.run(split_band_algorithm_id, split_band_algorithm_parameters) # Check result print('Path of G_conv: %s is exist = %s' % (split_band_result.get('G_conv'), os.path.exists(split_band_result.get('G_conv')))) print('Path of R_conv: %s is exist = %s' % (split_band_result.get('R_conv'), os.path.exists(split_band_result.get('R_conv')))) #### Run NDVI raster calculation algorithm #### # algorithm id: ndvi_algorithm_id = 'uas:Calculate_NDVI' # parameters ndvi_algorithm_parameters = { 'inputnirband': split_band_result['B_conv'], 'inputredband': split_band_result['R_conv'], 'Output': full_output_path } if False: # Run algorithm ndvi_result = processing.run(ndvi_algorithm_id, ndvi_algorithm_parameters) # Check result print('Path of NDVI: %s is exist = %s' % (ndvi_result.get('Output'), os.path.exists(ndvi_result.get('Output')))) else: from qgis.analysis import QgsRasterCalculator, QgsRasterCalculatorEntry entries = [] nir_layer = QgsRasterLayer(ndvi_algorithm_parameters['inputnirband'], "nir") QgsProject.instance().addMapLayer(nir_layer) nir = QgsRasterCalculatorEntry() nir.ref = 'nir@1' nir.raster = nir_layer nir.bandNumber = 1 entries.append(nir) red_layer = QgsRasterLayer(ndvi_algorithm_parameters['inputredband'], "red") QgsProject.instance().addMapLayer(red_layer) red = QgsRasterCalculatorEntry() red.ref = 'red@1' red.raster = red_layer red.bandNumber = 1 entries.append(red) ndvi_expression = 'Float( nir@1 - red@1 ) / Float( nir@1 + red@1 )' calc = QgsRasterCalculator(ndvi_expression, ndvi_algorithm_parameters['Output'], 'GTiff', nir_layer.extent(), nir_layer.width(), nir_layer.height(), entries) a = calc.processCalculation() print('Result: ', a) # Exit QGIS qgs.exitQgis()
######################################################################################################################## # INITIALIZE QGIS ######################################################################################################################## # Import main modules import os from qgis.core import * from qgis.PyQt.QtCore import QVariant QgsApplication.setPrefixPath(os.environ['QGIS_PREFIX_PATH'], True) # Supply path to qgis install location qgs = QgsApplication( [], False ) # Create a reference to the QgsApplication, setting the second argument to False disables the GUI qgs.initQgis() # Load providers # Import processing modules from processing.core.Processing import Processing from qgis.analysis import QgsNativeAlgorithms Processing.initialize() # Initialize processing algorithms QgsApplication.processingRegistry().addProvider( QgsNativeAlgorithms()) # Register native algorithms import processing from processing.tools import dataobjects context = dataobjects.createContext() context.setInvalidGeometryCheck(QgsFeatureRequest.GeometryNoCheck)
# This will get replaced with a git SHA1 when you do a git archive __revision__ = 'fb5caa7a0f944788119b3429efb8f017964c5443' from qgis.testing import start_app, unittest from qgis.core import QgsApplication from qgis.analysis import QgsNativeAlgorithms from processing.gui.AlgorithmDialog import AlgorithmDialog from processing.gui.BatchAlgorithmDialog import BatchAlgorithmDialog from processing.modeler.ModelerParametersDialog import ModelerParametersDialog from processing.gui.wrappers import * start_app() QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) class AlgorithmDialogTest(unittest.TestCase): def testCreation(self): alg = QgsApplication.processingRegistry().algorithmById('native:centroids') a = AlgorithmDialog(alg) self.assertEqual(a.mainWidget().alg, alg) class WrappersTest(unittest.TestCase): def checkConstructWrapper(self, param, expected_wrapper_class): alg = QgsApplication.processingRegistry().algorithmById('native:centroids')
def calculate(self, process_path): qgs = QgsApplication([], False) qgs.initQgis() Processing.initialize() QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) gdal.AllRegister() process_path = process_path outPath = self.output_file cellSize = self.cellSize # read D raster inputLayer = self.input_file_d #bn_inputLayer = str(os.path.splitext(os.path.basename(inputLayer))[0]) #teste = str(bn_inputLayer) + '@1\'' #QMessageBox.about(self, "drastic", str(teste)) # read R raster inputLayer2 = self.input_file_r #bn_inputLayer2 = str(os.path.splitext(os.path.basename(inputLayer2))[0]) # read A raster inputLayer3 = self.input_file_a #bn_inputLayer3 = str(os.path.splitext(os.path.basename(inputLayer3))[0]) # read S raster inputLayer4 = self.input_file_s #bn_inputLayer4 = str(os.path.splitext(os.path.basename(inputLayer4))[0]) # read T raster inputLayer5 = self.input_file_t #bn_inputLayer5 = str(os.path.splitext(os.path.basename(inputLayer5))[0]) # read I raster inputLayer6 = self.input_file_i #bn_inputLayer6 = str(os.path.splitext(os.path.basename(inputLayer6))[0]) # read C raster inputLayer7 = self.input_file_c #bn_inputLayer7 = str(os.path.splitext(os.path.basename(inputLayer7))[0]) # outpath #outPath = self.outputLayerCombo.text() #gdal.AllRegister() # sum of the raster = DRASTIC # D gdalRaster = gdal.Open(str(inputLayer)) # # multiply by weight # depth_weight = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/depth_weight" x = gdalRaster.RasterXSize y = gdalRaster.RasterYSize geo = gdalRaster.GetGeoTransform() # band = gdalRaster.GetRasterBand(1) # data = band.ReadAsArray(0,0,x,y) # mul = numpy.multiply(data, int(self.lineWeightD.value())) # # Create an output imagedriver with the reclassified values multiplied by the weight # driver = gdal.GetDriverByName( "GTiff" ) # outData = driver.Create(str(depth_weight), x,y,1, gdal.GDT_Float32) # outData.GetRasterBand(1).WriteArray(mul) # outData.SetGeoTransform(geo) # outData = None # # geo = gdalRaster.GetGeoTransform() # # pixel size pixelSize = geo[1] #pixelSize = 30 # extent minx = geo[0] maxy = geo[3] maxx = minx + geo[1] * x miny = maxy + geo[5] * y extent = str(minx) + "," + str(maxx) + "," + str(miny) + "," + str( maxy) band = gdalRaster.GetRasterBand(1) #data_d = band.ReadAsArray(0,0,x,y) Processing.initialize() #resamp_d = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/resamp_d_drastic.sdat" resamp_d = process_path + "resamp_d_drastic.sdat" params = { 'input': inputLayer, 'output': resamp_d, 'GRASS_REGION_PARAMETER': extent, 'GRASS_REGION_CELLSIZE_PARAMETER': 0, 'GRASS_RASTER_FORMAT_OPT': '', 'GRASS_RASTER_FORMAT_META': '' } Processing.runAlgorithm("grass7:r.resample", params) # Processing.runAlgorithm("saga:resampling", None, recharge_weight, True, 0, 0, extent, pixelSize, resamp_r) #try: # Processing.runAlgorithm("saga:resampling", # {'INPUT': inputLayer, 'KEEP_TYPE': True, 'SCALE_UP': 0, # 'SCALE_DOWN': 0, # 'TARGET_USER_XMIN TARGET_USER_XMAX TARGET_USER_YMIN TARGET_USER_YMAX': extent + '[EPSG:3763]', # 'TARGET_USER_SIZE': pixelSize, 'TARGET_USER_FITS': 0, 'TARGET_TEMPLATE': None, # 'OUTPUT': resamp_d}) #except: # Processing.runAlgorithm("saga:resampling", # {'INPUT': inputLayer, 'KEEP_TYPE': True, 'SCALE_UP': 0, # 'SCALE_DOWN': 0, # 'TARGET_USER_XMIN TARGET_USER_XMAX TARGET_USER_YMIN TARGET_USER_YMAX': extent + '[EPSG:3763]', # 'TARGET_USER_SIZE': pixelSize, 'TARGET_USER_FITS': 0, 'TARGET_TEMPLATE': None, # 'OUTPUT': resamp_d}) #resamp_r = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/resamp_r_drastic.sdat" resamp_r = process_path + "resamp_r_drastic.sdat" params = { 'input': inputLayer2, 'output': resamp_r, 'GRASS_REGION_PARAMETER': extent, 'GRASS_REGION_CELLSIZE_PARAMETER': 0, 'GRASS_RASTER_FORMAT_OPT': '', 'GRASS_RASTER_FORMAT_META': '' } Processing.runAlgorithm("grass7:r.resample", params) #try: # Processing.runAlgorithm("saga:resampling", # {'INPUT': inputLayer2, 'KEEP_TYPE': True, 'SCALE_UP': 0, # 'SCALE_DOWN': 0, # 'TARGET_USER_XMIN TARGET_USER_XMAX TARGET_USER_YMIN TARGET_USER_YMAX': extent + '[EPSG:3763]', # 'TARGET_USER_SIZE': pixelSize, 'TARGET_USER_FITS': 0, 'TARGET_TEMPLATE': None, # 'OUTPUT': resamp_r}) #except: # Processing.runAlgorithm("saga:resampling", # {'INPUT': inputLayer2, 'KEEP_TYPE': True, 'SCALE_UP': 0, # 'SCALE_DOWN': 0, # 'TARGET_USER_XMIN TARGET_USER_XMAX TARGET_USER_YMIN TARGET_USER_YMAX': extent + '[EPSG:3763]', # 'TARGET_USER_SIZE': pixelSize, 'TARGET_USER_FITS': 0, 'TARGET_TEMPLATE': None, # 'OUTPUT': resamp_r}) #resamp_a = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/resamp_a_drastic.sdat" resamp_a = process_path + "resamp_a_drastic.sdat" params = { 'input': inputLayer3, 'output': resamp_a, 'GRASS_REGION_PARAMETER': extent, 'GRASS_REGION_CELLSIZE_PARAMETER': 0, 'GRASS_RASTER_FORMAT_OPT': '', 'GRASS_RASTER_FORMAT_META': '' } Processing.runAlgorithm("grass7:r.resample", params) #try: # Processing.runAlgorithm("saga:resampling", None, recharge_weight, True, 0, 0, extent, pixelSize, resamp_r) # Processing.runAlgorithm("saga:resampling", # {'INPUT': inputLayer3, 'KEEP_TYPE': True, 'SCALE_UP': 0, # 'SCALE_DOWN': 0, # 'TARGET_USER_XMIN TARGET_USER_XMAX TARGET_USER_YMIN TARGET_USER_YMAX': extent + '[EPSG:3763]', # 'TARGET_USER_SIZE': pixelSize, 'TARGET_USER_FITS': 0, 'TARGET_TEMPLATE': None, # 'OUTPUT': resamp_a}) #except: # Processing.runAlgorithm("saga:resampling", # {'INPUT': inputLayer3, 'KEEP_TYPE': True, 'SCALE_UP': 0, # 'SCALE_DOWN': 0, # 'TARGET_USER_XMIN TARGET_USER_XMAX TARGET_USER_YMIN TARGET_USER_YMAX': extent + '[EPSG:3763]', # 'TARGET_USER_SIZE': pixelSize, 'TARGET_USER_FITS': 0, 'TARGET_TEMPLATE': None, # 'OUTPUT': resamp_a}) #resamp_s = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/resamp_s_drastic.sdat" resamp_s = process_path + "resamp_s_drastic.sdat" params = { 'input': inputLayer4, 'output': resamp_s, 'GRASS_REGION_PARAMETER': extent, 'GRASS_REGION_CELLSIZE_PARAMETER': 0, 'GRASS_RASTER_FORMAT_OPT': '', 'GRASS_RASTER_FORMAT_META': '' } Processing.runAlgorithm("grass7:r.resample", params) #try: # Processing.runAlgorithm("saga:resampling", None, recharge_weight, True, 0, 0, extent, pixelSize, resamp_r) # Processing.runAlgorithm("saga:resampling", # {'INPUT': inputLayer4, 'KEEP_TYPE': True, 'SCALE_UP': 0, # 'SCALE_DOWN': 0, # 'TARGET_USER_XMIN TARGET_USER_XMAX TARGET_USER_YMIN TARGET_USER_YMAX': extent + '[EPSG:3763]', # 'TARGET_USER_SIZE': pixelSize, 'TARGET_USER_FITS': 0, 'TARGET_TEMPLATE': None, # 'OUTPUT': resamp_s}) #except: # Processing.runAlgorithm("saga:resampling", # {'INPUT': inputLayer4, 'KEEP_TYPE': True, 'SCALE_UP': 0, # 'SCALE_DOWN': 0, # 'TARGET_USER_XMIN TARGET_USER_XMAX TARGET_USER_YMIN TARGET_USER_YMAX': extent + '[EPSG:3763]', # 'TARGET_USER_SIZE': pixelSize, 'TARGET_USER_FITS': 0, 'TARGET_TEMPLATE': None, # 'OUTPUT': resamp_s}) #resamp_t = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/resamp_t_drastic.sdat" resamp_t = process_path + "resamp_t_drastic.sdat" params = { 'input': inputLayer5, 'output': resamp_t, 'GRASS_REGION_PARAMETER': extent, 'GRASS_REGION_CELLSIZE_PARAMETER': 0, 'GRASS_RASTER_FORMAT_OPT': '', 'GRASS_RASTER_FORMAT_META': '' } Processing.runAlgorithm("grass7:r.resample", params) #try: # Processing.runAlgorithm("saga:resampling", None, recharge_weight, True, 0, 0, extent, pixelSize, resamp_r) # Processing.runAlgorithm("saga:resampling", # {'INPUT': inputLayer5, 'KEEP_TYPE': True, 'SCALE_UP': 0, # 'SCALE_DOWN': 0, # 'TARGET_USER_XMIN TARGET_USER_XMAX TARGET_USER_YMIN TARGET_USER_YMAX': extent + '[EPSG:3763]', # 'TARGET_USER_SIZE': pixelSize, 'TARGET_USER_FITS': 0, 'TARGET_TEMPLATE': None, # 'OUTPUT': resamp_t}) #except: # Processing.runAlgorithm("saga:resampling", # {'INPUT': inputLayer5, 'KEEP_TYPE': True, 'SCALE_UP': 0, # 'SCALE_DOWN': 0, # 'TARGET_USER_XMIN TARGET_USER_XMAX TARGET_USER_YMIN TARGET_USER_YMAX': extent + '[EPSG:3763]', # 'TARGET_USER_SIZE': pixelSize, 'TARGET_USER_FITS': 0, 'TARGET_TEMPLATE': None, # 'OUTPUT': resamp_t}) #resamp_i = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/resamp_i_drastic.sdat" resamp_i = process_path + "resamp_i_drastic.sdat" params = { 'input': inputLayer6, 'output': resamp_i, 'GRASS_REGION_PARAMETER': extent, 'GRASS_REGION_CELLSIZE_PARAMETER': 0, 'GRASS_RASTER_FORMAT_OPT': '', 'GRASS_RASTER_FORMAT_META': '' } Processing.runAlgorithm("grass7:r.resample", params) #try: # Processing.runAlgorithm("saga:resampling", None, recharge_weight, True, 0, 0, extent, pixelSize, resamp_r) # Processing.runAlgorithm("saga:resampling", # {'INPUT': inputLayer6, 'KEEP_TYPE': True, 'SCALE_UP': 0, # 'SCALE_DOWN': 0, # 'TARGET_USER_XMIN TARGET_USER_XMAX TARGET_USER_YMIN TARGET_USER_YMAX': extent + '[EPSG:3763]', # 'TARGET_USER_SIZE': pixelSize, 'TARGET_USER_FITS': 0, 'TARGET_TEMPLATE': None, # 'OUTPUT': resamp_i}) #except: # Processing.runAlgorithm("saga:resampling", # {'INPUT': inputLayer6, 'KEEP_TYPE': True, 'SCALE_UP': 0, # 'SCALE_DOWN': 0, # 'TARGET_USER_XMIN TARGET_USER_XMAX TARGET_USER_YMIN TARGET_USER_YMAX': extent + '[EPSG:3763]', # 'TARGET_USER_SIZE': pixelSize, 'TARGET_USER_FITS': 0, 'TARGET_TEMPLATE': None, # 'OUTPUT': resamp_i}) #resamp_c = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/resamp_c_drastic.sdat" resamp_c = process_path + "resamp_c_drastic.sdat" params = { 'input': inputLayer7, 'output': resamp_c, 'GRASS_REGION_PARAMETER': extent, 'GRASS_REGION_CELLSIZE_PARAMETER': 0, 'GRASS_RASTER_FORMAT_OPT': '', 'GRASS_RASTER_FORMAT_META': '' } Processing.runAlgorithm("grass7:r.resample", params) #try: # Processing.runAlgorithm("saga:resampling", None, recharge_weight, True, 0, 0, extent, pixelSize, resamp_r) # Processing.runAlgorithm("saga:resampling", # {'INPUT': inputLayer7, 'KEEP_TYPE': True, 'SCALE_UP': 0, # 'SCALE_DOWN': 0, # 'TARGET_USER_XMIN TARGET_USER_XMAX TARGET_USER_YMIN TARGET_USER_YMAX': extent + '[EPSG:3763]', # 'TARGET_USER_SIZE': pixelSize, 'TARGET_USER_FITS': 0, 'TARGET_TEMPLATE': None, # 'OUTPUT': resamp_c}) #except: # Processing.runAlgorithm("saga:resampling", # {'INPUT': inputLayer7, 'KEEP_TYPE': True, 'SCALE_UP': 0, # 'SCALE_DOWN': 0, # 'TARGET_USER_XMIN TARGET_USER_XMAX TARGET_USER_YMIN TARGET_USER_YMAX': extent + '[EPSG:3763]', # 'TARGET_USER_SIZE': pixelSize, 'TARGET_USER_FITS': 0, 'TARGET_TEMPLATE': None, # 'OUTPUT': resamp_c}) # resamp_r = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/resamp_r_drastic.sdat" # Processing.runAlgorithm("saga:resampling", None, recharge_weight, True, 0, 0, extent, pixelSize, resamp_r) # # gdalRaster_d = gdal.Open(str(depth_weight)) # x_d = gdalRaster_d.RasterXSize # y_d = gdalRaster_d.RasterYSize # geo_d = gdalRaster_d.GetGeoTransform() # band_d = gdalRaster_d.GetRasterBand(1) # data_d = band_d.ReadAsArray(0,0,x_d,y_d) # # # # R # # resampling R raster # gdalRaster2 = gdal.Open(str(inputLayer2)) # # multiply by weight # recharge_weight = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/recharge_weight" # x2 = gdalRaster2.RasterXSize # y2 = gdalRaster2.RasterYSize # geo2 = gdalRaster2.GetGeoTransform() # band2 = gdalRaster2.GetRasterBand(1) # data2 = band2.ReadAsArray(0,0,x2,y2) # mul2 = numpy.multiply(data2, int(self.lineWeightR.value())) # # Create an output imagedriver with the reclassified values multiplied by the weight # driver2 = gdal.GetDriverByName( "GTiff" ) # outData2 = driver2.Create(str(recharge_weight), x2,y2,1, gdal.GDT_Float32) # outData2.GetRasterBand(1).WriteArray(mul2) # outData2.SetGeoTransform(geo2) # outData2 = None # # Processing.initialize() # resamp_r = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/resamp_r.sdat" # Processing.runAlgorithm("saga:resampling", None, recharge_weight, True, 0, 0, extent, pixelSize,0, None,3, resamp_r) # #resamp_r_dir = resamp_r + "." + "tif" # # R # gdalRaster_r = gdal.Open(str(resamp_r)) # x_r = gdalRaster_r.RasterXSize # y_r = gdalRaster_r.RasterYSize # geo_r = gdalRaster_r.GetGeoTransform() # band_r = gdalRaster_r.GetRasterBand(1) # data_r = band_r.ReadAsArray(0,0,x_r,y_r) # # # A # # resampling A raster # gdalRaster3 = gdal.Open(str(inputLayer3)) # # multiply by weight # aquifer_weight = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/aquifer_weight" # x3 = gdalRaster3.RasterXSize # y3 = gdalRaster3.RasterYSize # geo3 = gdalRaster3.GetGeoTransform() # band3 = gdalRaster3.GetRasterBand(1) # data3 = band3.ReadAsArray(0,0,x3,y3) # mul3 = numpy.multiply(data3, int(self.lineWeightA.value())) # # Create an output imagedriver with the reclassified values multiplied by the weight # driver3 = gdal.GetDriverByName( "GTiff" ) # outData3 = driver3.Create(str(aquifer_weight), x3,y3,1, gdal.GDT_Float32) # outData3.GetRasterBand(1).WriteArray(mul3) # outData3.SetGeoTransform(geo3) # outData3 = None # resamp_a = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/resamp_a.sdat" # Processing.runAlgorithm("saga:resampling", None, aquifer_weight, True, 0, 0, extent, pixelSize,0, None,3, resamp_a) # # # A # gdalRaster_a = gdal.Open(str(resamp_a)) # x_a = gdalRaster_a.RasterXSize # y_a = gdalRaster_a.RasterYSize # geo_a = gdalRaster_a.GetGeoTransform() # band_a = gdalRaster_a.GetRasterBand(1) # data_a = band_a.ReadAsArray(0,0,x_a,y_a) # # # # S # # resampling S raster # gdalRaster4 = gdal.Open(str(inputLayer4)) # # multiply by weight # soil_weight = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/soil_weight" # x4 = gdalRaster4.RasterXSize # y4 = gdalRaster4.RasterYSize # geo4 = gdalRaster4.GetGeoTransform() # band4 = gdalRaster4.GetRasterBand(1) # data4 = band4.ReadAsArray(0,0,x4,y4) # mul4 = numpy.multiply(data4, int(self.lineWeightS.value())) # # Create an output imagedriver with the reclassified values multiplied by the weight # driver4 = gdal.GetDriverByName( "GTiff" ) # outData4 = driver4.Create(str(soil_weight), x4,y4,1, gdal.GDT_Float32) # outData4.GetRasterBand(1).WriteArray(mul4) # outData4.SetGeoTransform(geo4) # outData4 = None # # # find nodata values # if self.lineWeightS.value()==2: # error = -299997 # # # soil_weight_correct = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/soil_weight_correct.sdat" # # # reclassify no data values # # Processing.initialize() # # Processing.runAlgorithm("saga:reclassifygridvalues", None, soil_weight, 0, error, 0, 0, 0.0, 1.0, 2.0, 0, "0,0,0,0,0,0,0,0,0", 0, True, 0.0, False, 0.0, soil_weight_correct) # # # # # resamp_s = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/resamp_s.sdat" # Processing.runAlgorithm("saga:resampling", None, soil_weight, True, 0, 0, extent, pixelSize,0, None,3, resamp_s) # # # S # gdalRaster_s = gdal.Open(str(resamp_s)) # x_s = gdalRaster_s.RasterXSize # y_s = gdalRaster_s.RasterYSize # geo_s = gdalRaster_s.GetGeoTransform() # band_s = gdalRaster_s.GetRasterBand(1) # data_s = band_s.ReadAsArray(0,0,x_s,y_s) # # # T # # resampling T raster # gdalRaster5 = gdal.Open(str(inputLayer5)) # # multiply by weight # topography_weight = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/topography_weight" # x5 = gdalRaster5.RasterXSize # y5 = gdalRaster5.RasterYSize # geo5 = gdalRaster5.GetGeoTransform() # band5 = gdalRaster5.GetRasterBand(1) # data5 = band5.ReadAsArray(0,0,x5,y5) # mul5 = numpy.multiply(data5, int(self.lineWeightT.value())) # # Create an output imagedriver with the reclassified values multiplied by the weight # driver5 = gdal.GetDriverByName( "GTiff" ) # outData5 = driver5.Create(str(topography_weight), x5,y5,1, gdal.GDT_Float32) # outData5.GetRasterBand(1).WriteArray(mul5) # outData5.SetGeoTransform(geo5) # outData5 = None # resamp_t = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/resamp_t.sdat" # Processing.runAlgorithm("saga:resampling", None, topography_weight, True, 0, 0, extent, pixelSize,0, None,3, resamp_t) # # # T # gdalRaster_t = gdal.Open(str(resamp_t)) # x_t = gdalRaster_t.RasterXSize # y_t = gdalRaster_t.RasterYSize # geo_t = gdalRaster_t.GetGeoTransform() # band_t = gdalRaster_t.GetRasterBand(1) # data_t = band_t.ReadAsArray(0,0,x_t,y_t) # #QMessageBox.about(self, "drastic", str(data_t)) # # # I # # resampling I raster # gdalRaster6 = gdal.Open(str(inputLayer6)) # # multiply by weight # impact_weight = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/impact_weight" # x6 = gdalRaster6.RasterXSize # y6 = gdalRaster6.RasterYSize # geo6 = gdalRaster6.GetGeoTransform() # band6 = gdalRaster6.GetRasterBand(1) # data6 = band6.ReadAsArray(0,0,x6,y6) # mul6 = numpy.multiply(data6, int(self.lineWeightI.value())) # # Create an output imagedriver with the reclassified values multiplied by the weight # driver6 = gdal.GetDriverByName( "GTiff" ) # outData6 = driver6.Create(str(impact_weight), x6,y6,1, gdal.GDT_Float32) # outData6.GetRasterBand(1).WriteArray(mul6) # outData6.SetGeoTransform(geo6) # outData6 = None # resamp_i = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/resamp_i.sdat" # Processing.runAlgorithm("saga:resampling", None, impact_weight, True, 0, 0, extent, pixelSize, 0, None,3,resamp_i) # # # I # gdalRaster_i = gdal.Open(str(resamp_i)) # x_i = gdalRaster_i.RasterXSize # y_i = gdalRaster_i.RasterYSize # geo_i = gdalRaster_i.GetGeoTransform() # band_i = gdalRaster_i.GetRasterBand(1) # data_i = band_i.ReadAsArray(0,0,x_i,y_i) # # # C # # resampling C raster # gdalRaster7 = gdal.Open(str(inputLayer7)) # # multiply by weight # hydraulic_weight = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/hydraulic_weight" # x7 = gdalRaster7.RasterXSize # y7 = gdalRaster7.RasterYSize # geo7 = gdalRaster7.GetGeoTransform() # band7 = gdalRaster7.GetRasterBand(1) # data7 = band7.ReadAsArray(0,0,x7,y7) # mul7 = numpy.multiply(data7, int(self.lineWeightC.value())) # # Create an output imagedriver with the reclassified values multiplied by the weight # driver7 = gdal.GetDriverByName( "GTiff" ) # outData7 = driver7.Create(str(hydraulic_weight), x7,y7,1, gdal.GDT_Float32) # outData7.GetRasterBand(1).WriteArray(mul7) # outData7.SetGeoTransform(geo7) # outData7 = None # resamp_c = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/resamp_c.sdat" # Processing.runAlgorithm("saga:resampling", None, hydraulic_weight, True, 0, 0, extent, pixelSize, 0, None,3, resamp_c) # # # C # gdalRaster_c = gdal.Open(str(resamp_c)) # x_c = gdalRaster_c.RasterXSize # y_c = gdalRaster_c.RasterYSize # geo_c = gdalRaster_c.GetGeoTransform() # band_c = gdalRaster_c.GetRasterBand(1) # data_c = band_c.ReadAsArray(0,0,x_c,y_c) # list_raster = [] # list_raster = list_raster + [inputLayer2]+[inputLayer3]+[inputLayer4]+[inputLayer5]+[inputLayer6]+[inputLayer7] # listt = ';'.join(list_raster) # # sum # first5 = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/first5" # Processing.runAlgorithm("gdal:rastercalculator", # {'INPUT_A': inputLayer, 'BAND_A': 1, 'INPUT_B': inputLayer2, 'BAND_B': 1, # 'INPUT_C': inputLayer3, 'BAND_C': 1, 'INPUT_D': inputLayer4, # 'BAND_D': 1, 'INPUT_E': inputLayer5, 'BAND_E': 1, 'INPUT_F': inputLayer6, 'BAND_F': 1, # 'FORMULA': "A+B+C+D+E+F", 'NO_DATA': None, 'RTYPE': 5, # 'EXTRA': '', 'OPTIONS': '', # 'OUTPUT': first5}) #Processing.runAlgorithm("gdal:rastercalculator", # {'INPUT_A': first5, 'BAND_A': 1, 'INPUT_B': inputLayer7, 'BAND_B': 1, # 'INPUT_C': None, 'BAND_C': -1, 'INPUT_D': None, # 'BAND_D': -1, 'INPUT_E': None, 'BAND_E': -1, 'INPUT_F': None, 'BAND_F': -1, # 'FORMULA': "A+B", 'NO_DATA': None, 'RTYPE': 5, # 'EXTRA': '', 'OPTIONS': '', # 'OUTPUT': outPath}) #QMessageBox.about(self, "drastic", str('\\"' + str(bn_inputLayer3) + '@1\'' + '\\"' + str(bn_inputLayer7) + '@1\' + '\\"' + str(bn_inputLayer) + '@1\'' + '\"' + str(bn_inputLayer6) + '@1\'' + '\"' + str(bn_inputLayer2) + '@1\'' + '\"' + str(bn_inputLayer4) + '@1\'' + '\"' + str(bn_inputLayer5) + '@1\'')) #drasti = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/drastic.sdat" drasti = process_path + "drastic.sdat" # multiplication by weights # D_weight = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/D_weight.sdat" # Processing.runAlgorithm("gdal:rastercalculator", # {'INPUT_A': inputLayer, 'BAND_A': 1, 'INPUT_B': None, # 'BAND_B': -1, 'INPUT_C': None, 'BAND_C': -1, 'INPUT_D': None, 'BAND_D': -1, # 'INPUT_E': None, # 'BAND_E': -1, 'INPUT_F': None, 'BAND_F': -1, # 'FORMULA': 'A*' + str(self.lineWeightD.value()), 'NO_DATA': None, 'RTYPE': 6, # 'OPTIONS': '', # 'OUTPUT': D_weight}) # Processing.runAlgorithm("grass7:r.mapcalc.simple", # {'a': resamp_d, # 'b': resamp_r, # 'c': resamp_a, # 'd': resamp_s, 'e': resamp_t, # 'f': resamp_t, 'expression': 'A*' + str(self.lineWeightD.value()) + '+B*' + str(self.lineWeightR.value()) + '+C*' + str(self.lineWeightA.value()) + '+D*' + str(self.lineWeightS.value()) + '+E*' + str(self.lineWeightT.value()) + '+F*' + str(self.lineWeightI.value()), 'output': drasti, # 'GRASS_REGION_PARAMETER': '20.6858,4109.2379,131434.879,134069.1139 [EPSG:3763]', # 'GRASS_REGION_CELLSIZE_PARAMETER': 30, 'GRASS_RASTER_FORMAT_OPT': '', # 'GRASS_RASTER_FORMAT_META': ''}) # Processing.runAlgorithm("grass7:r.mapcalc.simple", { # 'GRIDS': resamp_d, # 'XGRIDS': [resamp_r,resamp_a,resamp_s,resamp_t,resamp_i, resamp_c], # 'FORMULA': 'a*' + str(self.lineWeightD.value()) + '+b*' + str(self.lineWeightR.value()) + '+c*' + str(self.lineWeightA.value()) + '+d*' + str(self.lineWeightS.value()) + '+e*' + str(self.lineWeightT.value()) + '+f*' + str(self.lineWeightI.value()), 'RESAMPLING':3, 'USE_NODATA': False, 'TYPE': 7, 'RESULT': drasti} Processing.runAlgorithm( "grass7:r.mapcalc.simple", { 'a': resamp_d, 'b': resamp_r, 'c': resamp_a, 'd': resamp_s, 'e': resamp_t, 'f': resamp_i, 'expression': 'A*' + str(self.weight_d) + '+B*' + str(self.weight_r) + '+C*' + str(self.weight_a) + '+D*' + str(self.weight_s) + '+E*' + str(self.weight_t) + '+F*' + str(self.weight_i), 'output': drasti, 'GRASS_REGION_PARAMETER': extent + ' [EPSG:3763]', 'GRASS_REGION_CELLSIZE_PARAMETER': pixelSize, 'GRASS_RASTER_FORMAT_OPT': '', 'GRASS_RASTER_FORMAT_META': '' }) Processing.runAlgorithm( "grass7:r.mapcalc.simple", { 'a': drasti, 'b': resamp_c, 'c': None, 'd': None, 'e': None, 'f': None, 'expression': 'A+B*' + str(self.weight_c), 'output': outPath, 'GRASS_REGION_PARAMETER': extent + ' [EPSG:3763]', 'GRASS_REGION_CELLSIZE_PARAMETER': pixelSize, 'GRASS_RASTER_FORMAT_OPT': '', 'GRASS_RASTER_FORMAT_META': '' })
def calculate(self, process_path): qgs = QgsApplication([], False) qgs.initQgis() Processing.initialize() QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) gdal.AllRegister() inputLayer = self.input_file process_path = process_path outPath = self.output_file cellSize = self.cellSize Elevation = self.elevation lista_table = self.rattings for file in glob.glob(os.path.dirname(inputLayer) + "/a.*"): copyfile(file, process_path + os.path.basename(file)) inputLayer = process_path + os.path.basename(inputLayer) layer = QgsVectorLayer(inputLayer, inputLayer, "ogr") vectorlayer_vector = layer.dataProvider() # extent extent_rect = vectorlayer_vector.extent() xmin = extent_rect.xMinimum() xmax = extent_rect.xMaximum() ymin = extent_rect.yMinimum() ymax = extent_rect.yMaximum() extent = str(xmin) + "," + str(xmax) + "," + str(ymin) + "," + str( ymax) # read fields and add a new column with the indexes fields = layer.fields() new_field = QgsField("Indexes", QVariant.Double) layer_new = vectorlayer_vector.addAttributes([new_field]) layer.updateFields() newFieldIndex = vectorlayer_vector.fieldNameIndex(new_field.name()) allAttrs = vectorlayer_vector.attributeIndexes() # editing the new column #numberRows = int(self.tableWidget.rowCount()) #numberColumns = int(self.tableWidget.columnCount()) #classes = '' #lista = [] #for i in range(0,numberRows): # for j in range(0,numberColumns): # self.line = self.tableWidget.item(i,j) # lista = lista + [str(self.line.text())] # list of description on tool table #lista_table = lista field_names = [field.name() for field in fields] n = len(field_names) lista_attrib = [] for i in range(0, n): f = field_names[i] if f == str(Elevation): number = i for feat in layer.getFeatures(): attrb = feat.attributes() attribute_read = attrb[number] lista_attrib = lista_attrib + [str(attribute_read)] # list of description on attribute table of shapefile lista_attributes = lista_attrib #QMessageBox.about(self, "teste", str(lista_attributes)) # obtain the indexes of the description of shapefile attribute table description_common = set(lista_attributes).intersection(lista_table) listDescription = list(description_common) listElem = [] listElements = [] for j in range(0, len(listDescription)): elem = lista_table.index(listDescription[j]) listElements = listElements + [elem] elem_index = lista_table[int(elem + 1)] listElem = listElem + [float(elem_index)] for l in range(0, len(listElem)): layer.startEditing() exp = QgsExpression(str(listElem[l])) #exp.prepare() elemDescription = lista_table[listElements[l]] for f in layer.getFeatures(): # get attributes of column defined by the user attrb_elem = f[number] if attrb_elem == elemDescription: f[newFieldIndex] = exp.evaluate() layer.updateFeature(f) layer.commitChanges() list_attrb_newField = [] for features in layer.getFeatures(): attrb_newField = features.attributes() attrb_newField_read = attrb_newField[number + 1] # update and read the new field fieldsNew = layer.fields() field_names_new = [newField.name() for newField in fieldsNew] parameter_indexes = field_names_new[newFieldIndex] Processing.initialize() calculate = process_path + "/result.tif" #soil = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/soil.sdat" Processing.runAlgorithm( "grass7:v.to.rast", { 'input': inputLayer, 'type': [0, 1, 3], 'where': '', 'use': 0, 'attribute_column': parameter_indexes, 'rgb_column': None, 'label_column': None, 'value': 1, 'memory': 300, 'output': calculate, 'GRASS_REGION_PARAMETER': extent, 'GRASS_REGION_CELLSIZE_PARAMETER': cellSize, 'GRASS_RASTER_FORMAT_OPT': '', 'GRASS_RASTER_FORMAT_META': '', 'GRASS_SNAP_TOLERANCE_PARAMETER': -1, 'GRASS_MIN_AREA_PARAMETER': 0.0001 }) out_raster = gdal.Open(calculate) gdal.Warp(outPath, out_raster, dstSRS="EPSG:3857")
def add_poi_to_intersections(use='plugin'): if use == "standalone": app = QGuiApplication([]) QgsApplication.setPrefixPath(r'C:\Program Files\QGIS 3.0\apps\qgis', True) QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) QgsApplication.initQgis() feedback = QgsProcessingFeedback() """ implement Clip """ try: """Upload input data""" input = r'C:\Users\achituv\AppData\Roaming\QGIS\QGIS3\profiles\default\python\plugins\visibilitysyntax' \ r'/processing/poi_re.shp' overlay = 'C:/Users/achituv/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/visibilitysyntax' \ '/processing/buildings_0_re.shp' output = r'C:\Users\achituv\AppData\Roaming\QGIS\QGIS3\profiles\default\python\plugins\visibilitysyntax' \ r'\test\POI\results_file/cliped.shp' params = {'INPUT': input, 'OVERLAY': overlay, 'OUTPUT': output} processing.run('native:clip', params, feedback=feedback) print("Clip success") except: print("Clip failed") """ implement Extract """ try: """Upload input data""" input = 'C:/Users/achituv/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/visibilitysyntax/' \ 'processing/poi_re.shp' intersect = 'C:/Users/achituv/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/visibilitysyntax/' \ 'processing/buildings_0_re.shp' output = r'C:\Users\achituv\AppData\Roaming\QGIS\QGIS3\profiles\default\python\plugins\visibilitysyntax' \ r'\test\POI\results_file/extracted.shp' params = { 'INPUT': input, 'PREDICATE': [2], 'INTERSECT': intersect, 'OUTPUT': output } processing.run('native:extractbylocation', params, feedback=feedback) print("Extract success") except: print("Extract failed") """ implement Point along geometry """ try: input = 'C:/Users/achituv/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/visibilitysyntax' \ '/processing/highways_0_re.shp' output = r'C:\Users\achituv\AppData\Roaming\QGIS\QGIS3\profiles\default\python\plugins\visibilitysyntax' \ r'\test\POI\results_file/points_along.shp' alg = PointsAlongGeometry() alg.initAlgorithm() context = QgsProcessingContext() params = { 'INPUT': input, 'DISTANCE': 10, 'START_OFFSET': 0, 'END_OFFSET': 0, 'OUTPUT': output } res = alg.processAlgorithm(params, context, feedback=feedback) print("Point along geometry success") except: print("Point along geometry failed") """implement add ID""" try: hub_path = os.path.dirname( __file__) + r'/results_file/points_along.shp' junc = upload_new_layer(hub_path, "hub") if junc.fields()[len(junc.fields()) - 1].name() != "vis_id": junc.dataProvider().addAttributes( [QgsField("vis_id", QVariant.Int)]) junc.updateFields() n = len(junc.fields()) for i, feature in enumerate(junc.getFeatures()): junc.dataProvider().changeAttributeValues({i: {n - 1: i}}) print("add ID success") except: print("add ID failed") """ implement Distance to nearest hub """ try: """Upload input data""" input_path = r'C:\Users\achituv\AppData\Roaming\QGIS\QGIS3\profiles\default\python\plugins\visibilitysyntax' \ r'\test\POI\results_file/cliped.shp' input = upload_new_layer(input_path, "test_input") hubs_path = r'C:\Users\achituv\AppData\Roaming\QGIS\QGIS3\profiles\default\python\plugins\visibilitysyntax' \ r'\test\POI\results_file/points_along.shp' hubs = upload_new_layer(hubs_path, "test_hubs_") output = r'C:\Users\achituv\AppData\Roaming\QGIS\QGIS3\profiles\default\python\plugins\visibilitysyntax' \ r'\test\POI\results_file/line_to_points.shp' alg = HubDistanceLines() alg.initAlgorithm() # Some preprocessing for context project = QgsProject.instance() target_crs = QgsCoordinateReferenceSystem() target_crs.createFromOgcWmsCrs(input.crs().authid()) project.setCrs(target_crs) context = QgsProcessingContext() context.setProject(project) params = { 'INPUT': input, 'HUBS': hubs, 'FIELD': 'vis_id', 'UNIT': 4, 'OUTPUT': output } alg.processAlgorithm(params, context, feedback=feedback) print("Distance to nearest hub success") except: print("Distance to nearest hub failed") """ implement Polygon to lines """ try: input = 'C:/Users/achituv/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/visibilitysyntax/' \ 'processing/buildings_0_re.shp' output = r'C:\Users\achituv\AppData\Roaming\QGIS\QGIS3\profiles\default\python\plugins\visibilitysyntax' \ r'\test\POI\results_file\poly_as_lines.shp' alg = PolygonsToLines() alg.initAlgorithm() context = QgsProcessingContext() params = {'INPUT': input, 'OUTPUT': output} res = alg.processAlgorithm(params, context, feedback=feedback) print(" Polygon to lines success") except: print(" Polygon to lines failed") """ implement Line intersections """ try: """Upload input data""" input_path = r'C:\Users\achituv\AppData\Roaming\QGIS\QGIS3\profiles\default\python\plugins\visibilitysyntax' \ r'\test\POI\results_file\line_to_points.shp' input = upload_new_layer(input_path, "test_input") intersect_path = r'C:\Users\achituv\AppData\Roaming\QGIS\QGIS3\profiles\default\python\plugins\visibilitysyntax' \ r'\test\POI\results_file\poly_as_lines.shp' intersect = upload_new_layer(intersect_path, "test_intersect") output = r'C:\Users\achituv\AppData\Roaming\QGIS\QGIS3\profiles\default\python\plugins\visibilitysyntax' \ r'\test\POI\results_file\off_pnts.shp' params = { 'INPUT': input, 'INTERSECT': intersect, 'INPUT_FIELDS': [], 'INTERSECT_FIELDS': [], 'OUTPUT': output } processing.run('native:lineintersections', params, feedback=feedback) print("Line intersections success") except: print("Line intersections failed") """ implement Merge """ try: layer_2 = upload_new_layer( r'C:/Users/achituv/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/visibilitysyntax' r'/test\mean_close_point\mean_close_coor.shp', 'test1') layer_1 = upload_new_layer( r'C:\Users\achituv\AppData\Roaming\QGIS\QGIS3\profiles\default\python\plugins\visibilitysyntax' \ r'\test\POI\results_file/extracted.shp', 'test2') layer_3 = upload_new_layer( r'C:\Users\achituv\AppData\Roaming\QGIS\QGIS3\profiles\default\python\plugins\visibilitysyntax' \ r'\test\POI\results_file\off_pnts.shp', 'test3') layers = [layer_1, layer_2, layer_3] OUTPUT = r'C:\Users\achituv\AppData\Roaming\QGIS\QGIS3\profiles\default\python\plugins\visibilitysyntax' \ r'\test\POI\results_file\merge.shp' params = {'LAYERS': layers, 'CRS': 'EPSG:3857', 'OUTPUT': OUTPUT} processing.run('native:mergevectorlayers', params, feedback=feedback) print("Merge success") except: print("Merge failed") """ implement Delete Duplicate geometry """ try: """Upload input data""" feedback = QgsProcessingFeedback() """Upload input data""" input = 'C:/Users/achituv/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/visibilitysyntax/test/POI' \ '/results_file/merge.shp' OUTPUT = r'C:\Users\achituv\AppData\Roaming\QGIS\QGIS3\profiles\default\python\plugins\visibilitysyntax\test\POI' \ r'\results_file\final.shp' alg = DeleteDuplicateGeometries() alg.initAlgorithm() context = QgsProcessingContext() params = {'INPUT': input, 'OUTPUT': OUTPUT} res = alg.processAlgorithm(params, context, feedback=feedback) print("Delete Duplicate geometry success") except: print("Delete Duplicate geometry failed") """For standalone application""" if use == 'standalone': QgsApplication.exitQgis() app.exit()
def init_processing() -> None: from processing.core.Processing import Processing from qgis.analysis import QgsNativeAlgorithms from qgis.core import QgsApplication QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) Processing.initialize()
def calculate(self, process_path): qgs = QgsApplication([], False) qgs.initQgis() Processing.initialize() QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) gdal.AllRegister() process_path = process_path outPath = self.output_file cellSize = self.cellSize # read D raster inputLayer = self.input_file_g #bn_inputLayer = str(os.path.splitext(os.path.basename(inputLayer))[0]) #teste = str(bn_inputLayer) + '@1\'' #QMessageBox.about(self, "drastic", str(teste)) # read R raster inputLayer2 = self.input_file_o #bn_inputLayer2 = str(os.path.splitext(os.path.basename(inputLayer2))[0]) # read A raster inputLayer3 = self.input_file_d #bn_inputLayer3 = str(os.path.splitext(os.path.basename(inputLayer3))[0]) # outpath #outPath = self.outputLayerCombo.text() #gdal.AllRegister() # sum of the raster = DRASTIC # D gdalRaster = gdal.Open(str(inputLayer)) # # multiply by weight # depth_weight = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/depth_weight" x = gdalRaster.RasterXSize y = gdalRaster.RasterYSize geo = gdalRaster.GetGeoTransform() # band = gdalRaster.GetRasterBand(1) # data = band.ReadAsArray(0,0,x,y) # mul = numpy.multiply(data, int(self.lineWeightD.value())) # # Create an output imagedriver with the reclassified values multiplied by the weight # driver = gdal.GetDriverByName( "GTiff" ) # outData = driver.Create(str(depth_weight), x,y,1, gdal.GDT_Float32) # outData.GetRasterBand(1).WriteArray(mul) # outData.SetGeoTransform(geo) # outData = None # # geo = gdalRaster.GetGeoTransform() # # pixel size pixelSize = geo[1] #pixelSize = 30 # extent minx = geo[0] maxy = geo[3] maxx = minx + geo[1] * x miny = maxy + geo[5] * y extent = str(minx) + "," + str(maxx) + "," + str(miny) + "," + str( maxy) band = gdalRaster.GetRasterBand(1) #data_d = band.ReadAsArray(0,0,x,y) Processing.initialize() Processing.runAlgorithm( "grass7:r.mapcalc.simple", { 'a': inputLayer, 'b': inputLayer2, 'c': inputLayer3, 'd': inputLayer, 'e': inputLayer, 'f': inputLayer, 'expression': 'A*B*C', 'output': outPath, 'GRASS_REGION_PARAMETER': extent + '[EPSG:3763]', 'GRASS_REGION_CELLSIZE_PARAMETER': pixelSize, 'GRASS_RASTER_FORMAT_OPT': '', 'GRASS_RASTER_FORMAT_META': '' })