def run(algOrName, parameters, onFinish=None, feedback=None, context=None, is_child_algorithm=False): """ Executes given algorithm and returns its outputs as dictionary object. :param algOrName: Either an instance of an algorithm, or an algorithm's ID :param parameters: Algorithm parameters dictionary :param onFinish: optional function to run after the algorithm has completed :param feedback: Processing feedback object :param context: Processing context object :param is_child_algorithm: Set to True if this algorithm is being run as part of a larger algorithm, i.e. it is a sub-part of an algorithm which calls other Processing algorithms. :returns algorithm results as a dictionary, or None if execution failed :rtype: Union[dict, None] """ if onFinish or not is_child_algorithm: return Processing.runAlgorithm(algOrName, parameters, onFinish, feedback, context) else: # for child algorithms, we disable to default post-processing step where layer ownership # is transferred from the context to the caller. In this case, we NEED the ownership to remain # with the context, so that further steps in the algorithm have guaranteed access to the layer. def post_process(_alg, _context, _feedback): return return Processing.runAlgorithm(algOrName, parameters, onFinish=post_process, feedback=feedback, context=context)
def runAndLoadResults(algOrName, parameters, feedback=None, context=None): """ Executes given algorithm and load its results into the current QGIS project when possible. :param algOrName: Either an instance of an algorithm, or an algorithm's ID :param parameters: Algorithm parameters dictionary :param feedback: Processing feedback object :param context: Processing context object :returns algorithm results as a dictionary, or None if execution failed :rtype: Union[dict, None] """ if isinstance(algOrName, QgsProcessingAlgorithm): alg = algOrName else: alg = QgsApplication.processingRegistry().createAlgorithmById(algOrName) # output destination parameters to point to current project for param in alg.parameterDefinitions(): if not param.name() in parameters: continue if isinstance(param, (QgsProcessingParameterFeatureSink, QgsProcessingParameterVectorDestination, QgsProcessingParameterRasterDestination)): p = parameters[param.name()] if not isinstance(p, QgsProcessingOutputLayerDefinition): parameters[param.name()] = QgsProcessingOutputLayerDefinition(p, QgsProject.instance()) else: p.destinationProject = QgsProject.instance() parameters[param.name()] = p return Processing.runAlgorithm(alg, parameters=parameters, onFinish=handleAlgorithmResults, feedback=feedback, context=context)
def run(algOrName, *args, **kwargs): """Executes given algorithm and returns its outputs as dictionary object. """ alg = Processing.runAlgorithm(algOrName, None, *args, **kwargs) if alg is not None: return alg.getOutputValuesAsDictionary()
def execute(self): # Run alg with params # TODO: get args args = {} for k in self._inputs: v = getattr(self, k) args[v.identifier] = v.getValue() # Adds None for output parameter(s) for k in self._outputs: v = getattr(self, k) args[v.identifier] = None #processing.runalg("grass:v.hull","/home/ale/Documenti/maps/regioni_semplificato_4326.shp",False,"6.6268611901,18.5188598654,35.4930324712,47.0862707258",-1,0.0001,0,None) from processing import runalg alg = Processing.runAlgorithm(self.alg, None, args) if alg is not None: result = alg.getOutputValuesAsDictionary() for k in self._outputs: v = getattr(self, k) args[v.identifier] = result.get(k, None) return
def runAndLoadResults(algOrName, parameters, feedback=None, context=None): """ Executes given algorithm and load its results into the current QGIS project when possible. :param algOrName: Either an instance of an algorithm, or an algorithm's ID :param parameters: Algorithm parameters dictionary :param feedback: Processing feedback object :param context: Processing context object :returns algorithm results as a dictionary, or None if execution failed :rtype: Union[dict, None] """ if isinstance(algOrName, QgsProcessingAlgorithm): alg = algOrName else: alg = QgsApplication.processingRegistry().createAlgorithmById( algOrName) # output destination parameters to point to current project for param in alg.parameterDefinitions(): if not param.name() in parameters: continue if isinstance(param, (QgsProcessingParameterFeatureSink, QgsProcessingParameterVectorDestination, QgsProcessingParameterRasterDestination)): p = parameters[param.name()] if not isinstance(p, QgsProcessingOutputLayerDefinition): parameters[param.name()] = QgsProcessingOutputLayerDefinition( p, QgsProject.instance()) else: p.destinationProject = QgsProject.instance() parameters[param.name()] = p return Processing.runAlgorithm(alg, parameters=parameters, onFinish=handleAlgorithmResults, feedback=feedback, context=context)
def test_layer_algorithm(outputdir, data): """ Copy layer """ alg = _find_algorithm('pyqgiswps_test:testcopylayer') inputs = { p.name(): [parse_input_definition(p)] for p in alg.parameterDefinitions() } outputs = { p.name(): parse_output_definition(p) for p in alg.outputDefinitions() } inputs['INPUT'][0].data = 'france_parts' inputs['OUTPUT'][0].data = 'france_parts_2' # Load source project source = QgsProject() rv = source.read(data.join('france_parts.qgs').strpath) assert rv == True workdir = outputdir.strpath context = Context(source, workdir) feedback = QgsProcessingFeedback() parameters = dict( input_to_processing(ident, inp, alg, context) for ident,inp in inputs.items() ) assert isinstance( parameters['OUTPUT'], QgsProcessingOutputLayerDefinition) # Run algorithm with chdir(outputdir.strpath): results = Processing.runAlgorithm(alg, parameters=parameters, onFinish=handle_algorithm_results, feedback=feedback, context=context) assert context.destination_project.count() == 1 handle_layer_outputs(results, context) assert results['OUTPUT'] == parameters['OUTPUT'].destinationName output_uri = "http://localhost/wms/MAP=test/{name}.qgs".format(name=alg.name()) write_outputs( alg, results, outputs, output_uri, context ) assert outputs
def runAndLoadResults(algOrName, parameters, feedback=None, context=None): """Executes given algorithm and load its results into QGIS project when possible. """ if isinstance(algOrName, QgsProcessingAlgorithm): alg = algOrName else: alg = QgsApplication.processingRegistry().createAlgorithmById(algOrName) # output destination parameters to point to current project for param in alg.parameterDefinitions(): if not param.name() in parameters: continue if isinstance(param, (QgsProcessingParameterFeatureSink, QgsProcessingParameterVectorDestination, QgsProcessingParameterRasterDestination)): p = parameters[param.name()] if not isinstance(p, QgsProcessingOutputLayerDefinition): parameters[param.name()] = QgsProcessingOutputLayerDefinition(p, QgsProject.instance()) else: p.destinationProject = QgsProject.instance() parameters[param.name()] = p return Processing.runAlgorithm(alg, parameters=parameters, onFinish=handleAlgorithmResults, feedback=feedback, context=context)
def convert(self): self.buttonBox.button(QDialogButtonBox.Ok).setDefault(False) inputLayer = self.inputLayerCombo.currentText() # layer information 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) # attribute Elevation = self.lineAttrib.currentText() # cellsize cellSize = int(self.linePix.value()) outPath = self.inputLayerCombo3.text() # read fields and add a new column with the indexes fields = layer.fields() new_field = QgsField("Indexes", QVariant.Int) 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 # [xistos argilosos, argilitos, 2, rocha metamorfica/ignea, 3, ...] 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 # [xistos argilosos, argilitos, xistos argilosos, argilitos, till glaciar, ...] # obtain the indexes of the description of shapefile attribute table description_common = set(lista_attributes).intersection(lista_table) listDescription = list(description_common) # [xistos argilosos, argilitos, till glaciar] listElem = [] listElements = [] for j in range(0, len(listDescription)): elem = lista_table.index(listDescription[j]) listElements = listElements + [elem] # [0,6] elem_index = lista_table[int(elem + 1)] listElem = listElem + [int(elem_index)] # [2,5] for l in range(0, len(listElem)): layer.startEditing() exp = QgsExpression(str(listElem[l])) #exp.prepare(fields) 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() soil = QFileInfo( QgsApplication.qgisUserDatabaseFilePath()).path() + "/soil" Processing.runAlgorithm( "saga:rasterize", { 'INPUT': inputLayer, 'FIELD': parameter_indexes, 'OUTPUT': 2, 'MULTIPLE': 4, 'LINE_TYPE': 0, 'POLY_TYPE': 0, 'GRID_TYPE': 3, 'TARGET_USER_XMIN TARGET_USER_XMAX TARGET_USER_YMIN TARGET_USER_YMAX': extent + ' [EPSG:3763]', 'TARGET_USER_SIZE': cellSize, 'TARGET_USER_FITS': 0, 'GRID': outPath }) #soil_complete = soil + "." + "tif" #Processing.runAlgorithm("grass:v.to.rast.attribute", None, inputLayer, 0, parameter_indexes, extent, cellSize, -1.0, 0.0001, outPath) #Processing.runAlgorithm("grass7:r.surf.idw", None, soil_complete , 12, False, extent, cellSize, outPath) #soil_weight = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/soil_weight" #soil_weight_complete = soil_weight + "." + "tif" ## multiply by the weight #soil_media = soil + "." + "tif" #gdalRaster = gdal.Open(str(soil_media)) #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.lineWeight.value())) ## Create an output imagedriver with the reclassified values multiplied by the weight #driver = gdal.GetDriverByName( "GTiff" ) #outData = driver.Create(str(soil_weight_complete), x,y,1, gdal.GDT_Float32) #outData.GetRasterBand(1).WriteArray(mul) #outData.SetGeoTransform(geo) #outData = None ## eliminate no data values #if self.lineWeight.value()==5: #error = -499995 #elif self.lineWeight.value()==4: #error = -399996 #elif self.lineWeight.value()==3: #error = -299997 #elif self.lineWeight.value()==2: #error = -199998 #QMessageBox.about(self, "aquifer", str(error)) ## reclassify no data values #Processing.initialize() #Processing.runAlgorithm("saga:reclassifygridvalues", None, soil_weight_complete, 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, outPath) # add result into canvas # file_info = QFileInfo(outPath) # if file_info.exists(): # layer_name = file_info.baseName() # else: # return False # rlayer_new = QgsRasterLayer(outPath, layer_name) # if rlayer_new.isValid(): # QgsMapLayerRegistry.instance().addMapLayer(rlayer_new) # layer = QgsMapCanvasLayer(rlayer_new) # layerList = [layer] # extent = self.iface.canvas.setExtent(rlayer_new.extent()) # self.iface.canvas.setLayerSet(layerList) # self.iface.canvas.setVisible(True) # return True # else: # return False # QMessageBox.information(self, self.tr( "Finished" ), self.tr( "Aquifer media completed." ) ) # add result into canvas file_info_norm = QFileInfo(str(outPath)) # QMessageBox.about(self, "teste", str(file_info_norm)) rlayer_new_norm = QgsRasterLayer(outPath, 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]) self.buttonBox.button(QDialogButtonBox.Ok).setDefault(True)
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': '' })
def run(algOrName, parameters, onFinish=None, feedback=None, context=None): """Executes given algorithm and returns its outputs as dictionary object. """ return Processing.runAlgorithm(algOrName, parameters, onFinish, feedback, context)
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 runalg(algOrName, *args, **kwargs): alg = Processing.runAlgorithm(algOrName, None, *args, **kwargs) if alg is not None: return alg.getOutputValuesAsDictionary()
def runAndLoadResults(name, *args, **kwargs): """Executes given algorithm and load its results into QGIS project when possible. """ return Processing.runAlgorithm(name, handleAlgorithmResults, *args, **kwargs)
def test_context(outputdir, data): """ Context with Copy layer """ alg = _find_algorithm('pyqgiswps_test:testcopylayer') inputs = { p.name(): [parse_input_definition(p)] for p in alg.parameterDefinitions() } outputs = { p.name(): parse_output_definition(p) for p in alg.outputDefinitions() } inputs['INPUT'][0].data = 'france_parts' inputs['OUTPUT'][0].data = 'france_parts_2' workdir = outputdir.strpath context = ProcessingContext(workdir, 'france_parts.qgs') feedback = QgsProcessingFeedback() parameters = dict( input_to_processing(ident, inp, alg, context) for ident, inp in inputs.items()) assert isinstance(parameters['OUTPUT'], QgsProcessingOutputLayerDefinition) # Run algorithm with chdir(outputdir.strpath): results = Processing.runAlgorithm(alg, parameters=parameters, onFinish=handle_algorithm_results, feedback=feedback, context=context) assert context.destination_project.count() == 1 handle_layer_outputs(results, context) assert results['OUTPUT'] == parameters['OUTPUT'].destinationName output_uri = "http://localhost/wms/MAP=test/{name}.qgs".format( name=alg.name()) write_outputs(alg, results, outputs, output_uri, context) assert outputs assert context.destination_project.fileName() == outputdir.join( alg.name() + '.qgs').strpath # WFS configuration inserted WFSLayers = context.destination_project.readListEntry('WFSLayers', '/')[0] assert len(WFSLayers) != 0 # All Vector Layers has been published in WFS mapLayers = context.destination_project.mapLayers() assert len(WFSLayers) == len([ lid for lid, lyr in mapLayers.items() if lyr.type() == QgsMapLayer.VectorLayer ]) # Verifying th WFS configuration for lid in WFSLayers: lyr = context.destination_project.mapLayer(lid) # Is the WFS layer id references a Map Layer assert lyr # Is the WFS layer id references a Vector Layer assert lyr.type() == QgsMapLayer.VectorLayer # The WFS layer precision is defined assert context.destination_project.readNumEntry( "WFSLayersPrecision", "/" + lid)[0] == 6
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")
def convert(self): self.buttonBox.button(QDialogButtonBox.Ok).setDefault(False) inputLayer = self.inputLayerCombo.currentText() # layer information layer = QgsVectorLayer(unicode(inputLayer).encode('utf8'), 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) # attribute Elevation = self.lineAttrib.currentText() # cellsize cellSize = int(self.linePix.value()) outPath = self.inputLayerCombo3.text() # indexes for hidraulic conductivity 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 = "," intervals = string.join(lista) QMessageBox.about(self, 'teste', str(intervals)) Processing.initialize() conductivity = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/conductivity" Processing.runAlgorithm("grass7:v.to.rast.attribute", None, inputLayer, 0, Elevation, extent, cellSize, -1.0, 0.0001, conductivity) conductivity_raster = conductivity + "." + "tif" cond_reclassify = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/cond_reclassify.sdat" Processing.runAlgorithm("saga:reclassifygridvalues", None, conductivity_raster, 2, 0.0, 1.0, 0, 0.0, 1.0, 2.0, 0, intervals, 0, True, 0.0, True, 0.0, cond_reclassify) Processing.runAlgorithm("grass:r.surf.idw", None, cond_reclassify, 12, False, extent, cellSize, outPath) # add result into canvas file_info = QFileInfo(outPath) if file_info.exists(): layer_name = file_info.baseName() else: return False rlayer_new = QgsRasterLayer(outPath, layer_name) if rlayer_new.isValid(): QgsMapLayerRegistry.instance().addMapLayer(rlayer_new) layer = QgsMapCanvasLayer(rlayer_new) layerList = [layer] extent = self.iface.canvas.setExtent(rlayer_new.extent()) self.iface.canvas.setLayerSet(layerList) self.iface.canvas.setVisible(True) return True else: return False QMessageBox.information(self, self.tr( "Finished" ), self.tr( "Hidraulic conductivity completed." ) ) self.buttonBox.button(QDialogButtonBox.Ok).setDefault(True)
def runandload(name, *args): return Processing.runAlgorithm(name, Postprocessing.handleAlgorithmResults, *args)
QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) from processing.core.Processing import Processing Processing.initialize() import processing # somehow warning and error messages disappeared, here I turn them on again import cgitb cgitb.enable(format='text') # test processing toolbox # first qgis:aspect (works) args = "C:/Users/pi37pat/Desktop/dem.tif", "1",\ "C:/Users/pi37pat/Desktop/aspect13.tif" params = "INPUT", "Z_FACTOR", "OUTPUT" params = dict((x, y) for x, y in zip(params, args)) feedback = QgsProcessingFeedback() Processing.runAlgorithm(algOrName = 'qgis:aspect', parameters = params, feedback = feedback) # # next we try a native algorithm args = "C:/Users/pi37pat/Desktop/polys.shp", "C:/Users/pi37pat/Desktop/points.shp" params = "INPUT", "OUTPUT" params = dict((x, y) for x, y in zip(params, args)) feedback = QgsProcessingFeedback() Processing.runAlgorithm(algOrName = 'native:centroids', parameters = params, feedback = feedback) # # let's try grass7:r.slope.aspect, this does not work # args = "C:/Users/pi37pat/Desktop/dem.tif", "0", "0", True, "1.0", "0.0",\ # "C:/Users/pi37pat/Desktop/slope.tif", None, None, None, None, None, None, None,\ # None, "794599.107614635,798208.557614635,8931774.87460253,8935384.32460253",\ # "0.0", None, None # params = "elevation", "format", "precision", "-a", "zscale", "min_slope",\
def convert(self): self.buttonBox.button(QDialogButtonBox.Ok).setDefault(False) # read D raster inputLayer = self.inputLayerCombo.currentText() bn_inputLayer = str(os.path.splitext(os.path.basename(inputLayer))[0]) teste = str(bn_inputLayer) + '@1\'' QMessageBox.about(self, "Fissured", str(teste)) # read R raster inputLayer2 = self.inputLayerCombo2.currentText() bn_inputLayer2 = str(os.path.splitext(os.path.basename(inputLayer2))[0]) # read A raster inputLayer3 = self.inputLayerCombo3.currentText() bn_inputLayer3 = str(os.path.splitext(os.path.basename(inputLayer3))[0]) # read S raster inputLayer4 = self.inputLayerCombo4.currentText() bn_inputLayer4 = str(os.path.splitext(os.path.basename(inputLayer4))[0]) # read T raster inputLayer5 = self.inputLayerCombo5.currentText() bn_inputLayer5 = str(os.path.splitext(os.path.basename(inputLayer5))[0]) # read I raster inputLayer6 = self.inputLayerCombo6.currentText() bn_inputLayer6 = str(os.path.splitext(os.path.basename(inputLayer6))[0]) # read C raster inputLayer7 = self.inputLayerCombo7.currentText() bn_inputLayer7 = str(os.path.splitext(os.path.basename(inputLayer7))[0]) # outpath outPath = self.outputLayerCombo.text() gdal.AllRegister() # sum of the raster = Fissured # 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] # 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_Fissured.sdat" # Processing.runAlgorithm("saga:resampling", None, recharge_weight, True, 0, 0, extent, pixelSize, resamp_r) 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_Fissured.sdat" # Processing.runAlgorithm("saga:resampling", None, recharge_weight, True, 0, 0, extent, pixelSize, resamp_r) 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_Fissured.sdat" # 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}) resamp_s = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/resamp_s_Fissured.sdat" # 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}) resamp_t = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/resamp_t_Fissured.sdat" # 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}) resamp_i = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/resamp_t_Fissured.sdat" # 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}) resamp_c = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/resamp_t_Fissured.sdat" # 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}) # # # 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, "Fissured", 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, "Fissured", 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() + "/drasti.sdat" Processing.runAlgorithm("gdal:rastercalculator", {'INPUT_A': resamp_d, 'BAND_A': 1, 'INPUT_B': resamp_r, 'BAND_B': 1, 'INPUT_C': resamp_a, 'BAND_C': 1, 'INPUT_D': resamp_s, 'BAND_D': 1, 'INPUT_E': resamp_t, 'BAND_E': 1, 'INPUT_F': resamp_i, 'BAND_F': 1, 'FORMULA': 'A+B+C+D+E+F', 'NO_DATA': None, 'RTYPE': 5, 'EXTRA': '', 'OPTIONS': '', 'OUTPUT': drasti}) Processing.runAlgorithm("gdal:rastercalculator", {'INPUT_A': drasti, 'BAND_A': 1, 'INPUT_B': resamp_c, '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}) # summ = data_d + data_r + data_a + data_s + data_t + data_i + data_c # # sum_nodata = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/sum_nodata" # sum_nodata_rec = sum_nodata + "." + "tif" # # # Create an output imagedriver with the reclassified values multiplied by the weight # driver_sum = gdal.GetDriverByName( "GTiff" ) # outData_sum = driver_sum.Create(str(sum_nodata), x,y,1, gdal.GDT_Float32) # outData_sum.GetRasterBand(1).WriteArray(summ) # outData_sum.SetGeoTransform(geo) # outData_sum = None # reclassify no data values # Processing.runAlgorithm("saga:reclassifygridvalues", None, sum_nodata, 0, -10000100352, 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, outPath) if self.checkFissured.isChecked(): # add result into canvas file_info_norm = QFileInfo(str(outPath)) # QMessageBox.about(self, "teste", str(file_info_norm)) rlayer_new_norm = QgsRasterLayer(outPath, 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 = QFileInfo(outPath) # if file_info.exists(): # layer_name = file_info.baseName() # else: # return False # rlayer_new = QgsRasterLayer(outPath, layer_name) # if rlayer_new.isValid(): # QgsMapLayerRegistry.instance().addMapLayer(rlayer_new) # layer = QgsMapCanvasLayer(rlayer_new) # layerList = [layer] # extent = self.iface.canvas.setExtent(rlayer_new.extent()) # self.iface.canvas.setLayerSet(layerList) # self.iface.canvas.setVisible(True) # return True # else: # return False QMessageBox.information(self, self.tr("Finished"), self.tr("Fissured completed.")) self.buttonBox.button(QDialogButtonBox.Ok).setDefault(True)
def execute(self): # create a project p = QgsProject.instance() mlr = QgsMapLayerRegistry.instance() # Run alg with params # TODO: get args args = {} # get vector and raster inputs inputCrs = None for k in self._inputs: v = getattr(self, k) parm = self.alg.getParameterFromName( v.identifier ) # vector layers if parm.__class__.__name__ == 'ParameterVector': values = [] if vectorLayers and ParameterVector.VECTOR_TYPE_ANY in parm.shapetype : values = [l for l in vectorLayers] elif vectorLayers : if ParameterVector.VECTOR_TYPE_POINT in parm.shapetype : values += [l for l in vectorLayers if l['geometry'] == 'Point'] if ParameterVector.VECTOR_TYPE_LINE in parm.shapetype : values += [l for l in vectorLayers if l['geometry'] == 'Line'] if ParameterVector.VECTOR_TYPE_POLYGON in parm.shapetype : values += [l for l in vectorLayers if l['geometry'] == 'Polygon'] if values : layerName = v.getValue() values = [l for l in values if l['name'] == layerName] l = values[0] layer = QgsVectorLayer( l['datasource'], l['name'], l['provider'] ) crs = l['crs'] qgsCrs = None if str(crs).startswith('USER:'******'proj4']) ) else : qgsCrs = QgsCoordinateReferenceSystem( str(crs) ) if qgsCrs : layer.setCrs( qgsCrs ) mlr.addMapLayer( layer, False ) args[v.identifier] = layer inputCrs = layer.crs() else : fileName = v.getValue() fileInfo = QFileInfo( fileName ) # move fileName to fileName.gml for ogr with open( fileName, 'r' ) as f : o = open( fileName+'.gml', 'w' ) o.write( f.read() ) o.close() import shutil shutil.copy2(fileName+'.gml', '/tmp/test.gml' ) # get layer layer = QgsVectorLayer( fileName+'.gml', fileInfo.baseName(), 'ogr' ) pr = layer.dataProvider() e = layer.extent() mlr.addMapLayer( layer, False ) args[v.identifier] = layer inputCrs = layer.crs() # raster layers elif parm.__class__.__name__ == 'ParameterRaster': if rasterLayers : layerName = v.getValue() values = [l for l in rasterLayers if l['name'] == layerName] l = values[0] layer = QgsRasterLayer( l['datasource'], l['name'], l['provider'] ) crs = l['crs'] qgsCrs = None if str(crs).startswith('USER:'******'proj4']) ) else : qgsCrs = QgsCoordinateReferenceSystem( str(crs) ) if qgsCrs : layer.setCrs( qgsCrs ) mlr.addMapLayer( layer, False ) args[v.identifier] = layer inputCrs = layer.crs() else : fileName = v.getValue() fileInfo = QFileInfo( fileName ) layer = QgsRasterLayer( fileName, fileInfo.baseName(), 'gdal' ) mlr.addMapLayer( layer, False ) args[v.identifier] = layer inputCrs = layer.crs() elif parm.__class__.__name__ == 'ParameterExtent': coords = v.getValue().coords args[v.identifier] = str(coords[0][0])+','+str(coords[1][0])+','+str(coords[0][1])+','+str(coords[1][1]) else: args[v.identifier] = v.getValue() # if extent in inputs, transform it to the alg CRS if inputCrs: for k in self._inputs: v = getattr(self, k) parm = self.alg.getParameterFromName( v.identifier ) if parm.__class__.__name__ == 'ParameterExtent': coords = v.getValue().coords coordCrs = QgsCoordinateReferenceSystem( str( v.getValue().crs ) ) coordExtent = QgsRectangle( coords[0][0], coords[0][1], coords[1][0], coords[1][1] ) xform = QgsCoordinateTransform( coordCrs, inputCrs ) coordExtent = xform.transformBoundingBox( coordExtent ) args[v.identifier] = str(coordExtent.xMinimum())+','+str(coordExtent.xMaximum())+','+str(coordExtent.yMinimum())+','+str(coordExtent.yMaximum()) # Adds None for output parameter(s) for k in self._outputs: v = getattr(self, k) args[v.identifier] = None if not len( self.alg.parameters ): self.alg.defineCharacteristics() tAlg = Processing.runAlgorithm(self.alg, None, args) # if runalg failed return exception message if not tAlg: return 'Error in processing' # clear map layer registry mlr.removeAllMapLayers() # get result result = tAlg.getOutputValuesAsDictionary() for k in self._outputs: v = getattr(self, k) parm = self.alg.getOutputFromName( v.identifier ) if parm.__class__.__name__ == 'OutputVector': outputName = result.get(v.identifier, None) if not outputName : return 'No output file' # get output file info outputInfo = QFileInfo( outputName ) # get the output QGIS vector layer outputLayer = QgsVectorLayer( outputName, outputInfo.baseName(), 'ogr' ) # Update CRS # outputLayer.setCrs( tAlg.crs ) # define the file extension outputExt = 'gml' if v.format['mimetype'] == 'application/json': outputExt = 'geojson' # define the output file path outputFile = os.path.join( outputInfo.absolutePath(), outputInfo.baseName()+'.'+outputExt ) # write the output GML file if v.format['mimetype'] == 'application/json': error = QgsVectorFileWriter.writeAsVectorFormat( outputLayer, outputFile, 'utf-8', None, 'GeoJSON', False, None ) elif v.format['mimetype'] in ('text/xml; subtype=gml/3.1.1','application/gml+xml; version=3.1.1') : error = QgsVectorFileWriter.writeAsVectorFormat( outputLayer, outputFile, 'utf-8', None, 'GML', False, None, ['XSISCHEMAURI=http://schemas.opengis.net/gml/3.1.1/base/feature.xsd','FORMAT=GML3'] ) else: error = QgsVectorFileWriter.writeAsVectorFormat( outputLayer, outputFile, 'utf-8', None, 'GML', False, None, ['XSISCHEMAURI=http://schemas.opengis.net/gml/2.1.2/feature.xsd'] ) args[v.identifier] = outputFile # add output layer to map layer registry #outputLayer = QgsVectorLayer( outputFile, v.identifier, 'ogr' ) #mlr.addMapLayer( outputLayer ) elif parm.__class__.__name__ == 'OutputRaster': outputName = result.get(v.identifier, None) if not outputName : return 'No output file' args[v.identifier] = outputName else: args[v.identifier] = result.get(v.identifier, None) for k in self._outputs: v = getattr(self, k) v.setValue( args[v.identifier] ) return
def convert(self): self.buttonBox.button(QDialogButtonBox.Ok).setDefault(False) inputLayer = self.inputLayerCombo.currentText() # layer information 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) # attribute Elevation = self.lineAttrib.currentText() # cellsize cellSize = int(self.linePix.value()) outPath = self.inputLayerCombo3.text() # indexes for hidraulic conductivity 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 = "," intervals = string.join(lista) results = list(map(float, lista)) Processing.initialize() conductivity = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).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}) # list_new = [] # list_new_x = [] # list_new_y = [] # # QMessageBox.about(self, 'teste', str(self.plugin_dir)) # # FILE = os.path.join(self.plugin_dir, "//SINTACS grafico D.txt") # with open(os.path.join(self.plugin_dir, "SINTACS grafico C.txt"), 'r') as f: # d = {line.split('\t')[0]: line.split('\t')[1] for line in f} # #QMessageBox.about(self, "teste", str(d)) # # read raster values # raster = gdal.Open(str(conductivity)) # data_mdt = raster.ReadAsArray() # values_raster = numpy.unique(data_mdt) # # QMessageBox.about(self, 'teste', values_raster) # for element in values_raster: # # get the key of a certain value # target = element # # key, value = min(d.items(), key=lambda kv: abs(float(kv[1]) - target)) # m = d.get(target, d[min(d.keys(), key=lambda k: abs(float(k) - target))]) # # remove \n from list # m_new = m.replace('\n', '') # list_new_x = list_new_x + [element] # list_new_y = list_new_y + [float(m_new)] # for ii in range(len(list_new_x)): # list_new.append(list_new_x[ii]) # list_new.append(list_new_x[ii] + float(0.01)) # list_new.append(list_new_y[ii]) # QMessageBox.about(self, "teste", str(list_new)) Processing.runAlgorithm("grass7:r.reclass", { 'input': conductivity, 'rules': os.path.join(self.plugin_dir, "SINTACS grafico C.txt"), 'txtrules': '', 'output': outPath, 'GRASS_REGION_PARAMETER': None, 'GRASS_REGION_CELLSIZE_PARAMETER': 0, 'GRASS_RASTER_FORMAT_OPT': '', 'GRASS_RASTER_FORMAT_META': ''}) # 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': list_new, 'TOPERATOR': 0, 'NODATAOPT': True, # 'NODATA': 0, # 'OTHEROPT': True, 'OTHERS': 0, 'RESULT': outPath}) # Processing.runAlgorithm("grass7:r.surf.idw", None, cond_reclassify, 12, False, extent, cellSize, outPath) # add result into canvas file_info_norm = QFileInfo(str(outPath + '.sdat')) # QMessageBox.about(self, "teste", str(file_info_norm)) rlayer_new_norm = QgsRasterLayer(outPath + '.sdat', 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 = QFileInfo(outPath) # if file_info.exists(): # layer_name = file_info.baseName() # else: # return False # rlayer_new = QgsRasterLayer(outPath, layer_name) # if rlayer_new.isValid(): # QgsMapLayerRegistry.instance().addMapLayer(rlayer_new) # layer = QgsMapCanvasLayer(rlayer_new) # layerList = [layer] # extent = self.iface.canvas.setExtent(rlayer_new.extent()) # self.iface.canvas.setLayerSet(layerList) # self.iface.canvas.setVisible(True) # return True # else: # return False # QMessageBox.information(self, self.tr( "Finished" ), self.tr( "Hidraulic conductivity completed." ) ) self.buttonBox.button(QDialogButtonBox.Ok).setDefault(True)
def convert(self): gdal.AllRegister() # ------------------------ FIRST METHOD ------------------------------------------------- self.buttonBox.button(QDialogButtonBox.Ok).setDefault(False) if self.inputLayerCombo.currentText() != "": inputLayer = self.inputLayerCombo.currentText() inputMask = self.inputMaskCombo.currentText() # layer information layer = QgsVectorLayer(inputLayer, (QFileInfo(str(inputLayer))).baseName(), "ogr") vectorlayer_vector = layer.dataProvider() layer_mask = QgsVectorLayer(inputMask, (QFileInfo(str(inputMask))).baseName(), "ogr") vectorlayer_mask = layer_mask.dataProvider() # mask extent extent_rect = vectorlayer_mask.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) # attribute Elevation = self.lineAttrib.currentText() # cellsize cellSize = int(self.linePix.value()) outPath = self.inputLayerCombo3.text() # size of atributte table == number of points count = layer.featureCount() # points interpolation idw if self.comboBoxMethod.currentText( ) == "Inverse Distance Weighting": Processing.initialize() # grid directory (qgis2) idw_interpolation = QFileInfo( QgsApplication.qgisUserDatabaseFilePath()).path( ) + "/idw_interpolation" Processing.runAlgorithm("grass:v.surf.idw", None, inputLayer, count, 2.0, Elevation, False, extent, cellSize, -1.0, 0.0001, idw_interpolation) idw_int = idw_interpolation + "." + "tif" int_mask = QFileInfo(QgsApplication.qgisUserDatabaseFilePath() ).path() + "/int_mask" # clip grid(interpolation) with polygon (mask) Processing.runAlgorithm("saga:clipgridwithpolygon", None, idw_int, inputMask, int_mask) int_mask_zone = int_mask + "." + "tif" # indexes for topography 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) # reclassify idw interpolation if self.comboBoxMethod.currentText( ) == "Inverse Distance Weighting": idw_reclassify = QFileInfo( QgsApplication.qgisUserDatabaseFilePath()).path( ) + "/idw_reclassify" Processing.runAlgorithm("saga:reclassifygridvalues", None, int_mask_zone, 2, 0.0, 1.0, 0, 0.0, 1.0, 2.0, 0, intervalos, 0, True, 0.0, True, 0.0, outPath) # add result into canvas file_info = QFileInfo(outPath) if file_info.exists(): layer_name = file_info.baseName() else: return False rlayer_new = QgsRasterLayer(outPath, layer_name) if rlayer_new.isValid(): QgsMapLayerRegistry.instance().addMapLayer(rlayer_new) layer = QgsMapCanvasLayer(rlayer_new) layerList = [layer] extent = self.iface.canvas.setExtent(rlayer_new.extent()) self.iface.canvas.setLayerSet(layerList) self.iface.canvas.setVisible(True) return True else: return False # points interpolation kriging if self.comboBoxMethod.currentText() == "Kriging": Processing.initialize() # grid directory (qgis2) kriging_interpolation = QFileInfo( QgsApplication.qgisUserDatabaseFilePath()).path( ) + "/kriging_interpolation" Processing.runAlgorithm("saga:ordinarykrigingglobal", None, inputLayer, Elevation, True, 0, 1, False, 100, False, 0.0, 10, 1000, 1.0, 0.1, 1.0, 0.5, cellSize, True, extent, kriging_interpolation, None) kriging_int = kriging_interpolation + "." + "tif" int_mask_kriging = QFileInfo( QgsApplication.qgisUserDatabaseFilePath()).path( ) + "/int_mask_kriging" # clip grid(interpolation) with polygon (mask) Processing.runAlgorithm("saga:clipgridwithpolygon", None, kriging_int, inputMask, int_mask_kriging) int_mask_zone_k = int_mask_kriging + "." + "tif" kriging_reclassify = QFileInfo( QgsApplication.qgisUserDatabaseFilePath()).path( ) + "/kriging_reclassify" Processing.runAlgorithm("saga:reclassifygridvalues", None, int_mask_zone_k, 2, 0.0, 1.0, 0, 0.0, 1.0, 2.0, 0, intervalos, 0, True, 0.0, True, 0.0, outPath) # add result into canvas file_info_k = QFileInfo(outPath) if file_info_k.exists(): layer_name_k = file_info_k.baseName() else: return False rlayer_new_k = QgsRasterLayer(outPath, layer_name_k) if rlayer_new_k.isValid(): QgsMapLayerRegistry.instance().addMapLayer(rlayer_new_k) layer_k = QgsMapCanvasLayer(rlayer_new_k) layerList_k = [layer_k] extent_k = self.iface.canvas.setExtent( rlayer_new_k.extent()) self.iface.canvas.setLayerSet(layerList_k) self.iface.canvas.setVisible(True) return True else: return False # points interpolation cubic spline if self.comboBoxMethod.currentText( ) == "Cubic spline approximation (SAGA)": Processing.initialize() # grid directory (qgis2) cubicSpline_interpolation = QFileInfo( QgsApplication.qgisUserDatabaseFilePath()).path( ) + "/cubicSpline_interpolation" Processing.runAlgorithm("saga:cubicsplineapproximation", None, inputLayer, Elevation, 0, 3, count, 5, 140.0, extent, cellSize, cubicSpline_interpolation) cubicSpline_int = cubicSpline_interpolation + "." + "tif" int_mask_cubicSpline = QFileInfo( QgsApplication.qgisUserDatabaseFilePath()).path( ) + "/int_mask_cubicSpline" # clip grid(interpolation) with polygon (mask) Processing.runAlgorithm("saga:clipgridwithpolygon", None, cubicSpline_int, inputMask, int_mask_cubicSpline) int_mask_zone_cs = int_mask_cubicSpline + "." + "tif" cubicSpline_reclassify = QFileInfo( QgsApplication.qgisUserDatabaseFilePath()).path( ) + "/cubicSpline_reclassify" Processing.runAlgorithm("saga:reclassifygridvalues", None, int_mask_zone_cs, 2, 0.0, 1.0, 0, 0.0, 1.0, 2.0, 0, intervalos, 0, True, 0.0, True, 0.0, outPath) # add result into canvas file_info_cs = QFileInfo(outPath) if file_info_cs.exists(): layer_name_cs = file_info_cs.baseName() else: return False rlayer_new_cs = QgsRasterLayer(outPath, layer_name_cs) if rlayer_new_cs.isValid(): QgsMapLayerRegistry.instance().addMapLayer(rlayer_new_cs) layer_cs = QgsMapCanvasLayer(rlayer_new_cs) layerList_cs = [layer_cs] extent_cs = self.iface.canvas.setExtent( rlayer_new_cs.extent()) self.iface.canvas.setLayerSet(layerList_cs) self.iface.canvas.setVisible(True) return True else: return False if self.comboBoxMethod.currentText( ) == "Spatial approximation using spline with tension (GRASS)": Processing.initialize() # grid directory (qgis2) rst_interpolation = QFileInfo( QgsApplication.qgisUserDatabaseFilePath()).path( ) + "/rst_interpolation" Processing.runAlgorithm("grass:v.surf.rst", None, inputLayer, "", None, Elevation, 40, 40, 300, 0.001, 2.5, 1, 0, 0, False, False, extent, cellSize, -1, 0.0001, rst_interpolation, None, None, None, None, None) rst_int = rst_interpolation + "." + "tif" int_mask_rst = QFileInfo( QgsApplication.qgisUserDatabaseFilePath()).path( ) + "/int_mask_rst" # clip grid(interpolation) with polygon (mask) Processing.runAlgorithm("saga:clipgridwithpolygon", None, rst_int, inputMask, int_mask_rst) int_mask_zone_rst = int_mask_rst + "." + "tif" rst_reclassify = QFileInfo( QgsApplication.qgisUserDatabaseFilePath()).path( ) + "/rst_reclassify" Processing.runAlgorithm("saga:reclassifygridvalues", None, int_mask_zone_rst, 2, 0.0, 1.0, 0, 0.0, 1.0, 2.0, 0, intervalos, 0, True, 0.0, True, 0.0, outPath) # add result into canvas file_info_rst = QFileInfo(outPath) if file_info_rst.exists(): layer_name_rst = file_info_rst.baseName() else: return False rlayer_new_rst = QgsRasterLayer(outPath, layer_name_rst) if rlayer_new_rst.isValid(): QgsMapLayerRegistry.instance().addMapLayer(rlayer_new_rst) layer_rst = QgsMapCanvasLayer(rlayer_new_rst) layerList_rst = [layer_rst] extent_rst = self.iface.canvas.setExtent( rlayer_new_rst.extent()) self.iface.canvas.setLayerSet(layerList_rst) self.iface.canvas.setVisible(True) return True else: return False # ----------------------- SECOND RASTER ---------------------------------------------------------------------------------------- if self.inputLayerCombo_mdt != "": outPath2 = self.inputLayerCombo3.text() # read raster inputRaster = self.inputLayerCombo_mdt.currentText() layer_raster = QgsRasterLayer(inputRaster, inputRaster, "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() # QMessageBox.about(self, "teste", str(inputRaster)) # QMessageBox.about(self, "teste", str(extent_raster_str)) # QMessageBox.about(self, "teste", str(cellSize)) # read maximum depth max_depth = self.line_max.value() # read distance distance = self.line_distance.value() # minimum size size = self.line_size.value() Processing.initialize() # grid directory (qgis2) # generate stream segments stream = QFileInfo( QgsApplication.qgisUserDatabaseFilePath()).path() + "/stream" #QMessageBox.about(self, "teste", str(stream)) Processing.runAlgorithm( "grass7:r.watershed", { 'elevation': inputRaster, 'depression': None, 'flow': None, 'disturbed_land': None, 'blocking': None, 'threshold': 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" Processing.runAlgorithm( "gdal:rastercalculator", { 'INPUT_A': stream, '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>1", 'NO_DATA': None, 'RTYPE': 5, 'EXTRA': '', 'OPTIONS': '', 'OUTPUT': stream_ones }) # raster distance raster_distance = QFileInfo( QgsApplication.qgisUserDatabaseFilePath()).path( ) + "/raster_distance.tif" # Processing.runAlgorithm("saga:proximitygrid", None, str(stream_ones_str), 3, str(raster_distance), None, None) Processing.runAlgorithm( "gdal:proximity", { 'INPUT': str(stream_ones), 'BAND': 1, 'VALUES': '1', 'UNITS': 0, 'MAX_DISTANCE': 0, 'REPLACE': 0, 'NODATA': 0, 'OPTIONS': '', 'DATA_TYPE': 5, 'OUTPUT': str(raster_distance) }) # condition distance >= 200, always maximum depth meters dist_major_200 = QFileInfo(QgsApplication.qgisUserDatabaseFilePath( )).path() + "/dist_major_200" Processing.runAlgorithm( "gdal:rastercalculator", { 'INPUT_A': raster_distance, '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(distance), 'NO_DATA': None, 'RTYPE': 5, 'EXTRA': '', 'OPTIONS': '', 'OUTPUT': dist_major_200 }) dist_multiplication = QFileInfo( QgsApplication.qgisUserDatabaseFilePath()).path( ) + "/dist_multiplication" Processing.runAlgorithm( "gdal:rastercalculator", { 'INPUT_A': dist_major_200, '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(max_depth), 'NO_DATA': None, 'RTYPE': 5, 'EXTRA': '', 'OPTIONS': '', 'OUTPUT': dist_multiplication }) # condition distance < 200, inteprolation between 0 and maximum depth dist_minor_200 = QFileInfo(QgsApplication.qgisUserDatabaseFilePath( )).path() + "/dist_minor_200" Processing.runAlgorithm( "gdal:rastercalculator", { 'INPUT_A': raster_distance, '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(distance), 'NO_DATA': None, 'RTYPE': 5, 'EXTRA': '', 'OPTIONS': '', 'OUTPUT': dist_minor_200 }) # multiplication by the raster distance dist_multiplication_dist = QFileInfo( QgsApplication.qgisUserDatabaseFilePath()).path( ) + "/dist_multiplication_dist" Processing.runAlgorithm( "gdal:rastercalculator", { 'INPUT_A': dist_minor_200, 'BAND_A': 1, 'INPUT_B': raster_distance, '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': dist_multiplication_dist }) # interpolation between 0 and distance interpolation_dist = QFileInfo( QgsApplication.qgisUserDatabaseFilePath()).path( ) + "/interpolation_dist" Processing.runAlgorithm( "gdal:rastercalculator", { 'INPUT_A': dist_multiplication_dist, '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(max_depth) + "/" + str(distance), 'NO_DATA': None, 'RTYPE': 5, 'EXTRA': '', 'OPTIONS': '', 'OUTPUT': interpolation_dist }) # depth surface = sum of two conditions depth_surface = QFileInfo(QgsApplication.qgisUserDatabaseFilePath( )).path() + "/depth_surface" Processing.runAlgorithm( "gdal:rastercalculator", { 'INPUT_A': dist_multiplication, 'BAND_A': 1, 'INPUT_B': interpolation_dist, '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': depth_surface }) # list_new = [] # list_new_x = [] # list_new_y = [] # #QMessageBox.about(self, 'teste', str(self.plugin_dir)) # #FILE = os.path.join(self.plugin_dir, "//SINTACS grafico D.txt") # with open(os.path.join(self.plugin_dir, "SINTACS grafico D.txt"), 'r') as f: # d = {line.split('\t')[0]: line.split('\t')[1] for line in f} # #QMessageBox.about(self, "teste", str(d)) # # read raster values # raster = gdal.Open(str(depth_surface)) # data_mdt = raster.ReadAsArray() # values_raster = numpy.unique(data_mdt) # # QMessageBox.about(self, 'teste', values_raster) # for element in values_raster: # # get the key of a certain value # target = element # # key, value = min(d.items(), key=lambda kv: abs(float(kv[1]) - target)) # m = d.get(target, d[min(d.keys(), key=lambda k: abs(float(k) - target))]) # # remove \n from list # m_new = m.replace('\n', '') # list_new_x = list_new_x + [element] # list_new_y = list_new_y + [float(m_new)] # QMessageBox.about(self, "teste", str(list_new_x)) # QMessageBox.about(self, "teste", str(list_new_y)) # for ii in range(len(list_new_x)): # list_new.append(list_new_x[ii]) # list_new.append(list_new_x[ii] + float(0.01)) # list_new.append(list_new_y[ii]) # # QMessageBox.about(self, "teste", str(list_new)) # # Processing.runAlgorithm("saga:reclassifyvaluessimple", # {'GRID_IN': depth_surface, 'METHOD': 0, 'LOOKUP': list_new, 'GRID_OUT': outPath2}) Processing.runAlgorithm( "grass7:r.reclass", { 'input': depth_surface, 'rules': os.path.join(self.plugin_dir, "SINTACS grafico D - Copy.txt"), 'txtrules': '', 'output': outPath2, 'GRASS_REGION_PARAMETER': None, 'GRASS_REGION_CELLSIZE_PARAMETER': 0, 'GRASS_RASTER_FORMAT_OPT': '', 'GRASS_RASTER_FORMAT_META': '' }) # add result into canvas file_info_norm = QFileInfo(str(outPath2 + '.sdat')) # QMessageBox.about(self, "teste", str(file_info_norm)) rlayer_new_norm = QgsRasterLayer(outPath2 + '.sdat', 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]) QMessageBox.information(self, self.tr("Finished"), self.tr("Depth completed.")) self.buttonBox.button(QDialogButtonBox.Ok).setDefault(True)
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 convert(self): self.buttonBox.button(QDialogButtonBox.Ok).setDefault(False) inputLayer = self.inputLayerCombo.currentText() inputLayer2 = self.inputLayerCombo2.currentText() gdal.AllRegister() # sum of the raster = SI # D gdalRaster = gdal.Open(str(inputLayer)) # # multiply by weight # depth_weight = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/depth_weight" x = gdalRaster.RasterXSize y = gdalRaster.RasterYSize geo = gdalRaster.GetGeoTransform() # # pixel size pixelSize = geo[1] # 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) outPath = self.inputLayerCombo3.text() Processing.initialize() normalize1 = QFileInfo( QgsApplication.qgisUserDatabaseFilePath()).path() + "/normalize1" Processing.runAlgorithm( "grass7:r.rescale", { 'input': inputLayer, 'from': [self.linePixmin.value(), self.linePixmax.value()], 'to': [0, 100], 'output': normalize1, 'GRASS_REGION_PARAMETER': str(extent) + '[EPSG:3763]', 'GRASS_REGION_CELLSIZE_PARAMETER': pixelSize, 'GRASS_RASTER_FORMAT_OPT': '', 'GRASS_RASTER_FORMAT_META': '' }) normalize2 = QFileInfo( QgsApplication.qgisUserDatabaseFilePath()).path() + "/normalize2" Processing.runAlgorithm( "grass7:r.rescale", { 'input': inputLayer2, 'from': [self.linePixmin2.value(), self.linePixmax2.value()], 'to': [0, 100], 'output': normalize2, 'GRASS_REGION_PARAMETER': str(extent) + '[EPSG:3763]', 'GRASS_REGION_CELLSIZE_PARAMETER': pixelSize, 'GRASS_RASTER_FORMAT_OPT': '', 'GRASS_RASTER_FORMAT_META': '' }) # Processing.runAlgorithm("gdal:rastercalculator", {'INPUT_A': normalize1 + '.sdat', 'BAND_A': 1, # 'INPUT_B': normalize2 + '.sdat', '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': 6, 'OPTIONS': '', # 'OUTPUT': outPath}) Processing.runAlgorithm( "grass7:r.mapcalc.simple", { 'a': normalize1 + '.sdat', 'b': normalize2 + '.sdat', 'c': normalize2 + '.sdat', 'd': normalize1 + '.sdat', 'e': normalize2 + '.sdat', 'f': normalize1 + '.sdat', 'expression': 'A-B', 'output': outPath, 'GRASS_REGION_PARAMETER': extent + '[EPSG:3763]', 'GRASS_REGION_CELLSIZE_PARAMETER': 30, 'GRASS_RASTER_FORMAT_OPT': '', 'GRASS_RASTER_FORMAT_META': '' }) # add result into canvas # add result into canvas file_info_norm = QFileInfo(str(outPath)) # QMessageBox.about(self, "teste", str(file_info_norm)) rlayer_new_norm = QgsRasterLayer(outPath, 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]) QMessageBox.information(self, self.tr("Finished"), self.tr("Analysis completed.")) self.buttonBox.button(QDialogButtonBox.Ok).setDefault(True)
def run(algOrName, *args, **kwargs): """Executes given algorithm and returns its outputs as dictionary object. """ return Processing.runAlgorithm(algOrName, None, *args, **kwargs)
def runandload(name, *args, **kwargs): return Processing.runAlgorithm(name, handleAlgorithmResults, *args, **kwargs)
def convert(self): gdal.AllRegister() # ------------------------ FIRST METHOD ------------------------------------------------- self.buttonBox.button(QDialogButtonBox.Ok).setDefault(False) if self.inputLayerCombo.currentText() != "": inputLayer = self.inputLayerCombo.currentText() inputMask = self.inputMaskCombo.currentText() # layer information layer = QgsVectorLayer( unicode(inputLayer).encode('utf8'), inputLayer, "ogr") vectorlayer_vector = layer.dataProvider() layer_mask = QgsVectorLayer( unicode(inputMask).encode('utf8'), inputMask, "ogr") vectorlayer_mask = layer_mask.dataProvider() # mask extent extent_rect = vectorlayer_mask.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) # attribute Elevation = self.lineAttrib.currentText() # cellsize cellSize = int(self.linePix.value()) outPath = self.inputLayerCombo3.text() # size of atributte table == number of points count = layer.featureCount() # points interpolation idw if self.comboBoxMethod.currentText( ) == "Inverse Distance Weighting": Processing.initialize() # grid directory (qgis2) idw_interpolation = QFileInfo( QgsApplication.qgisUserDbFilePath()).path( ) + "/idw_interpolation" Processing.runAlgorithm("grass:v.surf.idw", None, inputLayer, count, 2.0, Elevation, False, extent, cellSize, -1.0, 0.0001, idw_interpolation) idw_int = idw_interpolation + "." + "tif" int_mask = QFileInfo( QgsApplication.qgisUserDbFilePath()).path() + "/int_mask" # clip grid(interpolation) with polygon (mask) Processing.runAlgorithm("saga:clipgridwithpolygon", None, idw_int, inputMask, int_mask) int_mask_zone = int_mask + "." + "tif" # indexes for topography 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) # reclassify idw interpolation if self.comboBoxMethod.currentText( ) == "Inverse Distance Weighting": idw_reclassify = QFileInfo(QgsApplication.qgisUserDbFilePath() ).path() + "/idw_reclassify" Processing.runAlgorithm("saga:reclassifygridvalues", None, int_mask_zone, 2, 0.0, 1.0, 0, 0.0, 1.0, 2.0, 0, intervalos, 0, True, 0.0, True, 0.0, outPath) # add result into canvas file_info = QFileInfo(outPath) if file_info.exists(): layer_name = file_info.baseName() else: return False rlayer_new = QgsRasterLayer(outPath, layer_name) if rlayer_new.isValid(): QgsMapLayerRegistry.instance().addMapLayer(rlayer_new) layer = QgsMapCanvasLayer(rlayer_new) layerList = [layer] extent = self.iface.canvas.setExtent(rlayer_new.extent()) self.iface.canvas.setLayerSet(layerList) self.iface.canvas.setVisible(True) return True else: return False # points interpolation kriging if self.comboBoxMethod.currentText() == "Kriging": Processing.initialize() # grid directory (qgis2) kriging_interpolation = QFileInfo( QgsApplication.qgisUserDbFilePath()).path( ) + "/kriging_interpolation" Processing.runAlgorithm("saga:ordinarykrigingglobal", None, inputLayer, Elevation, True, 0, 1, False, 100, False, 0.0, 10, 1000, 1.0, 0.1, 1.0, 0.5, cellSize, True, extent, kriging_interpolation, None) kriging_int = kriging_interpolation + "." + "tif" int_mask_kriging = QFileInfo(QgsApplication.qgisUserDbFilePath( )).path() + "/int_mask_kriging" # clip grid(interpolation) with polygon (mask) Processing.runAlgorithm("saga:clipgridwithpolygon", None, kriging_int, inputMask, int_mask_kriging) int_mask_zone_k = int_mask_kriging + "." + "tif" kriging_reclassify = QFileInfo( QgsApplication.qgisUserDbFilePath()).path( ) + "/kriging_reclassify" Processing.runAlgorithm("saga:reclassifygridvalues", None, int_mask_zone_k, 2, 0.0, 1.0, 0, 0.0, 1.0, 2.0, 0, intervalos, 0, True, 0.0, True, 0.0, outPath) # add result into canvas file_info_k = QFileInfo(outPath) if file_info_k.exists(): layer_name_k = file_info_k.baseName() else: return False rlayer_new_k = QgsRasterLayer(outPath, layer_name_k) if rlayer_new_k.isValid(): QgsMapLayerRegistry.instance().addMapLayer(rlayer_new_k) layer_k = QgsMapCanvasLayer(rlayer_new_k) layerList_k = [layer_k] extent_k = self.iface.canvas.setExtent( rlayer_new_k.extent()) self.iface.canvas.setLayerSet(layerList_k) self.iface.canvas.setVisible(True) return True else: return False # points interpolation cubic spline if self.comboBoxMethod.currentText( ) == "Cubic spline approximation (SAGA)": Processing.initialize() # grid directory (qgis2) cubicSpline_interpolation = QFileInfo( QgsApplication.qgisUserDbFilePath()).path( ) + "/cubicSpline_interpolation" Processing.runAlgorithm("saga:cubicsplineapproximation", None, inputLayer, Elevation, 0, 3, count, 5, 140.0, extent, cellSize, cubicSpline_interpolation) cubicSpline_int = cubicSpline_interpolation + "." + "tif" int_mask_cubicSpline = QFileInfo( QgsApplication.qgisUserDbFilePath()).path( ) + "/int_mask_cubicSpline" # clip grid(interpolation) with polygon (mask) Processing.runAlgorithm("saga:clipgridwithpolygon", None, cubicSpline_int, inputMask, int_mask_cubicSpline) int_mask_zone_cs = int_mask_cubicSpline + "." + "tif" cubicSpline_reclassify = QFileInfo( QgsApplication.qgisUserDbFilePath()).path( ) + "/cubicSpline_reclassify" Processing.runAlgorithm("saga:reclassifygridvalues", None, int_mask_zone_cs, 2, 0.0, 1.0, 0, 0.0, 1.0, 2.0, 0, intervalos, 0, True, 0.0, True, 0.0, outPath) # add result into canvas file_info_cs = QFileInfo(outPath) if file_info_cs.exists(): layer_name_cs = file_info_cs.baseName() else: return False rlayer_new_cs = QgsRasterLayer(outPath, layer_name_cs) if rlayer_new_cs.isValid(): QgsMapLayerRegistry.instance().addMapLayer(rlayer_new_cs) layer_cs = QgsMapCanvasLayer(rlayer_new_cs) layerList_cs = [layer_cs] extent_cs = self.iface.canvas.setExtent( rlayer_new_cs.extent()) self.iface.canvas.setLayerSet(layerList_cs) self.iface.canvas.setVisible(True) return True else: return False if self.comboBoxMethod.currentText( ) == "Spatial approximation using spline with tension (GRASS)": Processing.initialize() # grid directory (qgis2) rst_interpolation = QFileInfo( QgsApplication.qgisUserDbFilePath()).path( ) + "/rst_interpolation" Processing.runAlgorithm("grass:v.surf.rst", None, inputLayer, "", None, Elevation, 40, 40, 300, 0.001, 2.5, 1, 0, 0, False, False, extent, cellSize, -1, 0.0001, rst_interpolation, None, None, None, None, None) rst_int = rst_interpolation + "." + "tif" int_mask_rst = QFileInfo(QgsApplication.qgisUserDbFilePath() ).path() + "/int_mask_rst" # clip grid(interpolation) with polygon (mask) Processing.runAlgorithm("saga:clipgridwithpolygon", None, rst_int, inputMask, int_mask_rst) int_mask_zone_rst = int_mask_rst + "." + "tif" rst_reclassify = QFileInfo(QgsApplication.qgisUserDbFilePath() ).path() + "/rst_reclassify" Processing.runAlgorithm("saga:reclassifygridvalues", None, int_mask_zone_rst, 2, 0.0, 1.0, 0, 0.0, 1.0, 2.0, 0, intervalos, 0, True, 0.0, True, 0.0, outPath) # add result into canvas file_info_rst = QFileInfo(outPath) if file_info_rst.exists(): layer_name_rst = file_info_rst.baseName() else: return False rlayer_new_rst = QgsRasterLayer(outPath, layer_name_rst) if rlayer_new_rst.isValid(): QgsMapLayerRegistry.instance().addMapLayer(rlayer_new_rst) layer_rst = QgsMapCanvasLayer(rlayer_new_rst) layerList_rst = [layer_rst] extent_rst = self.iface.canvas.setExtent( rlayer_new_rst.extent()) self.iface.canvas.setLayerSet(layerList_rst) self.iface.canvas.setVisible(True) return True else: return False # ----------------------- SECOND RASTER ---------------------------------------------------------------------------------------- if self.inputLayerCombo_mdt != "": outPath2 = self.inputLayerCombo3.text() # read raster inputRaster = self.inputLayerCombo_mdt.currentText() layer_raster = QgsRasterLayer(inputRaster, inputRaster, "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() # read maximum depth max_depth = self.line_max.value() # read distance distance = self.line_distance.value() # minimum size size = self.line_size.value() Processing.initialize() # grid directory (qgis2) # generate stream segments stream = QFileInfo( QgsApplication.qgisUserDatabaseFilePath()).path() + "/stream" Processing.runAlgorithm( "grass7:r.watershed", { 'elevation': inputRaster, 'depression': None, 'flow': None, 'disturbed_land': None, 'blocking': None, 'threshold': 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" Processing.runAlgorithm( "gdal:rastercalculator", { 'INPUT_A': stream, '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>1", 'NO_DATA': None, 'RTYPE': 5, 'EXTRA': '', 'OPTIONS': '', 'OUTPUT': stream_ones }) # raster distance raster_distance = QFileInfo( QgsApplication.qgisUserDatabaseFilePath()).path( ) + "/raster_distance.sdat" Processing.runAlgorithm( "gdal:proximity", { 'INPUT': str(stream_ones), 'BAND': 1, 'VALUES': '1', 'UNITS': 0, 'MAX_DISTANCE': 0, 'REPLACE': 0, 'NODATA': 0, 'OPTIONS': '', 'DATA_TYPE': 5, 'OUTPUT': str(raster_distance) }) # condition distance >= 200, always maximum depth meters dist_major_200 = QFileInfo(QgsApplication.qgisUserDatabaseFilePath( )).path() + "/dist_major_200" Processing.runAlgorithm( "gdal:rastercalculator", { 'INPUT_A': raster_distance, '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(distance), 'NO_DATA': None, 'RTYPE': 5, 'EXTRA': '', 'OPTIONS': '', 'OUTPUT': dist_major_200 }) dist_multiplication = QFileInfo( QgsApplication.qgisUserDatabaseFilePath()).path( ) + "/dist_multiplication" Processing.runAlgorithm( "gdal:rastercalculator", { 'INPUT_A': dist_major_200, '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(max_depth), 'NO_DATA': None, 'RTYPE': 5, 'EXTRA': '', 'OPTIONS': '', 'OUTPUT': dist_multiplication }) # condition distance < 200, inteprolation between 0 and maximum depth dist_minor_200 = QFileInfo(QgsApplication.qgisUserDatabaseFilePath( )).path() + "/dist_minor_200" Processing.runAlgorithm( "gdal:rastercalculator", { 'INPUT_A': raster_distance, '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(distance), 'NO_DATA': None, 'RTYPE': 5, 'EXTRA': '', 'OPTIONS': '', 'OUTPUT': dist_minor_200 }) # multiplication by the raster distance dist_multiplication_dist = QFileInfo( QgsApplication.qgisUserDatabaseFilePath()).path( ) + "/dist_multiplication_dist" Processing.runAlgorithm( "gdal:rastercalculator", { 'INPUT_A': dist_minor_200, 'BAND_A': 1, 'INPUT_B': raster_distance, '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': dist_multiplication_dist }) # interpolation between 0 and distance interpolation_dist = QFileInfo( QgsApplication.qgisUserDatabaseFilePath()).path( ) + "/interpolation_dist" Processing.runAlgorithm( "gdal:rastercalculator", { 'INPUT_A': dist_multiplication_dist, '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(max_depth) + "/" + str(distance), 'NO_DATA': None, 'RTYPE': 5, 'EXTRA': '', 'OPTIONS': '', 'OUTPUT': interpolation_dist }) # depth surface = sum of two conditions depth_surface = QFileInfo(QgsApplication.qgisUserDatabaseFilePath( )).path() + "/depth_surface" Processing.runAlgorithm( "gdal:rastercalculator", { 'INPUT_A': dist_multiplication, 'BAND_A': 1, 'INPUT_B': interpolation_dist, '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': depth_surface }) # indexes for topography 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(float, lista)) depth_reclassify = QFileInfo( QgsApplication.qgisUserDatabaseFilePath()).path( ) + "/depth_reclassify.sdat" 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 }) # 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]) # file_info_norm = QFileInfo(outPath2) # if file_info_norm.exists(): # layer_name_norm = file_info_norm.baseName() # else: # return False # rlayer_new_norm = QgsRasterLayer(outPath2, layer_name_norm) # if rlayer_new_norm.isValid(): # QgsMapLayerRegistry.instance().addMapLayer(rlayer_new_norm) # layer_norm = QgsMapCanvasLayer(rlayer_new_norm) # layerList_norm = [layer_norm] # extent_norm = self.iface.canvas.setExtent(rlayer_new_norm.extent()) # self.iface.canvas.setLayerSet(layerList_norm) # self.iface.canvas.setVisible(True) # return True # else: # return False QMessageBox.information(self, self.tr("Finished"), self.tr("Depth completed.")) self.buttonBox.button(QDialogButtonBox.Ok).setDefault(True)
def convert(self): self.buttonBox.button(QDialogButtonBox.Ok).setDefault(False) inputLayer = self.inputLayerCombo.currentText() # layer information 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) # attribute Elevation = self.lineAttrib.currentText() # cellsize cellSize = int(self.linePix.value()) outPath = self.inputLayerCombo3.text() # 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() 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': outPath, '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 }) # add result into canvas # add result into canvas file_info_norm = QFileInfo(str(outPath)) # QMessageBox.about(self, "teste", str(file_info_norm)) rlayer_new_norm = QgsRasterLayer(outPath, 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]) # file_info = QFileInfo(outPath) # if file_info.exists(): # layer_name = file_info.baseName() # else: # return False # rlayer_new = QgsRasterLayer(outPath, layer_name) # if rlayer_new.isValid(): # QgsMapLayerRegistry.instance().addMapLayer(rlayer_new) # layer = QgsMapCanvasLayer(rlayer_new) # layerList = [layer] # extent = self.iface.canvas.setExtent(rlayer_new.extent()) # self.iface.canvas.setLayerSet(layerList) # self.iface.canvas.setVisible(True) # return True # else: # return False QMessageBox.information(self, self.tr("Finished"), self.tr("Aquifer media completed.")) self.buttonBox.button(QDialogButtonBox.Ok).setDefault(True)
def convert(self): self.buttonBox.button(QDialogButtonBox.Ok).setDefault(False) if self.inputLayerCombo.currentText() != "": inputLayer = self.inputLayerCombo.currentText() inputLayer1 = self.inputLayerCombo1.currentText() inputLayer2 = self.inputLayerCombo2.currentText() # layer information layer = QgsVectorLayer( unicode(inputLayer).encode('utf8'), inputLayer, "ogr") layer1 = QgsVectorLayer( unicode(inputLayer1).encode('utf8'), inputLayer1, "ogr") layer2 = QgsVectorLayer( unicode(inputLayer2).encode('utf8'), inputLayer2, "ogr") vectorlayer_vector = layer.dataProvider() vectorlayer_vector1 = layer1.dataProvider() vectorlayer_vector2 = layer2.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) # attribute Elevation = self.lineAttrib.currentText() Attrib1 = self.lineAttribRunoff.currentText() Attrib2 = self.lineAttribEvap.currentText() # cellsize cellSize = int(self.linePix.value()) outPath = self.inputLayerCombo3.text() Processing.initialize() # grid directory (qgis2) filedir = QFileInfo( QgsApplication.qgisUserDatabaseFilePath()).path() + "/pret" filedir1 = QFileInfo( QgsApplication.qgisUserDatabaseFilePath()).path() + "/runoff" filedir2 = QFileInfo( QgsApplication.qgisUserDatabaseFilePath()).path() + "/evapo" 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': filedir, '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 }) # map subtraction in case of having the three shapefiles if self.inputLayerCombo1.currentText() != "": Processing.runAlgorithm( "grass7:v.to.rast", { 'input': inputLayer1, 'type': [0, 1, 3], 'where': '', 'use': 0, 'attribute_column': Attrib1, 'rgb_column': None, 'label_column': None, 'value': None, 'memory': 300, 'output': filedir1, '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 }) Processing.runAlgorithm( "grass7:v.to.rast", { 'input': inputLayer2, 'type': [0, 1, 3], 'where': '', 'use': 0, 'attribute_column': Attrib2, 'rgb_column': None, 'label_column': None, 'value': None, 'memory': 300, 'output': filedir2, '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 }) Infiltrazione = QFileInfo( QgsApplication.qgisUserDatabaseFilePath()).path( ) + "/Infiltrazione" gdalRaster_prec = gdal.Open(str(out)) x_prec = gdalRaster_prec.RasterXSize y_prec = gdalRaster_prec.RasterYSize geo_prec = gdalRaster_prec.GetGeoTransform() band_prec = gdalRaster_prec.GetRasterBand(1) data_prec = band_prec.ReadAsArray(0, 0, x_prec, y_prec) gdalRaster_runoff = gdal.Open(str(outRunoff)) x_runoff = gdalRaster_runoff.RasterXSize y_runoff = gdalRaster_runoff.RasterYSize geo_runoff = gdalRaster_runoff.GetGeoTransform() band_runoff = gdalRaster_runoff.GetRasterBand(1) data_runoff = band_runoff.ReadAsArray(0, 0, x_runoff, y_runoff) gdalRaster_evapo = gdal.Open(str(outEvap)) x_evapo = gdalRaster_evapo.RasterXSize y_evapo = gdalRaster_evapo.RasterYSize geo_evapo = gdalRaster_evapo.GetGeoTransform() band_evapo = gdalRaster_evapo.GetRasterBand(1) data_evapo = band_evapo.ReadAsArray(0, 0, x_evapo, y_evapo) sub1 = numpy.subtract(data_prec, data_runoff) sub2 = numpy.subtract(sub1, data_evapo) # Create an output imagedriver with the substraction result driver_out = gdal.GetDriverByName("GTiff") outData_Infiltrazione = driver_out.Create( str(Infiltrazione), x_prec, y_prec, 1, gdal.GDT_Float32) outData_Infiltrazione.GetRasterBand(1).WriteArray(sub2) outData_Infiltrazione.SetGeoTransform(geo_prec) outData_Infiltrazione = None # multiplication of precipitation by 0.1, in case of having only the precipitation shapefile if self.inputLayerCombo1.currentText() == "": userReclassify = QFileInfo( QgsApplication.qgisUserDatabaseFilePath()).path( ) + "/reclassify" # Infiltrazione = precipitation * 0.1 (10% of precipitation) gdalRaster = gdal.Open(str(out)) x = gdalRaster.RasterXSize y = gdalRaster.RasterYSize geo = gdalRaster.GetGeoTransform() band = gdalRaster.GetRasterBand(1) data = band.ReadAsArray(0, 0, x, y) mul = numpy.multiply(data, 0.1) # Create an output imagedriver with the multiplication result driver = gdal.GetDriverByName("GTiff") outData = driver.Create(str(userReclassify), x, y, 1, gdal.GDT_Float32) outData.GetRasterBand(1).WriteArray(mul) outData.SetGeoTransform(geo) outData = None # 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) # reclassification of Infiltrazione values in case of having only the precipitation shapefile if self.inputLayerCombo1.currentText() == "": Infiltrazione_prec = QFileInfo( QgsApplication.qgisUserDatabaseFilePath()).path( ) + "/Infiltrazione_prec" Processing.runAlgorithm("saga:reclassifygridvalues", None, userReclassify, 2, 0.0, 1.0, 0, 0.0, 1.0, 2.0, 0, intervalos, 0, True, 0.0, True, 0.0, outPath) # add result into canvas file_info_prec = QFileInfo(outPath) if file_info_prec.exists(): layer_name_prec = file_info_prec.baseName() else: return False rlayer_new_prec = QgsRasterLayer(outPath, layer_name_prec) if rlayer_new_prec.isValid(): QgsMapLayerRegistry.instance().addMapLayer(rlayer_new_prec) layer_prec = QgsMapCanvasLayer(rlayer_new_prec) layerList_prec = [layer_prec] extent_prec = self.iface.canvas.setExtent( rlayer_new_prec.extent()) self.iface.canvas.setLayerSet(layerList_prec) self.iface.canvas.setVisible(True) return True else: return False QMessageBox.information( self, self.tr("Finished"), self.tr("Net Infiltrazione completed.")) # reclassification of Infiltrazione values in case of having the three shapefiles if self.inputLayerCombo1.currentText() != "": Infiltrazione_prec_run_evap = QFileInfo( QgsApplication.qgisUserDatabaseFilePath()).path( ) + "/Infiltrazione_prec_run_evap" Processing.runAlgorithm("saga:reclassifygridvalues", None, Infiltrazione, 2, 0.0, 1.0, 0, 0.0, 1.0, 2.0, 0, intervalos, 0, True, 0.0, True, 0.0, outPath) # add result into canvas file_info_prec_runoff_evapo = QFileInfo(outPath) if file_info_prec_runoff_evapo.exists(): layer_name_prec_runoff_evapo = file_info_prec_runoff_evapo.baseName( ) else: return False rlayer_new_prec_runoff_evapo = QgsRasterLayer( outPath, layer_name_prec_runoff_evapo) if rlayer_new_prec_runoff_evapo.isValid(): QgsMapLayerRegistry.instance().addMapLayer( rlayer_new_prec_runoff_evapo) layer_prec_runoff_evapo = QgsMapCanvasLayer( rlayer_new_prec_runoff_evapo) layerList_prec_runoff_evapo = [layer_prec_runoff_evapo] extent_prec_runoff_evapo = self.iface.canvas.setExtent( rlayer_new_prec_runoff_evapo.extent()) self.iface.canvas.setLayerSet(layerList_prec_runoff_evapo) self.iface.canvas.setVisible(True) return True else: return False QMessageBox.information( self, self.tr("Finished"), self.tr("Net Infiltrazione completed.")) if self.inputLayerCombo4.currentText() != "": gdal.AllRegister() # read mdt data outPath2 = self.inputLayerCombo3.text() inputRaster = self.inputLayerCombo4.currentText() 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) # Infiltrazione = numpy.multiply(precipitation, 0.15) Infiltrazione_without_rec = QFileInfo( QgsApplication.qgisUserDatabaseFilePath()).path( ) + "/Infiltrazione_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': Infiltrazione_without_rec }) # Create an output imagedriver with the multiplication result # driver2 = gdal.GetDriverByName( "GTiff" ) # outData2 = driver2.Create(str(Infiltrazione_without_rec+'.'+'tif'), x,y,1, gdal.GDT_Float32) # outData2.GetRasterBand(1).WriteArray(Infiltrazione) # outData2.SetGeoTransform(geo) # outData2 = None # list_new = [] # list_new_x = [] # list_new_y = [] # # QMessageBox.about(self, 'teste', str(self.plugin_dir)) # # FILE = os.path.join(self.plugin_dir, "//SINTACS grafico D.txt") # with open(os.path.join(self.plugin_dir, "SINTACS grafico I.txt"), 'r') as f: # d = {line.split('\t')[0]: line.split('\t')[1] for line in f} # QMessageBox.about(self, "teste", str(d)) # # read raster values # raster = gdal.Open(str(Infiltrazione_without_rec)) # data_mdt = raster.ReadAsArray() # values_raster = numpy.unique(data_mdt) # QMessageBox.about(self, 'teste', str(values_raster)) # for element in values_raster: # # get the key of a certain value # target = element # # key, value = min(d.items(), key=lambda kv: abs(float(kv[1]) - target)) # m = d.get(target, d[min(d.keys(), key=lambda k: abs(float(k) - target))]) # # remove \n from list # m_new = m.replace('\n', '') # list_new_x = list_new_x + [element] # list_new_y = list_new_y + [float(m_new)] # # Set the path for the output file # output_file = open('C:\Artigos\DRASTIC_melhoria/file.txt', 'w') # for ii in range(len(list_new_x)): # list_new.append(list_new_x[ii]) # list_new.append(list_new_x[ii] + float(0.01)) # list_new.append(list_new_y[ii]) # # Get the features and properly rewrite them as lines # for feat in list_new: # output_file.write(str(feat) + '/t') # output_file.close() # 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(list_new)) Processing.initialize() # Processing.runAlgorithm("native:reclassifybytable", { # 'INPUT_RASTER': Infiltrazione_without_rec, # 'RASTER_BAND': 1, 'TABLE': list_new, # 'NO_DATA': 0, 'RANGE_BOUNDARIES': 0, 'NODATA_FOR_MISSING': False, 'DATA_TYPE': 5, # 'OUTPUT': outPath2}) Processing.runAlgorithm( "grass7:r.reclass", { 'input': Infiltrazione_without_rec, 'rules': os.path.join(self.plugin_dir, "SINTACS grafico I - Copy.txt"), 'txtrules': '', 'output': outPath2, 'GRASS_REGION_PARAMETER': None, 'GRASS_REGION_CELLSIZE_PARAMETER': 0, 'GRASS_RASTER_FORMAT_OPT': '', 'GRASS_RASTER_FORMAT_META': '' }) # 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_Infiltrazione = QFileInfo(outPath2) # if file_info_Infiltrazione.exists(): # layer_name_Infiltrazione = file_info_Infiltrazione.baseName() # else: # return False # rlayer_new_Infiltrazione = QgsRasterLayer(outPath2, layer_name_Infiltrazione) # if rlayer_new_Infiltrazione.isValid(): # QgsMapLayerRegistry.instance().addMapLayer(rlayer_new_Infiltrazione) # layer_prec_Infiltrazione = QgsMapCanvasLayer(rlayer_new_Infiltrazione) # layerList_Infiltrazione = [layer_prec_Infiltrazione] # extent_Infiltrazione = self.iface.canvas.setExtent(rlayer_new_Infiltrazione.extent()) # self.iface.canvas.setLayerSet(layerList_Infiltrazione) # self.iface.canvas.setVisible(True) # return True # else: # return False QMessageBox.information(self, self.tr("Finished"), self.tr("Net Infiltrazione completed.")) self.buttonBox.button(QDialogButtonBox.Ok).setDefault(True)
def execute(self): # create a project p = QgsProject.instance() mlr = QgsMapLayerRegistry.instance() # Run alg with params # TODO: get args args = {} # get vector and raster inputs inputCrs = None for k in self._inputs: v = getattr(self, k) parm = self.alg.getParameterFromName( v.identifier ) # vector layers if parm.__class__.__name__ == 'ParameterVector': values = [] if vectorLayers and ParameterVector.VECTOR_TYPE_ANY in parm.shapetype : values = [l for l in vectorLayers] elif vectorLayers : if ParameterVector.VECTOR_TYPE_POINT in parm.shapetype : values += [l for l in vectorLayers if l['geometry'] == 'Point'] if ParameterVector.VECTOR_TYPE_LINE in parm.shapetype : values += [l for l in vectorLayers if l['geometry'] == 'Line'] if ParameterVector.VECTOR_TYPE_POLYGON in parm.shapetype : values += [l for l in vectorLayers if l['geometry'] == 'Polygon'] if values : layerName = v.getValue() values = [l for l in values if l['name'] == layerName] l = values[0] layer = QgsVectorLayer( l['datasource'], l['name'], l['provider'] ) crs = l['crs'] qgsCrs = None if str(crs).startswith('USER:'******'proj4']) ) else : qgsCrs = QgsCoordinateReferenceSystem( str(crs) ) if qgsCrs : layer.setCrs( qgsCrs ) mlr.addMapLayer( layer, False ) args[v.identifier] = layer inputCrs = layer.crs() else : fileName = v.getValue() fileInfo = QFileInfo( fileName ) # move fileName to fileName.gml for ogr with open( fileName, 'r' ) as f : o = open( fileName+'.gml', 'w' ) o.write( f.read() ) o.close() #import shutil #shutil.copy2(fileName+'.gml', '/tmp/test.gml' ) # get layer layer = QgsVectorLayer( fileName+'.gml', fileInfo.baseName(), 'ogr' ) pr = layer.dataProvider() e = layer.extent() mlr.addMapLayer( layer, False ) args[v.identifier] = layer inputCrs = layer.crs() # raster layers elif parm.__class__.__name__ == 'ParameterRaster': if rasterLayers : layerName = v.getValue() values = [l for l in rasterLayers if l['name'] == layerName] l = values[0] layer = QgsRasterLayer( l['datasource'], l['name'], l['provider'] ) crs = l['crs'] qgsCrs = None if str(crs).startswith('USER:'******'proj4']) ) else : qgsCrs = QgsCoordinateReferenceSystem( str(crs) ) if qgsCrs : layer.setCrs( qgsCrs ) mlr.addMapLayer( layer, False ) args[v.identifier] = layer inputCrs = layer.crs() else : fileName = v.getValue() fileInfo = QFileInfo( fileName ) layer = QgsRasterLayer( fileName, fileInfo.baseName(), 'gdal' ) mlr.addMapLayer( layer, False ) args[v.identifier] = layer inputCrs = layer.crs() elif parm.__class__.__name__ == 'ParameterExtent': coords = v.getValue().coords args[v.identifier] = str(coords[0][0])+','+str(coords[1][0])+','+str(coords[0][1])+','+str(coords[1][1]) else: args[v.identifier] = v.getValue() # if extent in inputs, transform it to the alg CRS if inputCrs: for k in self._inputs: v = getattr(self, k) parm = self.alg.getParameterFromName( v.identifier ) if parm.__class__.__name__ == 'ParameterExtent': coords = v.getValue().coords coordCrs = None if v.getValue().crs: coordCrs = QgsCoordinateReferenceSystem( str( v.getValue().crs ) ) elif crss: coordCrs = QgsCoordinateReferenceSystem( str( crss[0] ) ) else: coordCrs = QgsCoordinateReferenceSystem( 'EPSG:4326' ) if coordCrs: coordExtent = QgsRectangle( coords[0][0], coords[0][1], coords[1][0], coords[1][1] ) xform = QgsCoordinateTransform( coordCrs, inputCrs ) coordExtent = xform.transformBoundingBox( coordExtent ) args[v.identifier] = str(coordExtent.xMinimum())+','+str(coordExtent.xMaximum())+','+str(coordExtent.yMinimum())+','+str(coordExtent.yMaximum()) # Adds None for output parameter(s) for k in self._outputs: v = getattr(self, k) args[v.identifier] = None if not len( self.alg.parameters ): self.alg.defineCharacteristics() tAlg = Processing.runAlgorithm(self.alg, None, args) # if runalg failed return exception message if not tAlg: return 'Error in processing' # clear map layer registry mlr.removeAllMapLayers() # get result result = tAlg.getOutputValuesAsDictionary() for k in self._outputs: v = getattr(self, k) parm = self.alg.getOutputFromName( v.identifier ) # Output Vector if parm.__class__.__name__ == 'OutputVector': outputName = result.get(v.identifier, None) if not outputName : return 'No output file' # get output file info outputInfo = QFileInfo( outputName ) # get the output QGIS vector layer outputLayer = QgsVectorLayer( outputName, outputInfo.baseName(), 'ogr' ) # Update input CRS if not inputCrs.authid(): inputCrs.saveAsUserCRS(''); crs = QgsCoordinateReferenceSystem() crs.createFromProj4(inputCrs.toProj4()) inputCrs = crs # Update CRS if not outputLayer.dataProvider().crs().authid(): outputLayer.setCrs( inputCrs ) # define destination CRS destCrs = None if outputLayer.crs().authid().startswith( 'USER:'******'EPSG:4326' ) v.projection = 'EPSG:4326' # define the file extension outputExt = 'gml' if v.format['mimetype'] == 'application/json': outputExt = 'geojson' elif v.format['mimetype'] == 'application/x-zipped-shp': outputExt = 'shp' elif v.format['mimetype'] == 'application/x-zipped-tab': outputExt = 'tab' # define the output file path outputFile = os.path.join( outputInfo.absolutePath(), outputInfo.baseName()+'.'+outputExt ) # write the output GML file if v.format['mimetype'] == 'application/x-zipped-shp': if destCrs : outputFile = os.path.join( outputInfo.absolutePath(), outputInfo.baseName()+'_'+str(destCrs.srsid())+'.'+outputExt ) outputInfo = QFileInfo( outputFile ) error = QgsVectorFileWriter.writeAsVectorFormat( outputLayer, outputFile, 'utf-8', destCrs, 'ESRI Shapefile', False, None ) # compress files import zipfile try: import zlib compression = zipfile.ZIP_DEFLATED except: compression = zipfile.ZIP_STORED zFile = os.path.join( outputInfo.absolutePath(), outputInfo.baseName()+'.zip' ) with zipfile.ZipFile(zFile, 'w') as zf: zf.write(os.path.join( outputInfo.absolutePath(), outputInfo.baseName()+'.shp' ), compress_type=compression, arcname=outputInfo.baseName()+'.shp') zf.write(os.path.join( outputInfo.absolutePath(), outputInfo.baseName()+'.shx' ), compress_type=compression, arcname=outputInfo.baseName()+'.shx') zf.write(os.path.join( outputInfo.absolutePath(), outputInfo.baseName()+'.dbf' ), compress_type=compression, arcname=outputInfo.baseName()+'.dbf') if os.path.exists( os.path.join( outputInfo.absolutePath(), outputInfo.baseName()+'.prj' ) ): zf.write(os.path.join( outputInfo.absolutePath(), outputInfo.baseName()+'.prj' ), compress_type=compression, arcname=outputInfo.baseName()+'.prj') zf.close() outputFile = zFile elif v.format['mimetype'] == 'application/x-zipped-tab': error = QgsVectorFileWriter.writeAsVectorFormat( outputLayer, outputFile, 'utf-8', destCrs, 'Mapinfo File', False, None ) # compress files import zipfile try: import zlib compression = zipfile.ZIP_DEFLATED except: compression = zipfile.ZIP_STORED zFile = os.path.join( outputInfo.absolutePath(), outputInfo.baseName()+'.zip' ) with zipfile.ZipFile(zFile, 'w') as zf: zf.write(os.path.join( outputInfo.absolutePath(), outputInfo.baseName()+'.tab' ), compress_type=compression, arcname=outputInfo.baseName()+'.tab') zf.write(os.path.join( outputInfo.absolutePath(), outputInfo.baseName()+'.dat' ), compress_type=compression, arcname=outputInfo.baseName()+'.dat') zf.write(os.path.join( outputInfo.absolutePath(), outputInfo.baseName()+'.map' ), compress_type=compression, arcname=outputInfo.baseName()+'.map') if os.path.exists( os.path.join( outputInfo.absolutePath(), outputInfo.baseName()+'.id' ) ): zf.write(os.path.join( outputInfo.absolutePath(), outputInfo.baseName()+'.id' ), compress_type=compression, arcname=outputInfo.baseName()+'.id') zf.close() outputFile = zFile elif v.format['mimetype'] == 'application/json': error = QgsVectorFileWriter.writeAsVectorFormat( outputLayer, outputFile, 'utf-8', destCrs, 'GeoJSON', False, None ) elif v.format['mimetype'] in ('text/xml; subtype=gml/3.1.1','application/gml+xml; version=3.1.1') : error = QgsVectorFileWriter.writeAsVectorFormat( outputLayer, outputFile, 'utf-8', destCrs, 'GML', False, None, ['XSISCHEMAURI=http://schemas.opengis.net/gml/3.1.1/base/feature.xsd','FORMAT=GML3'] ) else: error = QgsVectorFileWriter.writeAsVectorFormat( outputLayer, outputFile, 'utf-8', destCrs, 'GML', False, None, ['XSISCHEMAURI=http://schemas.opengis.net/gml/2.1.2/feature.xsd'] ) args[v.identifier] = outputFile # get OWS getCapabilities URL if not v.asReference and v.format['mimetype'] in ('application/x-ogc-wms', 'application/x-ogc-wfs'): from pywps.Wps.Execute import QGIS qgis = QGIS.QGIS(self, self.pywps.UUID) v.setValue( outputFile ) outputFile = qgis.getReference(v) args[v.identifier] = outputFile # Output Raster elif parm.__class__.__name__ == 'OutputRaster': outputName = result.get(v.identifier, None) # get output file info outputInfo = QFileInfo( outputName ) # get the output QGIS vector layer outputLayer = QgsRasterLayer( outputName, outputInfo.baseName(), 'gdal' ) # Update CRS if not outputLayer.dataProvider().crs().authid(): outputLayer.setCrs( inputCrs ) v.projection = 'proj4:'+inputCrs.toProj4() if not outputName : return 'No output file' args[v.identifier] = outputName # get OWS getCapabilities URL if not v.asReference and v.format['mimetype'] in ('application/x-ogc-wms', 'application/x-ogc-wcs'): from pywps.Wps.Execute import QGIS qgis = QGIS.QGIS(self, self.pywps.UUID) v.setValue( outputName ) outputFile = qgis.getReference(v) args[v.identifier] = outputFile else: args[v.identifier] = result.get(v.identifier, None) for k in self._outputs: v = getattr(self, k) v.setValue( args[v.identifier] ) return
def convert(self): self.buttonBox.button(QDialogButtonBox.Ok).setDefault(False) if self.inputLayerCombo.currentText() != "": inputLayer = self.inputLayerCombo.currentText() # layer information 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) # elevation attribute Elevation = self.lineAttrib.currentText() # cellsize cellSize = int(self.linePix.value()) outPath = self.inputLayerCombo3.text() Processing.initialize() # grid directory (qgis2) filedir = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/raster" 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': filedir, '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}) userDir = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/grid" Processing.runAlgorithm("grass7:r.surf.contour", None, out, extent, cellSize, userDir) # slope userSlope = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/slope" outGrid = userDir + "." + "tif" Processing.runAlgorithm("grass7:r.slope.aspect", None, outGrid, 1, 1, 1.0, 0.0, extent, cellSize, userSlope, None, None, None, None, None, None, None, None) # reclassify slope raster outSlope = userSlope + "." + "tif" userSlopeRec = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/slopeRec" if self.inputLayerCombo.currentText() == "": gdal.AllRegister() inputLayer_dem = self.inputLayerCombo_dem.currentText() # QMessageBox.about(self, "recharge", str(inputRaster)) gdalRaster = gdal.Open(str(inputLayer_dem)) # QMessageBox.about(self, "recharge", str(gdalRaster)) 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] ## layer information # layer_raster = QgsRasterLayer(unicode(inputLayer_dem).encode('utf8'), inputLayer_dem , "gdal") # rasterlayer = layer_raster.dataProvider() ## extent # extent_rect = rasterlayer.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) ##QMessageBox.about(self, "Superficie_topografica", str(extent)) ## cellsize # cellSize = layer_raster.rasterUnitsPerPixelX() ##cellSize = int(self.linePix.value()) ##QMessageBox.about(self, "Superficie_topografica", str(cellSize)) outPath = self.inputLayerCombo3.text() # pixel size is the same as the dem raster, miss reamostragem Processing.initialize() # mdt_interp = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/mdt_interp" # Processing.runAlgorithm("grass7:r.surf.idw", None, inputLayer_dem, 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) # geo_mdt = gdalMDT.GetGeoTransform() # minx = geo_mdt[0] # maxy = geo_mdt[3] # maxx = minx + geo_mdt[1]*x_mdt # miny = maxy + geo_mdt[5]*y_mdt # extent_raster_new = str(minx) + "," + str(maxx) + "," + str(miny) + "," + str(maxy) # pixelSize_new = geo_mdt[1] # slope from DEM userSlope_dem = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/slope_dem.tif" Processing.runAlgorithm("grass7:r.slope.aspect", {'elevation': inputLayer_dem, 'format': 1, 'precision': 0, '-a': True, 'zscale': 1, 'min_slope': 0, 'slope': userSlope_dem, 'aspect': None, 'pcurvature': None, 'tcurvature': None, 'dx': None, 'dy': None, 'dxx': None, 'dyy': None, 'dxy': None, 'GRASS_REGION_PARAMETER': extent_raster + '[EPSG:3763]', 'GRASS_REGION_CELLSIZE_PARAMETER': pixelSize, 'GRASS_RASTER_FORMAT_OPT': '', 'GRASS_RASTER_FORMAT_META': ''}) # reclassify slope raster # outSlope_dem = userSlope_dem + "." + "tif" # userSlopeRec_dem = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/slopeRec_dem" # indexes for Superficie_topografica # 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, "Superficie_topografica", str(userSlope_dem)) # list_new = [] # list_new_x = [] # list_new_y = [] # # QMessageBox.about(self, 'teste', str(self.plugin_dir)) # # FILE = os.path.join(self.plugin_dir, "//SINTACS grafico D.txt") # with open(os.path.join(self.plugin_dir, "SINTACS grafico S.txt"), 'r') as f: # d = {line.split('\t')[0]: line.split('\t')[1] for line in f} # #QMessageBox.about(self, "teste", str(d)) # # read raster values # raster = gdal.Open(str(userSlope_dem)) # data_mdt = raster.ReadAsArray() # values_raster = numpy.unique(data_mdt) # # QMessageBox.about(self, 'teste', values_raster) # for element in values_raster: # #QMessageBox.about(self, 'teste', str(element)) # if element <= 24.42: # #QMessageBox.about(self, 'teste', str(element)) # # get the key of a certain value # target = element # # key, value = min(d.items(), key=lambda kv: abs(float(kv[1]) - target)) # m = d.get(target, d[min(d.keys(), key=lambda k: abs(float(k) - target))]) # # remove \n from list # m_new = m.replace('\n', '') # list_new_x = list_new_x + [element] # list_new_y = list_new_y + [float(m_new)] # # # Set the path for the output file # output_file = open('C:\Artigos\DRASTIC_melhoria/file.txt', 'w') # for ii in range(len(list_new_x)): # list_new.append(list_new_x[ii]) # list_new.append(list_new_x[ii] + float(0.01)) # list_new.append(list_new_y[ii]) # list_new = list_new + [24.43] # list_new = list_new + [1000] # list_new = list_new + [0.9717] # QMessageBox.about(self, "teste", str(list_new)) # Get the features and properly rewrite them as lines # for feat in list_new: # output_file.write(str(feat)+'/t') # output_file.close() #QMessageBox.about(self, 'teste', str(list_new[20:])) # if self.inputLayerCombo.currentText() != "": # Processing.runAlgorithm("saga:reclassifyvalues", # {'INPUT': outSlope, 'METHOD': 2, 'OLD': 0, 'NEW': 1, 'SOPERATOR': 0, 'MIN': 0, # 'MAX': 1, # 'RNEW': 2, 'ROPERATOR': 0, 'RETAB': list_new, 'TOPERATOR': 0, 'NODATAOPT': True, # 'NODATA': 0, # 'OTHEROPT': True, 'OTHERS': 0, 'RESULT': outPath}) # reclassify slope_dem values #if self.inputLayerCombo.currentText() == "": # topo_interp = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/topo_interp.tif" # Processing.runAlgorithm("saga:reclassifyvalues", # {'INPUT': userSlope_dem, 'METHOD': 2, 'OLD': 0, 'NEW': 1, 'SOPERATOR': 0, 'MIN': 0, # 'MAX': 1, # 'RNEW': 2, 'ROPERATOR': 0, 'RETAB': list_new, 'TOPERATOR': 0, 'NODATAOPT': True, # 'NODATA': 0, # 'OTHEROPT': True, 'OTHERS': 0, 'RESULT': outPath}) Processing.runAlgorithm("grass7:r.reclass", { 'input': userSlope_dem, 'rules': os.path.join(self.plugin_dir, "SINTACS grafico S - Copy.txt"), 'txtrules': '', 'output': outPath, 'GRASS_REGION_PARAMETER': None, 'GRASS_REGION_CELLSIZE_PARAMETER': 0, 'GRASS_RASTER_FORMAT_OPT': '', 'GRASS_RASTER_FORMAT_META': ''}) # topo = topo_interp + "." + "tif" # Processing.runAlgorithm("grass7:r.surf.idw", None, topo_interp, 12, False, extent_raster, pixelSize, outPath) ## multiply by weight # fileInfo_dem = QFileInfo(outSlopeRec_dem) # baseName_dem = fileInfo_dem.baseName() # rlayer_dem = QgsRasterLayer(outSlopeRec_dem, baseName_dem) # gdalRaster_dem = gdal.Open(str(outSlopeRec_dem)) # x_dem = gdalRaster_dem.RasterXSize # y_dem = gdalRaster_dem.RasterYSize # geo_dem = gdalRaster_dem.GetGeoTransform() # band_dem = gdalRaster_dem.GetRasterBand(1) # data_dem = band_dem.ReadAsArray(0,0,x_dem,y_dem) # mul_dem = numpy.multiply(data_dem, int(self.lineWeight.value())) ## Create an output imagedriver # driver_dem = gdal.GetDriverByName( "GTiff" ) # outData_dem = driver_dem.Create(str(outPath), x_dem,y_dem,1, gdal.GDT_Float32) # outData_dem.GetRasterBand(1).WriteArray(mul_dem) # outData_dem.SetGeoTransform(geo_dem) # outData_dem = None # add result into canvas file_info_norm = QFileInfo(str(outPath + '.sdat')) # QMessageBox.about(self, "teste", str(file_info_norm)) rlayer_new_norm = QgsRasterLayer(outPath + '.sdat', 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]) # file_info_dem = QFileInfo(outPath) # if file_info_dem.exists(): # layer_name_dem = file_info_dem.baseName() # else: # return False # rlayer_new_dem = QgsRasterLayer(outPath, layer_name_dem) # if rlayer_new_dem.isValid(): # QgsMapLayerRegistry.instance().addMapLayer(rlayer_new_dem) # layer_dem = QgsMapCanvasLayer(rlayer_new_dem) # layerList_dem = [layer_dem] # extent_dem = self.iface.canvas.setExtent(rlayer_new_dem.extent()) # self.iface.canvas.setLayerSet(layerList_dem) # self.iface.canvas.setVisible(True) # return True # else: # return False QMessageBox.information(self, self.tr("Finished"), self.tr("Superficie_topografica completed.")) self.buttonBox.button(QDialogButtonBox.Ok).setDefault(True)
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 execute(self): # create a project p = QgsProject.instance() mlr = QgsMapLayerRegistry.instance() # Run alg with params # TODO: get args args = {} # get vector and raster inputs inputCrs = None for k in self._inputs: v = getattr(self, k) parm = self.alg.getParameterFromName(v.identifier) # vector layers if parm.__class__.__name__ == 'ParameterVector': values = [] if vectorLayers and ParameterVector.VECTOR_TYPE_ANY in parm.shapetype: values = [l for l in vectorLayers] elif vectorLayers: if ParameterVector.VECTOR_TYPE_POINT in parm.shapetype: values += [ l for l in vectorLayers if l['geometry'] == 'Point' ] if ParameterVector.VECTOR_TYPE_LINE in parm.shapetype: values += [ l for l in vectorLayers if l['geometry'] == 'Line' ] if ParameterVector.VECTOR_TYPE_POLYGON in parm.shapetype: values += [ l for l in vectorLayers if l['geometry'] == 'Polygon' ] if values: layerName = v.getValue() values = [l for l in values if l['name'] == layerName] l = values[0] layer = QgsVectorLayer(l['datasource'], l['name'], l['provider']) crs = l['crs'] qgsCrs = None if str(crs).startswith('USER:'******'proj4'])) else: qgsCrs = QgsCoordinateReferenceSystem(str(crs)) if qgsCrs: layer.setCrs(qgsCrs) mlr.addMapLayer(layer, False) args[v.identifier] = layer inputCrs = layer.crs() else: fileName = v.getValue() fileInfo = QFileInfo(fileName) # move fileName to fileName.gml for ogr with open(fileName, 'r') as f: o = open(fileName + '.gml', 'w') o.write(f.read()) o.close() #import shutil #shutil.copy2(fileName+'.gml', '/tmp/test.gml' ) # get layer layer = QgsVectorLayer(fileName + '.gml', fileInfo.baseName(), 'ogr') pr = layer.dataProvider() e = layer.extent() mlr.addMapLayer(layer, False) args[v.identifier] = layer inputCrs = layer.crs() # raster layers elif parm.__class__.__name__ == 'ParameterRaster': if rasterLayers: layerName = v.getValue() values = [ l for l in rasterLayers if l['name'] == layerName ] l = values[0] layer = QgsRasterLayer(l['datasource'], l['name'], l['provider']) crs = l['crs'] qgsCrs = None if str(crs).startswith('USER:'******'proj4'])) else: qgsCrs = QgsCoordinateReferenceSystem(str(crs)) if qgsCrs: layer.setCrs(qgsCrs) mlr.addMapLayer(layer, False) args[v.identifier] = layer inputCrs = layer.crs() else: fileName = v.getValue() fileInfo = QFileInfo(fileName) layer = QgsRasterLayer(fileName, fileInfo.baseName(), 'gdal') mlr.addMapLayer(layer, False) args[v.identifier] = layer inputCrs = layer.crs() elif parm.__class__.__name__ == 'ParameterExtent': coords = v.getValue().coords args[v.identifier] = str(coords[0][0]) + ',' + str( coords[1][0]) + ',' + str(coords[0][1]) + ',' + str( coords[1][1]) else: args[v.identifier] = v.getValue() # if extent in inputs, transform it to the alg CRS if inputCrs: for k in self._inputs: v = getattr(self, k) parm = self.alg.getParameterFromName(v.identifier) if parm.__class__.__name__ == 'ParameterExtent': coords = v.getValue().coords coordCrs = None if v.getValue().crs: coordCrs = QgsCoordinateReferenceSystem( str(v.getValue().crs)) elif crss: coordCrs = QgsCoordinateReferenceSystem(str(crss[0])) else: coordCrs = QgsCoordinateReferenceSystem('EPSG:4326') if coordCrs: coordExtent = QgsRectangle(coords[0][0], coords[0][1], coords[1][0], coords[1][1]) xform = QgsCoordinateTransform(coordCrs, inputCrs) coordExtent = xform.transformBoundingBox(coordExtent) args[v.identifier] = str( coordExtent.xMinimum()) + ',' + str( coordExtent.xMaximum()) + ',' + str( coordExtent.yMinimum()) + ',' + str( coordExtent.yMaximum()) # Adds None for output parameter(s) for k in self._outputs: v = getattr(self, k) args[v.identifier] = None if not len(self.alg.parameters): self.alg.defineCharacteristics() tAlg = Processing.runAlgorithm(self.alg, None, args) # if runalg failed return exception message if not tAlg: return 'Error in processing' # clear map layer registry mlr.removeAllMapLayers() # get result result = tAlg.getOutputValuesAsDictionary() for k in self._outputs: v = getattr(self, k) parm = self.alg.getOutputFromName(v.identifier) # Output Vector if parm.__class__.__name__ == 'OutputVector': outputName = result.get(v.identifier, None) if not outputName: return 'No output file' # get output file info outputInfo = QFileInfo(outputName) # get the output QGIS vector layer outputLayer = QgsVectorLayer(outputName, outputInfo.baseName(), 'ogr') # Update input CRS if not inputCrs.authid(): inputCrs.saveAsUserCRS('') crs = QgsCoordinateReferenceSystem() crs.createFromProj4(inputCrs.toProj4()) inputCrs = crs # Update CRS if not outputLayer.dataProvider().crs().authid(): outputLayer.setCrs(inputCrs) # define destination CRS destCrs = None if outputLayer.crs().authid().startswith('USER:'******'EPSG:4326') v.projection = 'EPSG:4326' # define the file extension outputExt = 'gml' if v.format['mimetype'] == 'application/json': outputExt = 'geojson' elif v.format['mimetype'] == 'application/x-zipped-shp': outputExt = 'shp' elif v.format['mimetype'] == 'application/x-zipped-tab': outputExt = 'tab' # define the output file path outputFile = os.path.join( outputInfo.absolutePath(), outputInfo.baseName() + '.' + outputExt) # write the output GML file if v.format['mimetype'] == 'application/x-zipped-shp': if destCrs: outputFile = os.path.join( outputInfo.absolutePath(), outputInfo.baseName() + '_' + str(destCrs.srsid()) + '.' + outputExt) outputInfo = QFileInfo(outputFile) error = QgsVectorFileWriter.writeAsVectorFormat( outputLayer, outputFile, 'utf-8', destCrs, 'ESRI Shapefile', False, None) # compress files import zipfile try: import zlib compression = zipfile.ZIP_DEFLATED except: compression = zipfile.ZIP_STORED zFile = os.path.join(outputInfo.absolutePath(), outputInfo.baseName() + '.zip') with zipfile.ZipFile(zFile, 'w') as zf: zf.write(os.path.join(outputInfo.absolutePath(), outputInfo.baseName() + '.shp'), compress_type=compression, arcname=outputInfo.baseName() + '.shp') zf.write(os.path.join(outputInfo.absolutePath(), outputInfo.baseName() + '.shx'), compress_type=compression, arcname=outputInfo.baseName() + '.shx') zf.write(os.path.join(outputInfo.absolutePath(), outputInfo.baseName() + '.dbf'), compress_type=compression, arcname=outputInfo.baseName() + '.dbf') if os.path.exists( os.path.join(outputInfo.absolutePath(), outputInfo.baseName() + '.prj')): zf.write(os.path.join( outputInfo.absolutePath(), outputInfo.baseName() + '.prj'), compress_type=compression, arcname=outputInfo.baseName() + '.prj') zf.close() outputFile = zFile elif v.format['mimetype'] == 'application/x-zipped-tab': error = QgsVectorFileWriter.writeAsVectorFormat( outputLayer, outputFile, 'utf-8', destCrs, 'Mapinfo File', False, None) # compress files import zipfile try: import zlib compression = zipfile.ZIP_DEFLATED except: compression = zipfile.ZIP_STORED zFile = os.path.join(outputInfo.absolutePath(), outputInfo.baseName() + '.zip') with zipfile.ZipFile(zFile, 'w') as zf: zf.write(os.path.join(outputInfo.absolutePath(), outputInfo.baseName() + '.tab'), compress_type=compression, arcname=outputInfo.baseName() + '.tab') zf.write(os.path.join(outputInfo.absolutePath(), outputInfo.baseName() + '.dat'), compress_type=compression, arcname=outputInfo.baseName() + '.dat') zf.write(os.path.join(outputInfo.absolutePath(), outputInfo.baseName() + '.map'), compress_type=compression, arcname=outputInfo.baseName() + '.map') if os.path.exists( os.path.join(outputInfo.absolutePath(), outputInfo.baseName() + '.id')): zf.write(os.path.join( outputInfo.absolutePath(), outputInfo.baseName() + '.id'), compress_type=compression, arcname=outputInfo.baseName() + '.id') zf.close() outputFile = zFile elif v.format['mimetype'] == 'application/json': error = QgsVectorFileWriter.writeAsVectorFormat( outputLayer, outputFile, 'utf-8', destCrs, 'GeoJSON', False, None) elif v.format['mimetype'] in ( 'text/xml; subtype=gml/3.1.1', 'application/gml+xml; version=3.1.1'): error = QgsVectorFileWriter.writeAsVectorFormat( outputLayer, outputFile, 'utf-8', destCrs, 'GML', False, None, [ 'XSISCHEMAURI=http://schemas.opengis.net/gml/3.1.1/base/feature.xsd', 'FORMAT=GML3' ]) else: error = QgsVectorFileWriter.writeAsVectorFormat( outputLayer, outputFile, 'utf-8', destCrs, 'GML', False, None, [ 'XSISCHEMAURI=http://schemas.opengis.net/gml/2.1.2/feature.xsd' ]) args[v.identifier] = outputFile # get OWS getCapabilities URL if not v.asReference and v.format['mimetype'] in ( 'application/x-ogc-wms', 'application/x-ogc-wfs'): from pywps.Wps.Execute import QGIS qgis = QGIS.QGIS(self, self.pywps.UUID) v.setValue(outputFile) outputFile = qgis.getReference(v) args[v.identifier] = outputFile # Output Raster elif parm.__class__.__name__ == 'OutputRaster': outputName = result.get(v.identifier, None) # get output file info outputInfo = QFileInfo(outputName) # get the output QGIS vector layer outputLayer = QgsRasterLayer(outputName, outputInfo.baseName(), 'gdal') # Update CRS if not outputLayer.dataProvider().crs().authid(): outputLayer.setCrs(inputCrs) v.projection = 'proj4:' + inputCrs.toProj4() if not outputName: return 'No output file' args[v.identifier] = outputName # get OWS getCapabilities URL if not v.asReference and v.format['mimetype'] in ( 'application/x-ogc-wms', 'application/x-ogc-wcs'): from pywps.Wps.Execute import QGIS qgis = QGIS.QGIS(self, self.pywps.UUID) v.setValue(outputName) outputFile = qgis.getReference(v) args[v.identifier] = outputFile else: args[v.identifier] = result.get(v.identifier, None) for k in self._outputs: v = getattr(self, k) v.setValue(args[v.identifier]) return
def convert(self): self.buttonBox.button(QDialogButtonBox.Ok).setDefault(False) if self.inputLayerCombo.currentText() != "": inputLayer = self.inputLayerCombo.currentText() # layer information 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) # elevation attribute Elevation = self.lineAttrib.currentText() # cellsize cellSize = int(self.linePix.value()) outPath = self.inputLayerCombo3.text() Processing.initialize() # grid directory (qgis2) filedir = QFileInfo( QgsApplication.qgisUserDatabaseFilePath()).path() + "/raster" 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': filedir, '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 }) userDir = QFileInfo( QgsApplication.qgisUserDatabaseFilePath()).path() + "/grid" Processing.runAlgorithm("grass7:r.surf.contour", None, out, extent, cellSize, userDir) # slope userSlope = QFileInfo( QgsApplication.qgisUserDbFilePath()).path() + "/slope" outGrid = userDir + "." + "tif" Processing.runAlgorithm("grass7:r.slope.aspect", None, outGrid, 1, 1, 1.0, 0.0, extent, cellSize, userSlope, None, None, None, None, None, None, None, None) # reclassify slope raster outSlope = userSlope + "." + "tif" userSlopeRec = QFileInfo( QgsApplication.qgisUserDbFilePath()).path() + "/slopeRec" if self.inputLayerCombo.currentText() == "": gdal.AllRegister() inputLayer_dem = self.inputLayerCombo_dem.currentText() #QMessageBox.about(self, "recharge", str(inputRaster)) gdalRaster = gdal.Open(str(inputLayer_dem)) #QMessageBox.about(self, "recharge", str(gdalRaster)) 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] ## layer information #layer_raster = QgsRasterLayer(unicode(inputLayer_dem).encode('utf8'), inputLayer_dem , "gdal") #rasterlayer = layer_raster.dataProvider() ## extent #extent_rect = rasterlayer.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) ##QMessageBox.about(self, "Topography", str(extent)) ## cellsize #cellSize = layer_raster.rasterUnitsPerPixelX() ##cellSize = int(self.linePix.value()) ##QMessageBox.about(self, "Topography", str(cellSize)) outPath = self.inputLayerCombo3.text() # pixel size is the same as the dem raster, miss reamostragem Processing.initialize() # mdt_interp = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/mdt_interp" # Processing.runAlgorithm("grass7:r.surf.idw", None, inputLayer_dem, 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) #geo_mdt = gdalMDT.GetGeoTransform() #minx = geo_mdt[0] #maxy = geo_mdt[3] #maxx = minx + geo_mdt[1]*x_mdt #miny = maxy + geo_mdt[5]*y_mdt #extent_raster_new = str(minx) + "," + str(maxx) + "," + str(miny) + "," + str(maxy) #pixelSize_new = geo_mdt[1] # slope from DEM userSlope_dem = QFileInfo(QgsApplication.qgisUserDatabaseFilePath( )).path() + "/slope_dem.tif" Processing.runAlgorithm( "grass7:r.slope.aspect", { 'elevation': inputLayer_dem, 'format': 1, 'precision': 0, '-a': True, 'zscale': 1, 'min_slope': 0, 'slope': userSlope_dem, 'aspect': None, 'pcurvature': None, 'tcurvature': None, 'dx': None, 'dy': None, 'dxx': None, 'dyy': None, 'dxy': None, 'GRASS_REGION_PARAMETER': extent_raster + '[EPSG:3763]', 'GRASS_REGION_CELLSIZE_PARAMETER': pixelSize, 'GRASS_RASTER_FORMAT_OPT': '', 'GRASS_RASTER_FORMAT_META': '' }) # reclassify slope raster #outSlope_dem = userSlope_dem + "." + "tif" #userSlopeRec_dem = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/slopeRec_dem" # indexes for topography 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, "Topography", str(userSlope_dem)) if self.inputLayerCombo.currentText() != "": Processing.runAlgorithm( "saga:reclassifyvalues", { 'INPUT': outSlope, '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 }) ## multiply by weight #fileInfo = QFileInfo(outSlopeRec) #baseName = fileInfo.baseName() #rlayer = QgsRasterLayer(outSlopeRec, baseName) #gdalRaster = gdal.Open(str(outSlopeRec)) #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.lineWeight.value())) ## Create an output imagedriver #driver = gdal.GetDriverByName( "GTiff" ) #outData = driver.Create(str(outPath), x,y,1, gdal.GDT_Float32) #outData.GetRasterBand(1).WriteArray(mul) #outData.SetGeoTransform(geo) #outData = None # add result into canvas # file_info = QFileInfo(outPath) # if file_info.exists(): # layer_name = file_info.baseName() # else: # return False # rlayer_new = QgsRasterLayer(outPath, layer_name) # if rlayer_new.isValid(): # QgsMapLayerRegistry.instance().addMapLayer(rlayer_new) # layer = QgsMapCanvasLayer(rlayer_new) # layerList = [layer] # extent = self.iface.canvas.setExtent(rlayer_new.extent()) # self.iface.canvas.setLayerSet(layerList) # self.iface.canvas.setVisible(True) # return True # else: # return False # reclassify slope_dem values if self.inputLayerCombo.currentText() == "": #topo_interp = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/topo_interp.tif" Processing.runAlgorithm( "saga:reclassifyvalues", { 'INPUT': userSlope_dem, '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 }) #topo = topo_interp + "." + "tif" #Processing.runAlgorithm("grass7:r.surf.idw", None, topo_interp, 12, False, extent_raster, pixelSize, outPath) ## multiply by weight #fileInfo_dem = QFileInfo(outSlopeRec_dem) #baseName_dem = fileInfo_dem.baseName() #rlayer_dem = QgsRasterLayer(outSlopeRec_dem, baseName_dem) #gdalRaster_dem = gdal.Open(str(outSlopeRec_dem)) #x_dem = gdalRaster_dem.RasterXSize #y_dem = gdalRaster_dem.RasterYSize #geo_dem = gdalRaster_dem.GetGeoTransform() #band_dem = gdalRaster_dem.GetRasterBand(1) #data_dem = band_dem.ReadAsArray(0,0,x_dem,y_dem) #mul_dem = numpy.multiply(data_dem, int(self.lineWeight.value())) ## Create an output imagedriver #driver_dem = gdal.GetDriverByName( "GTiff" ) #outData_dem = driver_dem.Create(str(outPath), x_dem,y_dem,1, gdal.GDT_Float32) #outData_dem.GetRasterBand(1).WriteArray(mul_dem) #outData_dem.SetGeoTransform(geo_dem) #outData_dem = None # add result into canvas file_info_norm = QFileInfo(str(outPath)) # QMessageBox.about(self, "teste", str(file_info_norm)) rlayer_new_norm = QgsRasterLayer(outPath, 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]) # file_info_dem = QFileInfo(outPath) # if file_info_dem.exists(): # layer_name_dem = file_info_dem.baseName() # else: # return False # rlayer_new_dem = QgsRasterLayer(outPath, layer_name_dem) # if rlayer_new_dem.isValid(): # QgsMapLayerRegistry.instance().addMapLayer(rlayer_new_dem) # layer_dem = QgsMapCanvasLayer(rlayer_new_dem) # layerList_dem = [layer_dem] # extent_dem = self.iface.canvas.setExtent(rlayer_new_dem.extent()) # self.iface.canvas.setLayerSet(layerList_dem) # self.iface.canvas.setVisible(True) # return True # else: # return False QMessageBox.information(self, self.tr("Finished"), self.tr("Topography completed.")) self.buttonBox.button(QDialogButtonBox.Ok).setDefault(True)
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")
def convert(self): self.buttonBox.button(QDialogButtonBox.Ok).setDefault(False) if self.inputLayerCombo.currentText()!="": inputLayer = self.inputLayerCombo.currentText() inputLayer1 = self.inputLayerCombo1.currentText() inputLayer2 = self.inputLayerCombo2.currentText() # layer information layer = QgsVectorLayer(unicode(inputLayer).encode('utf8'), inputLayer , "ogr") layer1 = QgsVectorLayer(unicode(inputLayer1).encode('utf8'), inputLayer1 , "ogr") layer2 = QgsVectorLayer(unicode(inputLayer2).encode('utf8'), inputLayer2 , "ogr") vectorlayer_vector = layer.dataProvider() vectorlayer_vector1 = layer1.dataProvider() vectorlayer_vector2 = layer2.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) # attribute Elevation = self.lineAttrib.currentText() Attrib1 = self.lineAttribRunoff.currentText() Attrib2 = self.lineAttribEvap.currentText() # cellsize cellSize = int(self.linePix.value()) outPath = self.inputLayerCombo3.text() Processing.initialize() # grid directory (qgis2) filedir = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/pret" filedir1 = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/runoff" filedir2 = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/evapo" 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': filedir, '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}) # map subtraction in case of having the three shapefiles if self.inputLayerCombo1.currentText()!="": Processing.runAlgorithm("grass7:v.to.rast", {'input': inputLayer1, 'type': [0, 1, 3], 'where': '', 'use': 0, 'attribute_column': Attrib1, 'rgb_column': None, 'label_column': None, 'value': None, 'memory': 300, 'output': filedir1, '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}) Processing.runAlgorithm("grass7:v.to.rast", {'input': inputLayer2, 'type': [0, 1, 3], 'where': '', 'use': 0, 'attribute_column': Attrib2, 'rgb_column': None, 'label_column': None, 'value': None, 'memory': 300, 'output': filedir2, '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}) recharge = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/recharge" gdalRaster_prec = gdal.Open(str(out)) x_prec = gdalRaster_prec.RasterXSize y_prec = gdalRaster_prec.RasterYSize geo_prec = gdalRaster_prec.GetGeoTransform() band_prec = gdalRaster_prec.GetRasterBand(1) data_prec = band_prec.ReadAsArray(0,0,x_prec,y_prec) gdalRaster_runoff = gdal.Open(str(outRunoff)) x_runoff = gdalRaster_runoff.RasterXSize y_runoff = gdalRaster_runoff.RasterYSize geo_runoff = gdalRaster_runoff.GetGeoTransform() band_runoff = gdalRaster_runoff.GetRasterBand(1) data_runoff = band_runoff.ReadAsArray(0,0,x_runoff,y_runoff) gdalRaster_evapo = gdal.Open(str(outEvap)) x_evapo = gdalRaster_evapo.RasterXSize y_evapo = gdalRaster_evapo.RasterYSize geo_evapo = gdalRaster_evapo.GetGeoTransform() band_evapo = gdalRaster_evapo.GetRasterBand(1) data_evapo = band_evapo.ReadAsArray(0,0,x_evapo,y_evapo) sub1 = numpy.subtract(data_prec, data_runoff) sub2 = numpy.subtract(sub1, data_evapo) # Create an output imagedriver with the substraction result driver_out = gdal.GetDriverByName( "GTiff" ) outData_recharge = driver_out.Create(str(recharge), x_prec,y_prec,1, gdal.GDT_Float32) outData_recharge.GetRasterBand(1).WriteArray(sub2) outData_recharge.SetGeoTransform(geo_prec) outData_recharge = None # multiplication of precipitation by 0.1, in case of having only the precipitation shapefile if self.inputLayerCombo1.currentText()=="": userReclassify = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/reclassify" # recharge = precipitation * 0.1 (10% of precipitation) gdalRaster = gdal.Open(str(out)) x = gdalRaster.RasterXSize y = gdalRaster.RasterYSize geo = gdalRaster.GetGeoTransform() band = gdalRaster.GetRasterBand(1) data = band.ReadAsArray(0,0,x,y) mul = numpy.multiply(data, 0.1) # Create an output imagedriver with the multiplication result driver = gdal.GetDriverByName( "GTiff" ) outData = driver.Create(str(userReclassify), x,y,1, gdal.GDT_Float32) outData.GetRasterBand(1).WriteArray(mul) outData.SetGeoTransform(geo) outData = None # 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) # reclassification of recharge values in case of having only the precipitation shapefile if self.inputLayerCombo1.currentText()=="": recharge_prec = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/recharge_prec" Processing.runAlgorithm("saga:reclassifygridvalues", None, userReclassify, 2, 0.0, 1.0, 0, 0.0, 1.0, 2.0, 0, intervalos, 0, True, 0.0, True, 0.0, outPath) # add result into canvas file_info_prec = QFileInfo(outPath) if file_info_prec.exists(): layer_name_prec = file_info_prec.baseName() else: return False rlayer_new_prec = QgsRasterLayer(outPath, layer_name_prec) if rlayer_new_prec.isValid(): QgsMapLayerRegistry.instance().addMapLayer(rlayer_new_prec) layer_prec = QgsMapCanvasLayer(rlayer_new_prec) layerList_prec = [layer_prec] extent_prec = self.iface.canvas.setExtent(rlayer_new_prec.extent()) self.iface.canvas.setLayerSet(layerList_prec) self.iface.canvas.setVisible(True) return True else: return False QMessageBox.information(self, self.tr( "Finished" ), self.tr( "Net Recharge completed." ) ) # reclassification of recharge values in case of having the three shapefiles if self.inputLayerCombo1.currentText()!="": recharge_prec_run_evap = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/recharge_prec_run_evap" Processing.runAlgorithm("saga:reclassifygridvalues", None, recharge, 2, 0.0, 1.0, 0, 0.0, 1.0, 2.0, 0, intervalos, 0, True, 0.0, True, 0.0, outPath) # add result into canvas file_info_prec_runoff_evapo = QFileInfo(outPath) if file_info_prec_runoff_evapo.exists(): layer_name_prec_runoff_evapo = file_info_prec_runoff_evapo.baseName() else: return False rlayer_new_prec_runoff_evapo = QgsRasterLayer(outPath, layer_name_prec_runoff_evapo) if rlayer_new_prec_runoff_evapo.isValid(): QgsMapLayerRegistry.instance().addMapLayer(rlayer_new_prec_runoff_evapo) layer_prec_runoff_evapo = QgsMapCanvasLayer(rlayer_new_prec_runoff_evapo) layerList_prec_runoff_evapo = [layer_prec_runoff_evapo] extent_prec_runoff_evapo = self.iface.canvas.setExtent(rlayer_new_prec_runoff_evapo.extent()) self.iface.canvas.setLayerSet(layerList_prec_runoff_evapo) self.iface.canvas.setVisible(True) return True else: return False QMessageBox.information(self, self.tr( "Finished" ), self.tr( "Net Recharge completed." ) ) if self.inputLayerCombo4.currentText()!="": gdal.AllRegister() # read mdt data outPath2 = self.inputLayerCombo3.text() inputRaster = self.inputLayerCombo4.currentText() 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 = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).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}) # 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 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() Processing.runAlgorithm("native:reclassifybytable", { 'INPUT_RASTER': recharge_without_rec, 'RASTER_BAND': 1, 'TABLE': results, 'NO_DATA': -9999, 'RANGE_BOUNDARIES': 0, 'NODATA_FOR_MISSING': False, 'DATA_TYPE': 5, 'OUTPUT': outPath2}) # 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." ) ) if self.inputLayerCombo5.currentText()!="": inputLayer = self.inputLayerCombo5.currentText() 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) # attribute Elevation = self.lineAttrib5.currentText() # cellsize cellSize = int(self.linePix.value()) prec_value = int(self.lineprec.value()) outPath = self.inputLayerCombo3.text() Processing.initialize() raster = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/raster.tif" Processing.runAlgorithm("grass7:v.to.rast", { 'input': inputLayer, 'type': [0, 1, 3], 'where': '', 'use': 0, 'attribute_column': Elevation, 'rgb_column': '', 'label_column': '', 'value': 1, 'memory': 300, 'output': raster, 'GRASS_REGION_PARAMETER': extent + ' [EPSG:3763]', 'GRASS_REGION_CELLSIZE_PARAMETER': cellSize, 'GRASS_RASTER_FORMAT_OPT': '', 'GRASS_RASTER_FORMAT_META': '', 'GRASS_SNAP_TOLERANCE_PARAMETER': -1, 'GRASS_MIN_AREA_PARAMETER': 0.0001}) precipitacao = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/precipitacao.tif" Processing.runAlgorithm("grass7:r.mapcalc.simple", { 'a': raster, 'b': None, 'c': None, 'd': None, 'e': None, 'f': None, 'expression': 'A*'+ str(prec_value) + '/100', 'output': precipitacao, 'GRASS_REGION_PARAMETER': extent +' [EPSG:3763]', 'GRASS_REGION_CELLSIZE_PARAMETER': cellSize, 'GRASS_RASTER_FORMAT_OPT': '', 'GRASS_RASTER_FORMAT_META': ''}) # indexes for topography 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 + [self.line.text()] string = "," intervalos = string.join(lista) results = list(map(float, lista)) # Processing.runAlgorithm("saga:reclassifyvalues", # {'INPUT': precipitacao, '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}) Processing.runAlgorithm("native:reclassifybytable", {'INPUT_RASTER': str(precipitacao), 'RASTER_BAND': 1, 'TABLE': results, 'NO_DATA': -9999, 'RANGE_BOUNDARIES': 0, 'NODATA_FOR_MISSING': False, 'DATA_TYPE': 5, 'OUTPUT': outPath}) # add result into canvas file_info_norm = QFileInfo(str(outPath)) # QMessageBox.about(self, "teste", str(file_info_norm)) rlayer_new_norm = QgsRasterLayer(outPath, 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]) QMessageBox.information(self, self.tr("Finished"), self.tr("Net Recharge completed.")) self.buttonBox.button(QDialogButtonBox.Ok).setDefault(True)
def convert(self): self.buttonBox.button(QDialogButtonBox.Ok).setDefault(False) # read D raster inputLayer = self.inputLayerCombo.currentText() # read R raster inputLayer2 = self.inputLayerCombo2.currentText() # read A raster inputLayer3 = self.inputLayerCombo3.currentText() # read S raster inputLayer4 = self.inputLayerCombo4.currentText() # read T raster inputLayer5 = self.inputLayerCombo5.currentText() # read I raster inputLayer6 = self.inputLayerCombo6.currentText() # read C raster inputLayer7 = self.inputLayerCombo7.currentText() # 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] # 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) 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, 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, 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_correct, True, 0, 0, extent, pixelSize, 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, 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, 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, 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) # sum summ = data_d + data_r + data_a + data_s + data_t + data_i + data_c sum_nodata = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/sum_nodata" sum_nodata_rec = sum_nodata + "." + "tif" # Create an output imagedriver with the reclassified values multiplied by the weight driver_sum = gdal.GetDriverByName( "GTiff" ) outData_sum = driver_sum.Create(str(sum_nodata), x,y,1, gdal.GDT_Float32) outData_sum.GetRasterBand(1).WriteArray(summ) outData_sum.SetGeoTransform(geo) outData_sum = None # reclassify no data values Processing.runAlgorithm("saga:reclassifygridvalues", None, sum_nodata, 0, -10000100352, 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, outPath) if self.checkdrastic.isChecked(): # add result into canvas file_info = QFileInfo(outPath) if file_info.exists(): layer_name = file_info.baseName() else: return False rlayer_new = QgsRasterLayer(outPath, layer_name) if rlayer_new.isValid(): QgsMapLayerRegistry.instance().addMapLayer(rlayer_new) layer = QgsMapCanvasLayer(rlayer_new) layerList = [layer] extent = self.iface.canvas.setExtent(rlayer_new.extent()) self.iface.canvas.setLayerSet(layerList) self.iface.canvas.setVisible(True) return True else: return False QMessageBox.information(self, self.tr( "Finished" ), self.tr( "DRASTIC completed." ) ) colorfile = 'C:/OSGeo4W64/apps/qgis/python/plugins/DRASTIC/colorfile.clr' outPath_color = self.outputLayerCombo_color.text() from colorize import raster2png raster2png(outPath, colorfile , outPath_color,1, False) if self.checkcolor.isChecked(): # add result into canvas file_info = QFileInfo(outPath_color) if file_info.exists(): layer_name = file_info.baseName() else: return False rlayer_new = QgsRasterLayer(outPath_color, layer_name) if rlayer_new.isValid(): QgsMapLayerRegistry.instance().addMapLayer(rlayer_new) layer = QgsMapCanvasLayer(rlayer_new) layerList = [layer] extent = self.iface.canvas.setExtent(rlayer_new.extent()) self.iface.canvas.setLayerSet(layerList) self.iface.canvas.setVisible(True) return True else: return False QMessageBox.information(self, self.tr( "Finished" ), self.tr( "DRASTIC completed." ) ) self.buttonBox.button(QDialogButtonBox.Ok).setDefault(True)