def processing_alghelp(_, request): """Retrieve arguments and usage information of a Processing algorithm. HTTP query arguments: alg (string): the name of the algorithm for which to show the help Returns: An array of strings describing the algorithm as well as its arguments. """ with GetStdOut() as alghelp: processing.alghelp(request.args['alg']) # strip parameter-initial tabs and remove blank lines return NetworkAPIResult([line.strip() for line in alghelp if line])
#Initialisierung und Beenden von QGIS in Python: # Import modules import sys from qgis.core import * from qgis.gui import * from PyQt4.QtCore import * from PyQt4.QtGui import * from qgis.utils import * # Configure QGIS directories and start the app # Not to be used in QGIS python editor app = QgsApplication([], True) QgsApplication.setPrefixPath("/usr", True) QgsApplication.initQgis() sys.path.append("/usr/share/qgis/python/plugins") import processing from processing.core.Processing import Processing from processing.tools import * Processing.initialize() # now do processing.runalg(...) - needs loaded Layer first inputVectorFile = '/home/jorge/Escritorio/CCAA/Comunidades_Autonomas_ETRS89_30N.shp' vecLayer = QgsVectorLayer(inputVectorFile, 'myVecLayer', 'ogr') processing.alghelp('grass:v.buffer.distance') processing.runalg('qgis:fixeddistancebuffer', vecLayer, 30, 10, False, '/tmp/buff.shp') # ... # finish app at the end QgsApplication.exitQgis()
def runAlgorithm(algOrName, onFinish, *args): if isinstance(algOrName, GeoAlgorithm): alg = algOrName else: alg = Processing.getAlgorithm(algOrName) if alg is None: print 'Error: Algorithm not found\n' return if len(args) != alg.getVisibleParametersCount() \ + alg.getVisibleOutputsCount(): print 'Error: Wrong number of parameters' processing.alghelp(algOrName) return alg = alg.getCopy() if isinstance(args, dict): # Set params by name for (name, value) in args.items(): if alg.getParameterFromName(name).setValue(value): continue if alg.getOutputFromName(name).setValue(value): continue print 'Error: Wrong parameter value %s for parameter %s.' \ % (value, name) return else: i = 0 for param in alg.parameters: if not param.hidden: if not param.setValue(args[i]): print 'Error: Wrong parameter value: ' \ + unicode(args[i]) return i = i + 1 for output in alg.outputs: if not output.hidden: if not output.setValue(args[i]): print 'Error: Wrong output value: ' + unicode(args[i]) return i = i + 1 msg = alg.checkParameterValuesBeforeExecuting() if msg: print 'Unable to execute algorithm\n' + msg return if not alg.checkInputCRS(): print 'Warning: Not all input layers use the same CRS.\n' \ + 'This can cause unexpected results.' ProcessingLog.addToLog(ProcessingLog.LOG_ALGORITHM, alg.getAsCommand()) # Don't set the wait cursor twice, because then when you # restore it, it will still be a wait cursor. cursor = QApplication.overrideCursor() if cursor is None or cursor == 0: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) elif cursor.shape() != Qt.WaitCursor: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) progress = SilentProgress() if iface is not None : progress = MessageBarProgress() ret = UnthreadedAlgorithmExecutor.runalg(alg, progress) if onFinish is not None and ret: onFinish(alg, progress) QApplication.restoreOverrideCursor() progress.close() return alg
for i, j in reversed(list(enumerate(field_names))): if j not in accepted_attributes: layer.deleteAttribute(i) print "--> Columns deleted.\n" # Export attribute table as csv file SLIC_attr = os.getcwd() + r"\39_SLIC_attr.csv" if not os.path.isfile(SLIC_attr): QgsVectorFileWriter.writeAsVectorFormat(layer, SLIC_attr, "utf-8", None, "CSV") print "--> Attribute table exported.\n" QgsMapLayerRegistry.instance().removeMapLayers([layer.id()]) print "All processing finished." """ ### Notes ### # QGIS help import processing processing.alghelp("qgis:fieldcalculator") processing.alghelp("grass7:v.clean") processing.alglist("g.extension") # Code Snippets # Add boundary field per line segment SLIC_boundary = os.getcwd() + r"\24_SLIC_final.shp" if not os.path.isfile(SLIC_boundary): processing.runalg('qgis:addfieldtoattributestable', {"INPUT_LAYER": SLIC_dsm_gradient, "FIELD_NAME": "boundary",
# Silence the error "UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.", see https://github.com/matplotlib/matplotlib/issues/5836#issuecomment-179592427 with warnings.catch_warnings(): warnings.simplefilter("ignore") from processing.core.Processing import Processing from processing.core.Processing import ProcessingConfig Processing.initialize() import processing # Manually set the OTB path, see https://github.com/qgis/QGIS/blob/master/python/plugins/processing/core/ProcessingConfig.py and https://github.com/qgis/QGIS/blob/master/python/plugins/processing/algs/otb/OTBUtils.py ProcessingConfig.setSettingValue("OTB_FOLDER", os.getenv('OTB_FOLDER', '')) ProcessingConfig.setSettingValue("OTB_LIB_FOLDER", os.getenv('OTB_LIB_FOLDER', '')) print("###### Algorithm help and options:") processing.alghelp("modeler:docker") processing.algoptions("modeler:docker") # Helper function for creating output directory import errno def make_sure_path_exists(path): try: os.makedirs(path) except OSError as exception: if exception.errno != errno.EEXIST: raise # Run model, use current timestamp for output directory name
#------------------------------------------------------------------------------------------------ #----------------------------------------# #--- Load processing tools to console ---# #----------------------------------------# #Load processing algorithms import processing #List of algorithm within processing processing.alglist() #Points related algorithms processing.alglist("point") #Processing tool example processing.alghelp("saga:slopeaspectcurvature") #Processing especification from polygon centroids processing.alghelp("saga:polygoncentroids") #ALGORITHM: Polygon centroids # POLYGONS <ParameterVector> # METHOD <ParameterBoolean> # CENTROIDS <OutputVector> processing.algoptions("saga:polygoncentroids") #--- Load a shapefile wd = "C:/Users/PC-600/Dropbox (Farmers Edge)/MuriloVianna/DB/SoilDB/ISRIC/ISRIC_250m/costumers" fn = "BLDFIE_M_sl1_250m_NA_ChapadaodaAtlantica_Subfield1972585_Zoning87346_NIR_NB_20150806.shp"
def runAlgorithm(algOrName, onFinish, *args): if isinstance(algOrName, GeoAlgorithm): alg = algOrName else: alg = Processing.getAlgorithm(algOrName) if alg is None: print 'Error: Algorithm not found\n' return alg = alg.getCopy() if len(args) == 1 and isinstance(args[0], dict): # Set params by name and try to run the alg even if not all parameter values are provided, # by using the default values instead. setParams = [] for (name, value) in args[0].items(): param = alg.getParameterFromName(name) if param and param.setValue(value): setParams.append(name) continue output = alg.getOutputFromName(name) if output and output.setValue(value): continue print 'Error: Wrong parameter value %s for parameter %s.' \ % (value, name) ProcessingLog.addToLog(ProcessingLog.LOG_ERROR, Processing.tr('Error in %s. Wrong parameter value %s for parameter %s.') \ % (alg.name, value, name)) return # fill any missing parameters with default values if allowed for param in alg.parameters: if param.name not in setParams: if not param.setValue(None): print( 'Error: Missing parameter value for parameter %s.' % (param.name)) ProcessingLog.addToLog(ProcessingLog.LOG_ERROR, Processing.tr('Error in %s. Missing parameter value for parameter %s.') \ % (alg.name, param.name)) return else: if len(args) != alg.getVisibleParametersCount() \ + alg.getVisibleOutputsCount(): print 'Error: Wrong number of parameters' processing.alghelp(algOrName) return i = 0 for param in alg.parameters: if not param.hidden: if not param.setValue(args[i]): print 'Error: Wrong parameter value: ' \ + unicode(args[i]) return i = i + 1 for output in alg.outputs: if not output.hidden: if not output.setValue(args[i]): print 'Error: Wrong output value: ' + unicode(args[i]) return i = i + 1 msg = alg.checkParameterValuesBeforeExecuting() if msg: print 'Unable to execute algorithm\n' + msg return if not alg.checkInputCRS(): print 'Warning: Not all input layers use the same CRS.\n' \ + 'This can cause unexpected results.' if iface is not None: # Don't set the wait cursor twice, because then when you # restore it, it will still be a wait cursor. cursor = QApplication.overrideCursor() if cursor is None or cursor == 0: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) elif cursor.shape() != Qt.WaitCursor: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) progress = None if iface is not None: progress = MessageBarProgress() ret = runalg(alg, progress) if onFinish is not None and ret: onFinish(alg, progress) if iface is not None: QApplication.restoreOverrideCursor() progress.close() return alg
def runAlgorithm(algOrName, onFinish, *args): if isinstance(algOrName, GeoAlgorithm): alg = algOrName else: alg = Processing.getAlgorithm(algOrName) if alg is None: print 'Error: Algorithm not found\n' return if len(args) != alg.getVisibleParametersCount() \ + alg.getVisibleOutputsCount(): print 'Error: Wrong number of parameters' processing.alghelp(algOrName) return alg = alg.getCopy() if isinstance(args, dict): # Set params by name for (name, value) in args.items(): if alg.getParameterFromName(name).setValue(value): continue if alg.getOutputFromName(name).setValue(value): continue print 'Error: Wrong parameter value %s for parameter %s.' \ % (value, name) return else: i = 0 for param in alg.parameters: if not param.hidden: if not param.setValue(args[i]): print 'Error: Wrong parameter value: ' \ + unicode(args[i]) return i = i + 1 for output in alg.outputs: if not output.hidden: if not output.setValue(args[i]): print 'Error: Wrong output value: ' + unicode(args[i]) return i = i + 1 msg = alg.checkParameterValuesBeforeExecuting() if msg: print 'Unable to execute algorithm\n' + msg return if not alg.checkInputCRS(): print 'Warning: Not all input layers use the same CRS.\n' \ + 'This can cause unexpected results.' ProcessingLog.addToLog(ProcessingLog.LOG_ALGORITHM, alg.getAsCommand()) # Don't set the wait cursor twice, because then when you # restore it, it will still be a wait cursor. cursor = QApplication.overrideCursor() if cursor is None or cursor == 0: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) elif cursor.shape() != Qt.WaitCursor: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) progress = MessageBarProgress() ret = UnthreadedAlgorithmExecutor.runalg(alg, progress) if onFinish is not None and ret: onFinish(alg, progress) QApplication.restoreOverrideCursor() progress.close() return alg
#GARRET BENZ #6/24/2019 #GEOG 682 path1 = "C:\Users\gbenz\Downloads\Crime_Incidents_in_2017\Crime_Incidents_in_2017.shp" from PyQt4.QtGui import * crime = QgsVectorLayer(path1, "Crime Incidents", "ogr") QgsMapLayerRegistry.instance().addMapLayer(crime) path2 = "C:\Users\gbenz\Downloads\Police_Districts\Police_Districts.shp" districts = QgsVectorLayer(path2, "Police Districts", "ogr") QgsMapLayerRegistry.instance().addMapLayer(districts) import processing processing.alghelp("qgis:joinattributesbylocation") processing.runalg( "qgis:joinattributesbylocation", { "TARGET": "C:\Users\gbenz\Downloads\Police_Districts\Police_Districts.shp", "JOIN": "C:\Users\gbenz\Downloads\Crime_Incidents_in_2017\Crime_Incidents_in_2017.shp", "PREDICATE": u'contains', "SUMMARY": 1, "KEEP": 1, "OUTPUT": "C:\Users\gbenz\Downloads\Police_Districts\joindata2.shp" }) #Which police district had the most crimes in 2017? How many crimes occured there? #ANSWER: The Second District reports the highest amount of crime with 5628 offenses recorded
import warnings; # Silence the error "UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.", see https://github.com/matplotlib/matplotlib/issues/5836#issuecomment-179592427 with warnings.catch_warnings(): warnings.simplefilter("ignore"); from processing.core.Processing import Processing from processing.core.Processing import ProcessingConfig Processing.initialize() import processing # Manually set the OTB path, see https://github.com/qgis/QGIS/blob/master/python/plugins/processing/core/ProcessingConfig.py and https://github.com/qgis/QGIS/blob/master/python/plugins/processing/algs/otb/OTBUtils.py ProcessingConfig.setSettingValue("OTB_FOLDER", os.getenv('OTB_FOLDER', '')) ProcessingConfig.setSettingValue("OTB_LIB_FOLDER", os.getenv('OTB_LIB_FOLDER', '')) print("###### Algorithm help and options:") processing.alghelp("modeler:docker") processing.algoptions("modeler:docker") # Helper function for creating output directory import errno def make_sure_path_exists(path): try: os.makedirs(path) except OSError as exception: if exception.errno != errno.EEXIST: raise # Run model, use current timestamp for output directory name input_image = os.path.join(os.getenv('QGIS_WORKSPACE', os.getcwd()), "aasee_muenster_sentinel2.tif") output_directory = os.path.join(os.getenv('QGIS_RESULT', os.path.join(tempfile.gettempdir(), 'results')), datetime.datetime.now().strftime("%Y%m%d-%H%M%S")) make_sure_path_exists(output_directory)
# -*- coding: utf-8 -*- #importar las funciones del procesamiento import processing #ahora necesitamos saber el algoritmo a usar #para ello usamos el método alglist() #si introduces alglist() te salen todos los métodos pero #si pones entre los paréwntesis algún nombre, te hace el filtro processing.alglist("merge") #nos tiene que salir #Merge vector layers---------------------------------->qgis:mergevectorlayers #como ya sabemos lo que queremos usar #usamos el método alghelp() para saber como es la sintaxis processing.alghelp("qgis:mergevectorlayers") #como ya sabemos la sintaxis, usamos ell sigueinte étodo #para usar el algoritmo #runalg(nombre del algoritmo,parámetro1,parámetro2,etc) nom_layer_carret = r'E:\CURSO_PYQGIS\CAPAS\carreteras.shp' nom_layer_rios = r'E:\CURSO_PYQGIS\CAPAS\rios.shp' nom_resultado = r'E:\CURSO_PYQGIS\CAPAS_PROCESADAS\elementos_lineales.shp' processing.runalg('qgis:mergevectorlayers', [nom_layer_carret, nom_layer_rios], nom_resultado) layer_lineas = QgsVectorLayer( r'E:\CURSO_PYQGIS\CAPAS_PROCESADAS\elementos_lineales.shp', 'elem_lineal', 'ogr') QgsMapLayerRegistry.instance().addMapLayer(layer_lineas)
# -*- coding: utf-8 -*- # 1. QGIS Mac Version import os import sys sys.path.append('/Applications/QGis.app/Contents/Resources/python/') sys.path.append('/Applications/QGis.app/Contents/Resources/python/plugins') # if you want to use the processing module, for example from qgis.core import * app = QgsApplication([],True) QgsApplication.setPrefixPath("/Applications/QGIS.app/Contents/Plugins", True) QgsApplication.initQgis() import processing # all the steps above need to be done on a mac version of qgis installed my kyngchaos # initialize processing from processing.core.Processing import Processing Processing.initialize() Processing.updateAlgsList() # run algorithms processing.alghelp("qgis:clip") processing.runalg("qgis:clip",inputlayer,overlaylayer,"output_file.shp")
# Silence the error "UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.", see https://github.com/matplotlib/matplotlib/issues/5836#issuecomment-179592427 with warnings.catch_warnings(): warnings.simplefilter("ignore") from processing.core.Processing import Processing from processing.core.Processing import ProcessingConfig Processing.initialize() import processing # Manually set the OTB path, see https://github.com/qgis/QGIS/blob/master/python/plugins/processing/core/ProcessingConfig.py and https://github.com/qgis/QGIS/blob/master/python/plugins/processing/algs/otb/OTBUtils.py ProcessingConfig.setSettingValue("OTB_FOLDER", os.getenv('OTB_FOLDER', '')) ProcessingConfig.setSettingValue("OTB_LIB_FOLDER", os.getenv('OTB_LIB_FOLDER', '')) print("###### Algorithm help and options:") processing.alghelp("otb:unsupervisedkmeansimageclassification") processing.algoptions("otb:unsupervisedkmeansimageclassification") # Helper function for creating output directory import errno def make_sure_path_exists(path): try: os.makedirs(path) except OSError as exception: if exception.errno != errno.EEXIST: raise # Get number of classes from envrionment variable within the container
def runAlgorithm(algOrName, onFinish, *args): if isinstance(algOrName, GeoAlgorithm): alg = algOrName else: alg = Processing.getAlgorithm(algOrName) if alg == None: print("Error: Algorithm not found\n") return if len(args) != alg.getVisibleParametersCount() + alg.getVisibleOutputsCount(): print ("Error: Wrong number of parameters") processing.alghelp(algOrName) return alg = alg.getCopy() if isinstance(args, dict): # set params by name for name, value in args.items(): if alg.getParameterFromName(name).setValue(value): continue; if alg.getOutputFromName(name).setValue(value): continue; print ("Error: Wrong parameter value %s for parameter %s." % (value, name)) return else: i = 0 for param in alg.parameters: if not param.hidden: if not param.setValue(args[i]): print ("Error: Wrong parameter value: " + unicode(args[i])) return i = i +1 for output in alg.outputs: if not output.hidden: if not output.setValue(args[i]): print ("Error: Wrong output value: " + unicode(args[i])) return i = i +1 msg = alg.checkParameterValuesBeforeExecuting() if msg: print ("Unable to execute algorithm\n" + msg) return if not alg.checkInputCRS(): print ("Warning: Not all input layers use the same CRS.\n" + "This can cause unexpected results.") ProcessingLog.addToLog(ProcessingLog.LOG_ALGORITHM, alg.getAsCommand()) # don't set the wait cursor twice, because then when you restore it # it will still be a wait cursor cursor = QApplication.overrideCursor() if cursor == None or cursor == 0: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) elif cursor.shape() != Qt.WaitCursor: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) useThreads = ProcessingConfig.getSetting(ProcessingConfig.USE_THREADS) #this is doing strange things, so temporarily the thread execution is disabled from the console useThreads = False if useThreads: algEx = AlgorithmExecutor(alg) progress = QProgressDialog() progress.setWindowTitle(alg.name) progress.setLabelText("Executing %s..." % alg.name) def finish(): QApplication.restoreOverrideCursor() if onFinish is not None: onFinish(alg, SilentProgress()) progress.close() def error(msg): QApplication.restoreOverrideCursor() print msg ProcessingLog.addToLog(ProcessingLog.LOG_ERROR, msg) def cancel(): try: algEx.finished.disconnect() algEx.terminate() QApplication.restoreOverrideCursor() progress.close() except: pass algEx.error.connect(error) algEx.finished.connect(finish) algEx.start() algEx.wait() else: progress = SilentProgress() ret = UnthreadedAlgorithmExecutor.runalg(alg, progress) if onFinish is not None and ret: onFinish(alg, progress) QApplication.restoreOverrideCursor() return alg
closed=[] exp=QgsExpression("Type='Traffic Signs' and Status='Acknowledged'") exp.prepare(scf.pendingFields()) for f in scf.getFeatures(): if exp.evaluate(f)==1: closed.append(f.id()) scf.setSelectedFeatures(closed) import processing processing.alglist() processing.alglist(“buffer”) processing.alghelp("gdalogr:buffervectors") processing.runalg("gdalogr:buffervectors",r'C:/Users/Paul/Desktop/Projected. shp',"geometry",100,False,None,False,"",r'C:/Users/Paul/Desktop/ProjectedBuffer.shp') layer = iface.addVectorLayer(r'C:\Users\Paul\Desktop\ProjectedBuffer.shp', "Buffer", "ogr") scfcity=City_or_Neighborhood searchterm=Filter progress.setInfo("Wait while I get data from the API") progress.setText("Calling API") if searchterm=="None": pagesURL="http://seeclickfix.com/api/v2/issues?per_page=100&place_url="+scf city+"&page=" url="http://seeclickfix.com/api/v2/issues?per_page=100&place_url="+scfcity else: pagesURL="http://seeclickfix.com/api/v2/issuesper_page=100&place_url="+scfc ity+"&search="+searchterm+"&page="
def runAlgorithm(algOrName, onFinish, *args, **kwargs): if isinstance(algOrName, GeoAlgorithm): alg = algOrName else: alg = Processing.getAlgorithm(algOrName) if alg is None: # fix_print_with_import print("Error: Algorithm not found\n") QgsMessageLog.logMessage( Processing.tr("Error: Algorithm {0} not found\n").format(algOrName), Processing.tr("Processing") ) return alg = alg.getCopy() if len(args) == 1 and isinstance(args[0], dict): # Set params by name and try to run the alg even if not all parameter values are provided, # by using the default values instead. setParams = [] for (name, value) in list(args[0].items()): param = alg.getParameterFromName(name) if param and param.setValue(value): setParams.append(name) continue output = alg.getOutputFromName(name) if output and output.setValue(value): continue # fix_print_with_import print("Error: Wrong parameter value %s for parameter %s." % (value, name)) QgsMessageLog.logMessage( Processing.tr("Error: Wrong parameter value {0} for parameter {1}.").format(value, name), Processing.tr("Processing"), ) ProcessingLog.addToLog( ProcessingLog.LOG_ERROR, Processing.tr("Error in %s. Wrong parameter value %s for parameter %s.") % (alg.name, value, name), ) return # fill any missing parameters with default values if allowed for param in alg.parameters: if param.name not in setParams: if not param.setDefaultValue(): # fix_print_with_import print("Error: Missing parameter value for parameter %s." % param.name) QgsMessageLog.logMessage( Processing.tr("Error: Missing parameter value for parameter {0}.").format(param.name), Processing.tr("Processing"), ) ProcessingLog.addToLog( ProcessingLog.LOG_ERROR, Processing.tr("Error in %s. Missing parameter value for parameter %s.") % (alg.name, param.name), ) return else: if len(args) != alg.getVisibleParametersCount() + alg.getVisibleOutputsCount(): # fix_print_with_import print("Error: Wrong number of parameters") QgsMessageLog.logMessage( Processing.tr("Error: Wrong number of parameters"), Processing.tr("Processing") ) processing.alghelp(algOrName) return i = 0 for param in alg.parameters: if not param.hidden: if not param.setValue(args[i]): # fix_print_with_import print("Error: Wrong parameter value: " + str(args[i])) QgsMessageLog.logMessage( Processing.tr("Error: Wrong parameter value: ") + str(args[i]), Processing.tr("Processing") ) return i = i + 1 for output in alg.outputs: if not output.hidden: if not output.setValue(args[i]): # fix_print_with_import print("Error: Wrong output value: " + str(args[i])) QgsMessageLog.logMessage( Processing.tr("Error: Wrong output value: ") + str(args[i]), Processing.tr("Processing") ) return i = i + 1 msg = alg._checkParameterValuesBeforeExecuting() if msg: # fix_print_with_import print("Unable to execute algorithm\n" + str(msg)) QgsMessageLog.logMessage( Processing.tr("Unable to execute algorithm\n{0}").format(msg), Processing.tr("Processing") ) return if not alg.checkInputCRS(): print("Warning: Not all input layers use the same CRS.\n" + "This can cause unexpected results.") QgsMessageLog.logMessage( Processing.tr("Warning: Not all input layers use the same CRS.\nThis can cause unexpected results."), Processing.tr("Processing"), ) # Don't set the wait cursor twice, because then when you # restore it, it will still be a wait cursor. overrideCursor = False if iface is not None: cursor = QApplication.overrideCursor() if cursor is None or cursor == 0: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) overrideCursor = True elif cursor.shape() != Qt.WaitCursor: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) overrideCursor = True progress = None if kwargs is not None and "progress" in list(kwargs.keys()): progress = kwargs["progress"] elif iface is not None: progress = MessageBarProgress(alg.name) ret = runalg(alg, progress) if ret: if onFinish is not None: onFinish(alg, progress) else: QgsMessageLog.logMessage( Processing.tr("There were errors executing the algorithm."), Processing.tr("Processing") ) if overrideCursor: QApplication.restoreOverrideCursor() if isinstance(progress, MessageBarProgress): progress.close() return alg
def shp2json(self, BoundaryFile, BoundaryQuery, PopulationFile, datafile, OutputFileName): exp = BoundaryQuery # print exp fileShape = BoundaryFile fileInfoShape = QFileInfo(fileShape) fileShapeName = fileInfoShape.fileName() layer = iface.addVectorLayer(fileShape, fileShapeName, "ogr") if layer.isValid(): subset = exp layer.setSubsetString(subset) fileCSV = PopulationFile fileInfoCSV = QFileInfo(fileCSV) fileNm = fileInfoCSV.fileName() if fileCSV == "": return uri = "file:" + fileCSV + "?delimiter=%s" % (";") # print uri cvslayer = iface.addVectorLayer(uri, fileNm, "delimitedtext") if cvslayer.isValid(): subset = exp cvslayer.setSubsetString(subset) joinInfo = QgsVectorJoinInfo() joinInfo.targetFieldName = 'name' joinInfo.joinFieldName = 'District' joinInfo.memoryCache = True joinInfo.joinLayerId = cvslayer.id() # print joinInfo.joinLayerId layer.addJoin(joinInfo) # iface.addVectorLayer(layer) fileGeoJsonInfo = QFileInfo(OutputFileName) fileGeoJsonDir = OutputFileName[:len(OutputFileName) - len(fileGeoJsonInfo.fileName())] fileGeoJson = fileGeoJsonDir + fileNm[:len(fileNm) - 4] + ".geojson" if fileGeoJson == "": return qgis.core.QgsVectorFileWriter.writeAsVectorFormat( layer, fileGeoJson, 'utf-8', layer.crs(), 'GeoJson') # fileCSV=PopulationFile # fileInfoCSV=QFileInfo(fileCSV) # fileNm=fileInfoCSV.fileName() ## iface.addVectorLayer(layer) # fileGeoJson= fileGeoJsonDir+fileNm[:len(fileNm)-4]+".geojson" # if fileGeoJson=="": # return # fileGeoJsonInfo=QFileInfo(fileGeoJson) # qgis.core.QgsVectorFileWriter.writeAsVectorFormat(layer, fileGeoJson, 'utf-8', layer.crs(), 'GeoJson') print "Made geojson File1" firstRes = QgsVectorLayer(fileGeoJson, fileGeoJsonInfo.fileName(), "ogr") if not firstRes.isValid(): return xMax = firstRes.extent().xMaximum() + firstRes.extent().width() * 0.05 xMin = firstRes.extent().xMinimum() - firstRes.extent().width() * 0.05 yMax = firstRes.extent().yMaximum() + firstRes.extent().width() * 0.05 yMin = firstRes.extent().yMinimum() - firstRes.extent().width() * 0.05 rect = QgsRectangle(xMin, yMin, xMax, yMax) maskLayer = QgsVectorLayer("Polygon", "mask", "memory") QgsMapLayerRegistry.instance().addMapLayer(maskLayer) feature = QgsFeature() feature.setGeometry(QgsGeometry.fromRect(rect)) maskLayer.startEditing() maskLayer.addFeature(feature) maskLayer.commitChanges() fileCSV1 = datafile fileInfoCSV1 = QFileInfo(fileCSV1) # print fileCSV1 if fileCSV1 == "": return uri1 = "file:" + fileCSV1 + "?delimiter=%s&xField=%s&yField=%s" % ( ",", "LNG", "LAT") cvslayer1 = iface.addVectorLayer(uri1, fileInfoCSV1.fileName(), "delimitedtext") # print cvslayer1.featureCount() filePath1 = OutputFileName if filePath1 == "": return filePathInfo = QFileInfo(filePath1) # print filePath1 sPath = filePathInfo.filePath() sName = filePathInfo.fileName() a = len(sPath) - len(sName) b = len(sName) - 8 s1 = sPath[:a] clippedPath = s1 + sName[:b] + "_Clipped.shp" clippedName = sName[:b] + "_Clipped.shp" # print clippedPath print "Start Clipping" processing.runalg("qgis:clip", cvslayer1, maskLayer, clippedPath) print "End Clipping" # voronoiPath = s1 + sName[:b] + "_Voronoi.shp" voronoiName = sName[:b] + "_Voronoi.shp" clippedLayer = QgsVectorLayer(clippedPath, clippedName, "ogr") print "Start the voronoi polygons" processing.runalg("qgis:voronoipolygons", clippedLayer, voronoiPath) print "End the voronoi polygons" voronoiLayer = QgsVectorLayer(voronoiPath, voronoiName, "ogr") res = voronoiLayer.dataProvider().addAttributes( [QgsField("category", QVariant.String)]) if res == "False": return voronoiLayer1 = QgsVectorLayer(voronoiPath, voronoiName, "ogr") iter = voronoiLayer1.getFeatures() dissolveFieldName0 = fileInfoCSV1.fileName() dissolveFieldNameLen = len(dissolveFieldName0) - 4 dissolveFieldName = dissolveFieldName0[:dissolveFieldNameLen] print dissolveFieldName dissolveFieldOutputName = "category" idx1 = voronoiLayer1.fieldNameIndex(dissolveFieldName) idx2 = voronoiLayer1.fieldNameIndex(dissolveFieldOutputName) print idx1, idx2 maxValue = -999999999999 minValue = 999999999999 # print str(minValue) for feature in iter: value1 = feature.attributes()[idx1] if value1 != NULL: maxValue = max(maxValue, value1) minValue = min(minValue, value1) stage = (maxValue - minValue) / 5 a1 = minValue a2 = a1 + stage a3 = a2 + stage a4 = a3 + stage a5 = a4 + stage a6 = maxValue count = 0 iter1 = voronoiLayer1.getFeatures() # print voronoiLayer1.featureCount() # print str(stage),a6 # proper=QVariant.String progressMessageBar = iface.messageBar().createMessage( "Adding the value in category filed...") progress = QProgressBar() progress.setMaximum(voronoiLayer1.featureCount()) progress.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) progressMessageBar.layout().addWidget(progress) iface.messageBar().pushWidget(progressMessageBar, iface.messageBar().INFO) voronoiLayer1.startEditing() for feature1 in iter1: value1 = feature1.attributes()[idx1] if a1 <= value1 < a2: proper = str(a1) + "-" + str(a2) elif a2 <= value1 < a3: proper = str(a2) + "-" + str(a3) elif a3 <= value1 < a4: proper = str(a3) + "-" + str(a4) elif a4 <= value1 < a5: proper = str(a4) + "-" + str(a5) elif a5 <= value1 <= a6: proper = str(a5) + "-" + str(a6) else: proper = "" voronoiLayer1.changeAttributeValue(count, idx2, proper) count += 1 progress.setValue(count) # print "count:", count iface.messageBar().clearWidgets() voronoiLayer1.commitChanges() voronoiLayer2 = QgsVectorLayer(voronoiPath, voronoiName, "ogr") dissolvePath = s1 + sName[:b] + "_Dissolve.shp" dissolveName = sName[:b] + "_Dissolve.shp" # print dissolvePath processing.alglist("Dissolve") processing.alghelp("qgis:dissolve") print "Start Dissolving" processing.runalg("qgis:dissolve", voronoiLayer2, False, "category", dissolvePath) print "End Dissolving" dissolveLayer = QgsVectorLayer(dissolvePath, dissolveName, "ogr") fInfo = QFileInfo(dissolvePath) resultClipName = fInfo.fileName() resultClipPath = dissolvePath[:len(dissolvePath) - len(resultClipName)] resultClipName = resultClipName[:len(resultClipName) - 4] + "Clip.shp" resultClipPath = resultClipPath + resultClipName print "Start Clipping" processing.runalg("qgis:clip", dissolveLayer, firstRes, resultClipPath) print "End Clipping" endLayer = QgsVectorLayer(resultClipPath, resultClipName, "ogr") fileGeoJson1 = OutputFileName if fileGeoJson1 == "": return fileGeoJsonInfo1 = QFileInfo(fileGeoJson1) qgis.core.QgsVectorFileWriter.writeAsVectorFormat( endLayer, fileGeoJson1, 'utf-8', endLayer.crs(), 'GeoJson') print "Made geojson File2" # jsonLayer1 = iface.addVectorLayer(fileGeoJson, fileGeoJsonInfo.fileName(), "ogr") jsonLayer2 = iface.addVectorLayer(fileGeoJson1, fileGeoJsonInfo1.fileName(), "ogr")
def runAlgorithm(algOrName, onFinish, *args): if isinstance(algOrName, GeoAlgorithm): alg = algOrName else: alg = Processing.getAlgorithm(algOrName) if alg is None: print 'Error: Algorithm not found\n' return alg = alg.getCopy() if len(args) == 1 and isinstance(args[0], dict): # Set params by name and try to run the alg even if not all parameter values are provided, # by using the default values instead. setParams = [] for (name, value) in args[0].items(): param = alg.getParameterFromName(name) if param and param.setValue(value): setParams.append(name) continue output = alg.getOutputFromName(name) if output and output.setValue(value): continue print 'Error: Wrong parameter value %s for parameter %s.' \ % (value, name) ProcessingLog.addToLog(ProcessingLog.LOG_ERROR, Processing.tr('Error in %s. Wrong parameter value %s for parameter %s.') \ % (alg.name, value, name)) return # fill any missing parameters with default values if allowed for param in alg.parameters: if param.name not in setParams: if not param.setValue(None): print ('Error: Missing parameter value for parameter %s.' % (param.name)) ProcessingLog.addToLog(ProcessingLog.LOG_ERROR, Processing.tr('Error in %s. Missing parameter value for parameter %s.') \ % (alg.name, param.name)) return else: if len(args) != alg.getVisibleParametersCount() \ + alg.getVisibleOutputsCount(): print 'Error: Wrong number of parameters' processing.alghelp(algOrName) return i = 0 for param in alg.parameters: if not param.hidden: if not param.setValue(args[i]): print 'Error: Wrong parameter value: ' \ + unicode(args[i]) return i = i + 1 for output in alg.outputs: if not output.hidden: if not output.setValue(args[i]): print 'Error: Wrong output value: ' + unicode(args[i]) return i = i + 1 msg = alg.checkParameterValuesBeforeExecuting() if msg: print 'Unable to execute algorithm\n' + msg return if not alg.checkInputCRS(): print 'Warning: Not all input layers use the same CRS.\n' \ + 'This can cause unexpected results.' if iface is not None: # Don't set the wait cursor twice, because then when you # restore it, it will still be a wait cursor. cursor = QApplication.overrideCursor() if cursor is None or cursor == 0: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) elif cursor.shape() != Qt.WaitCursor: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) progress = None if iface is not None : progress = MessageBarProgress() ret = runalg(alg, progress) if onFinish is not None and ret: onFinish(alg, progress) if iface is not None: QApplication.restoreOverrideCursor() progress.close() return alg
# -*- coding: utf-8 -*- #importar las funciones del procesamiento import processing #ahora necesitamos saber el algoritmo a usar #para ello usamos el método alglist() #si introduces alglist() te salen todos los métodos pero #si pones entre los paréwntesis algún nombre, te hace el filtro processing.alglist('difference') processing.alghelp('qgis:difference') #capas de entrada layer_ciudades =r'E:\CURSO_PYQGIS\CAPAS\ciudades.shp' layer_z_estudio = r'E:\CURSO_PYQGIS\CAPAS\zona_estudio.shp' layer_ciudades_fuera = r'E:\CURSO_PYQGIS\CAPAS_PROCESADAS\ciudades_fuera.shp' #proceso: processing.runalg('qgis:difference',layer_ciudades,layer_z_estudio,True,layer_ciudades_fuera) #carga capa a la TOC: layer_ciudades_fuera = QgsVectorLayer(r'E:\CURSO_PYQGIS\CAPAS_PROCESADAS\ciudades_fuera.shp', 'layer_ciudades_fuera', 'ogr') QgsMapLayerRegistry.instance().addMapLayer(layer_ciudades_fuera)
def runAlgorithm(algOrName, onFinish, *args, **kwargs): if isinstance(algOrName, GeoAlgorithm): alg = algOrName else: alg = Processing.getAlgorithm(algOrName) if alg is None: # fix_print_with_import print('Error: Algorithm not found\n') QgsMessageLog.logMessage( Processing.tr('Error: Algorithm {0} not found\n').format( algOrName), Processing.tr("Processing")) return alg = alg.getCopy() if len(args) == 1 and isinstance(args[0], dict): # Set params by name and try to run the alg even if not all parameter values are provided, # by using the default values instead. setParams = [] for (name, value) in args[0].items(): param = alg.getParameterFromName(name) if param and param.setValue(value): setParams.append(name) continue output = alg.getOutputFromName(name) if output and output.setValue(value): continue # fix_print_with_import print('Error: Wrong parameter value %s for parameter %s.' % (value, name)) QgsMessageLog.logMessage( Processing.tr( 'Error: Wrong parameter value {0} for parameter {1}.'). format(value, name), Processing.tr("Processing")) ProcessingLog.addToLog( ProcessingLog.LOG_ERROR, Processing. tr('Error in %s. Wrong parameter value %s for parameter %s.' ) % (alg.name, value, name)) return # fill any missing parameters with default values if allowed for param in alg.parameters: if param.name not in setParams: if not param.setDefaultValue(): # fix_print_with_import print( 'Error: Missing parameter value for parameter %s.' % param.name) QgsMessageLog.logMessage( Processing. tr('Error: Missing parameter value for parameter {0}.' ).format(param.name), Processing.tr("Processing")) ProcessingLog.addToLog( ProcessingLog.LOG_ERROR, Processing. tr('Error in %s. Missing parameter value for parameter %s.' ) % (alg.name, param.name)) return else: if len(args) != alg.getVisibleParametersCount( ) + alg.getVisibleOutputsCount(): # fix_print_with_import print('Error: Wrong number of parameters') QgsMessageLog.logMessage( Processing.tr('Error: Wrong number of parameters'), Processing.tr("Processing")) processing.alghelp(algOrName) return i = 0 for param in alg.parameters: if not param.hidden: if not param.setValue(args[i]): # fix_print_with_import print('Error: Wrong parameter value: ' + unicode(args[i])) QgsMessageLog.logMessage( Processing.tr('Error: Wrong parameter value: ') + unicode(args[i]), Processing.tr("Processing")) return i = i + 1 for output in alg.outputs: if not output.hidden: if not output.setValue(args[i]): # fix_print_with_import print('Error: Wrong output value: ' + unicode(args[i])) QgsMessageLog.logMessage( Processing.tr('Error: Wrong output value: ') + unicode(args[i]), Processing.tr("Processing")) return i = i + 1 msg = alg._checkParameterValuesBeforeExecuting() if msg: # fix_print_with_import print('Unable to execute algorithm\n' + unicode(msg)) QgsMessageLog.logMessage( Processing.tr('Unable to execute algorithm\n{0}').format(msg), Processing.tr("Processing")) return if not alg.checkInputCRS(): print('Warning: Not all input layers use the same CRS.\n' + 'This can cause unexpected results.') QgsMessageLog.logMessage( Processing. tr('Warning: Not all input layers use the same CRS.\nThis can cause unexpected results.' ), Processing.tr("Processing")) # Don't set the wait cursor twice, because then when you # restore it, it will still be a wait cursor. overrideCursor = False if iface is not None: cursor = QApplication.overrideCursor() if cursor is None or cursor == 0: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) overrideCursor = True elif cursor.shape() != Qt.WaitCursor: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) overrideCursor = True progress = None if kwargs is not None and "progress" in kwargs.keys(): progress = kwargs["progress"] elif iface is not None: progress = MessageBarProgress(alg.name) ret = runalg(alg, progress) if ret: if onFinish is not None: onFinish(alg, progress) else: QgsMessageLog.logMessage( Processing.tr("There were errors executing the algorithm."), Processing.tr("Processing")) if overrideCursor: QApplication.restoreOverrideCursor() if isinstance(progress, MessageBarProgress): progress.close() return alg
from timeit import default_timer as timer import errno def make_sure_path_exists(path): try: os.makedirs(path) except OSError as exception: if exception.errno != errno.EEXIST: raise # Debug model info print "### model.py ### Algorithm help and options for model" qgis_model_name = "modeler:example_analysis_linux_v3.2" processing.alghelp(qgis_model_name) processing.algoptions(qgis_model_name) print QgsApplication.showSettings() print "### model.py ### QGIS model prepared, logging to file %s" % filename # Run model inputimage_pre = os.path.join(os.environ['QGIS_WORKSPACE'], "data/pre_conflict.tif") inputimage_post = os.path.join(os.environ['QGIS_WORKSPACE'], "data/post_conflict.tif") output_directory = os.path.join( os.environ['QGIS_RESULT'], datetime.datetime.now().strftime("%Y%m%d-%H%M%S")) make_sure_path_exists(output_directory)