def parse_processing_algorithms(arg=None): """Parse available processing algorithms from alglist()'s console output""" with GetStdOut() as algs: processing.alglist(arg) # parse string into description/name pairs and remove blank lines # FIXME algorithms might have a -> sequence in their description # (grass:v.out.pov and grass7:v.out.pov in particular) algs = [re.split('-+>', alg, maxsplit=1) for alg in algs if alg] # turn into dictionary return {a[1]: a[0] for a in algs}
def run_script(iface): #time whole thing start = time.time() print(processing.alglist('ftools')) os.chdir("C:/Data/BuildingHeight_CEDA") filez = [] namez = [] #test with unzippedTestCopy, just a sample #for root, dirnames, filenames in os.walk('unzippedTestCopy'): #Get folder names with shapefiles in for root, dirnames, filenames in os.walk('Scotland'): for filename in fnmatch.filter(filenames, '*.shp'): filez.append(root + "/" + filename) namez.append(filename) #folders.append(root) #keep unique folder names by converting list to set #for ff in filez: for i in range(0, len(filez)): if i != 2: continue print filez[i] print namez[i] lyr = QgsVectorLayer(filez[i], 'ceda', 'ogr') print(lyr.isValid()) QgsMapLayerRegistry.instance().addMapLayers([lyr])
def run_script(iface): #time whole thing start = time.time() print(processing.alglist('ftools')) os.chdir("C:/Data/BuildingHeight_CEDA") filez = [] namez = [] #test with unzippedTestCopy, just a sample #for root, dirnames, filenames in os.walk('unzippedTestCopy'): #Get folder names with shapefiles in for root, dirnames, filenames in os.walk('Scotland'): for filename in fnmatch.filter(filenames, '*.shp'): filez.append(root + "/" + filename) namez.append(filename) #folders.append(root) #keep unique folder names by converting list to set #for ff in filez: for i in range(0,len(filez)): if i != 2: continue print filez[i] print namez[i] lyr = QgsVectorLayer(filez[i],'ceda','ogr') print(lyr.isValid()) QgsMapLayerRegistry.instance().addMapLayers([lyr])
from PyQt4.QtCore import QSettings, QTranslator, qVersion, QCoreApplication from PyQt4.QtGui import QAction, QIcon, QFileDialog # Initialize Qt resources from file resources.py import resources # Import the code for the dialog from clipdirectoryplugin_dialog import ClipDirectoryPluginDialog import os.path from os import listdir from os.path import isfile, join from qgis.core import QgsVectorLayer, QgsMapLayerRegistry, QgsMapLayer import ntpath import processing from qgis.utils import iface from qgis.gui import QgsMessageBar processing.alglist("clip") class ClipDirectoryPlugin: """QGIS Plugin Implementation.""" def __init__(self, iface): """Constructor. :param iface: An interface instance that will be passed to this class which provides the hook by which you can manipulate the QGIS application at run time. :type iface: QgsInterface """ # Save reference to the QGIS interface self.iface = iface # initialize plugin 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('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 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")
from qgis.PyQt.QtWidgets import * iface.mapCanvas().setSelectionColor( QColor("red") ) scf.setSelectedFeatures([100]) 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":
def run_script(iface): def GetFeaturesInBuffer(inputbuff, layer, newlayername, spatialindex = 0): if spatialindex != 0: print 'Using spatial index...' #Use spatial index made above to get bounding box of housing data quickly #Before subsetting ids = spatialindex.intersects(inputbuff.geometry().boundingBox()) #Use those IDs to make a new layer box = QgsVectorLayer('Point?crs=EPSG:27700', newlayername, 'memory') pr = box.dataProvider() #f = houses. #give new layer matching fields so the feature addition keeps the original values pr.addAttributes(layer.fields()) box.updateFields() #Get the features in the bounding box by feature id that we should got from the spatial index check #http://gis.stackexchange.com/questions/130439/how-to-efficiently-access-the-features-returned-by-qgsspatialindex request = QgsFeatureRequest() request.setFilterFids(ids) subset = layer.getFeatures(request) blob = [feature for feature in subset] #Add those features to housesInBox layer pr.addFeatures(blob) #replace input layer with box. Which should work with function scope, right? #layer reference is pointer to original at this level, can be overwritten... layer = box featuresInBuffer = QgsVectorLayer('Point?crs=EPSG:27700', newlayername, 'memory') pr = featuresInBuffer.dataProvider() # print(type(layer.fields())) #give new layer matching fields so the feature addition keeps the original values pr.addAttributes(layer.fields()) featuresInBuffer.updateFields() #So let's use geometry intersect instead. # for feature in housesInBox.getFeatures(): # if feature.geometry().intersects(inputbuff): # pr.addFeatures([feature]) #should be 433 points... yup! #print(housesInBuffer.featureCount()) #Now can I do that in one line? Yup! features = [feature for feature in layer.getFeatures() if feature.geometry().intersects(inputbuff.geometry())] print('Number of features in this buffer: ' + str(len(features))) # print(type(features)) # print(type(features[0])) pr.addFeatures(features) #check if features have orig attributes... #for ft in features: # print('feat: ' + ft.attributes()[1]) return(featuresInBuffer) #################### ##################### #time whole thing start = time.time() print(os.chdir('C:/Data/WindFarmViewShed')) print(processing.alglist('line')) #Load from CSV #Relative uri paths nope! uri = "file:///C:/Data/WindFarmViewShed/ViewshedPython/Data/turbinesFinal_reducedColumns.csv?type=csv&xField=Feature.Easting&yField=Feature.Northing&spatialIndex=no&subsetIndex=no&watchFile=no&crs=EPSG:27700" #run on pre-selected subset #uri = "file:///C:/Data/WindFarmViewShed/ViewshedPython/Data/turbines_subset.csv?type=csv&xField=Feature.Easting&yField=Feature.Northing&spatialIndex=no&subsetIndex=no&watchFile=no&crs=EPSG:27700" turbines = QgsVectorLayer(uri,'turbinescsv','delimitedtext') print(turbines.isValid()) #turbines = lyr ###################### #load houses #houses = QgsVectorLayer('C:/Data/WindFarmViewShed/Tests/PythonTests/testData/rawGeocodedNewRoS2.shp','houses','ogr') #print(houses.isValid()) #Load from CSV #uri = "file:///C:/Data/WindFarmViewShed/ViewshedPython/Data/geocodedOldNewRoS.csv?type=csv&xField=newRoS_eastings&yField=newRoS_northings&spatialIndex=no&subsetIndex=no&watchFile=no&crs=EPSG:27700" uri = "file:///C:/Data/WindFarmViewShed/ViewshedPython/Data/houses_finalMay2016.csv?type=csv&xField=eastingsFinal&yField=northingsFinal&spatialIndex=no&subsetIndex=no&watchFile=no&crs=EPSG:27700" houses = QgsVectorLayer(uri,'housesJavaDataPrep','delimitedtext') print(houses.isValid()) # # for field in houses.fields(): # # print(field.typeName()) # # houses.updateExtents() # # QgsMapLayerRegistry.instance().addMapLayers([houses]) #CREATE SPATIAL INDEX FOR HOUSING DATA #make spatial index of housing points - use to quickly reduce points for PiP test #To buffer bounding box #Adapted from #http://nathanw.net/2013/01/04/using-a-qgis-spatial-index-to-speed-up-your-code/ before = time.time() print('Starting spatial index...') #dictionary comprehension. e.g. http://www.diveintopython3.net/comprehensions.html #Creates dictionary of IDs and their qgsFeatures. Nice! allfeatures = {feature.id(): feature for (feature) in houses.getFeatures()} # print(type(allfeatures))#dict # print(type(allfeatures[1111]))#qgis._core.QgsFeature index = QgsSpatialIndex() map(index.insertFeature, allfeatures.values()) print('Spatial index done: ' + str(time.time() - before)) ###### # GET THE TWO POLYGON LAYERS TO INTERSECT LINES OF SIGHT WITH mastermapGrid = QgsVectorLayer( 'C:/Data/WindFarmViewShed/QGIS/ReportOutputs/BH_mastermap_grid.shp', 'mastermapGrid','ogr') print(mastermapGrid.isValid()) #Haven't made this yet # CEDApolygons = QgsVectorLayer( # 'C:/Data/WindFarmViewShed/QGIS/ReportOutputs/.shp', # 'CEDApolygons','ogr') # print(CEDApolygons.isValid()) # ##################### # # Cycle over 15km buffers for turbines geometryanalyzer = QgsGeometryAnalyzer() geometryanalyzer.buffer(turbines, # 'Data/temp/15kmBuffer.shp', 'ViewShedPython/Data/QGIS_processing/15kmTurbineBuffer.shp', # 'ViewShedPython/DataQGIS_processing/15kmBuffer' + str (buffr.id()) + '.shp', 15000, False, False, -1) #viewBuff = 0 viewBuff = QgsVectorLayer( # 'Data/temp/15kmBuffer.shp', 'ViewShedPython/Data/QGIS_processing/15kmTurbineBuffer.shp', 'viewbuffer','ogr') print(viewBuff.isValid()) viewBuff.updateExtents() QgsMapLayerRegistry.instance().addMapLayers([viewBuff]) # #USE VIEWBUFF TO SUBSET HOUSES #Test on one or two #Get a single turbine - gosh, isn't that terse request = QgsFeatureRequest() request.setFilterFids([2500]) subset = viewBuff.getFeatures(request) # selection = turbines.getFeatures(QgsFeatureRequest().setFilterExpression(u'"index" = 2000')) housesInBuffer = GetFeaturesInBuffer(subset.next(), houses, 'housesInBuffer', index) #just load subset for testing for now # housesInBuffer = QgsVectorLayer( # 'C:/Data/temp/QGIS/subsetHouses.shp', # 'turbines','ogr') # print(housesInBuffer.isValid()) #housesInBuffer.updateExtents() #QgsMapLayerRegistry.instance().addMapLayers([housesInBuffer]) # for buff in viewBuff.getFeatures(): # housesInBuffer = GetFeaturesInBuffer(buff, houses, 'housesInBuffer', 1) #make an empty line shapefile linez = QgsVectorLayer('LineString?crs=EPSG:27700', 'lines','memory') print(linez.isValid()) vpr = linez.dataProvider() vpr.addAttributes([QgsField("House",QVariant.String)]) linez.updateFields() #Make a line between each house and this within-15km turbine for house in housesInBuffer.getFeatures(): fts = turbines.getFeatures() turb = fts.next() #while using specific id request = QgsFeatureRequest() request.setFilterFids([2500]) subset = turbines.getFeatures(request) turb = subset.next() points = [turb.geometry().asPoint(),house.geometry().asPoint()] line = QgsGeometry.fromPolyline(points) #Make sure new feature has fields of the linez layer fields = vpr.fields() f = QgsFeature(fields) f.setGeometry(line) #print house.attributes()[1] f['House'] = house.attributes()[1] vpr.addFeatures([f]) linez.updateExtents() #Needs to be added as layer to be used in algorithm? Bah! QgsMapLayerRegistry.instance().addMapLayers([linez]) #See if lines cross any areas where there could be building height data processing.runalg('saga:linepolygonintersection', linez, mastermapGrid, 1, "C:/Data/temp/QGIS/polylinetest.csv")
def run_script(iface): def GetFeaturesInBuffer(inputbuff, layer, newlayername, spatialindex=0): if spatialindex != 0: print "Using spatial index..." # Use spatial index made above to get bounding box of housing data quickly # Before subsetting ids = spatialindex.intersects(inputbuff.geometry().boundingBox()) # Use those IDs to make a new layer box = QgsVectorLayer("Point?crs=EPSG:27700", newlayername, "memory") pr = box.dataProvider() # f = houses. # give new layer matching fields so the feature addition keeps the original values pr.addAttributes(layer.fields()) box.updateFields() # Get the features in the bounding box by feature id that we should got from the spatial index check # http://gis.stackexchange.com/questions/130439/how-to-efficiently-access-the-features-returned-by-qgsspatialindex request = QgsFeatureRequest() request.setFilterFids(ids) subset = layer.getFeatures(request) blob = [feature for feature in subset] # Add those features to housesInBox layer pr.addFeatures(blob) # replace input layer with box. Which should work with function scope, right? # layer reference is pointer to original at this level, can be overwritten... layer = box featuresInBuffer = QgsVectorLayer("Point?crs=EPSG:27700", newlayername, "memory") pr = featuresInBuffer.dataProvider() # print(type(layer.fields())) # give new layer matching fields so the feature addition keeps the original values pr.addAttributes(layer.fields()) featuresInBuffer.updateFields() # So let's use geometry intersect instead. # for feature in housesInBox.getFeatures(): # if feature.geometry().intersects(inputbuff): # pr.addFeatures([feature]) # should be 433 points... yup! # print(housesInBuffer.featureCount()) # Now can I do that in one line? Yup! features = [feature for feature in layer.getFeatures() if feature.geometry().intersects(inputbuff.geometry())] print ("Number of features in this buffer: " + str(len(features))) # print(type(features)) # print(type(features[0])) pr.addFeatures(features) # check if features have orig attributes... # for ft in features: # print('feat: ' + ft.attributes()[1]) return featuresInBuffer #################### ##################### # time whole thing start = time.time() print (os.chdir("C:/Data/WindFarmViewShed")) print (processing.alglist("line")) # Load from CSV # Relative uri paths nope! uri = "file:///C:/Data/WindFarmViewShed/ViewshedPython/Data/turbinesFinal_reducedColumns.csv?type=csv&xField=Feature.Easting&yField=Feature.Northing&spatialIndex=no&subsetIndex=no&watchFile=no&crs=EPSG:27700" # run on pre-selected subset # uri = "file:///C:/Data/WindFarmViewShed/ViewshedPython/Data/turbines_subset.csv?type=csv&xField=Feature.Easting&yField=Feature.Northing&spatialIndex=no&subsetIndex=no&watchFile=no&crs=EPSG:27700" turbines = QgsVectorLayer(uri, "turbinescsv", "delimitedtext") print (turbines.isValid()) # turbines = lyr ###################### # load houses # houses = QgsVectorLayer('C:/Data/WindFarmViewShed/Tests/PythonTests/testData/rawGeocodedNewRoS2.shp','houses','ogr') # print(houses.isValid()) # Load from CSV # uri = "file:///C:/Data/WindFarmViewShed/ViewshedPython/Data/geocodedOldNewRoS.csv?type=csv&xField=newRoS_eastings&yField=newRoS_northings&spatialIndex=no&subsetIndex=no&watchFile=no&crs=EPSG:27700" uri = "file:///C:/Data/WindFarmViewShed/ViewshedPython/Data/houses_finalMay2016.csv?type=csv&xField=eastingsFinal&yField=northingsFinal&spatialIndex=no&subsetIndex=no&watchFile=no&crs=EPSG:27700" houses = QgsVectorLayer(uri, "housesJavaDataPrep", "delimitedtext") print (houses.isValid()) # # for field in houses.fields(): # # print(field.typeName()) # # houses.updateExtents() # # QgsMapLayerRegistry.instance().addMapLayers([houses]) # CREATE SPATIAL INDEX FOR HOUSING DATA # make spatial index of housing points - use to quickly reduce points for PiP test # To buffer bounding box # Adapted from # http://nathanw.net/2013/01/04/using-a-qgis-spatial-index-to-speed-up-your-code/ before = time.time() print ("Starting spatial index...") # dictionary comprehension. e.g. http://www.diveintopython3.net/comprehensions.html # Creates dictionary of IDs and their qgsFeatures. Nice! allfeatures = {feature.id(): feature for (feature) in houses.getFeatures()} # print(type(allfeatures))#dict # print(type(allfeatures[1111]))#qgis._core.QgsFeature index = QgsSpatialIndex() map(index.insertFeature, allfeatures.values()) print ("Spatial index done: " + str(time.time() - before)) ###### # GET THE TWO POLYGON LAYERS TO INTERSECT LINES OF SIGHT WITH mastermapGrid = QgsVectorLayer( "C:/Data/WindFarmViewShed/QGIS/ReportOutputs/BH_mastermap_grid.shp", "mastermapGrid", "ogr" ) print (mastermapGrid.isValid()) # Haven't made this yet # CEDApolygons = QgsVectorLayer( # 'C:/Data/WindFarmViewShed/QGIS/ReportOutputs/.shp', # 'CEDApolygons','ogr') # print(CEDApolygons.isValid()) # ##################### # # Cycle over 15km buffers for turbines geometryanalyzer = QgsGeometryAnalyzer() geometryanalyzer.buffer( turbines, # 'Data/temp/15kmBuffer.shp', "ViewShedPython/Data/QGIS_processing/15kmTurbineBuffer.shp", # 'ViewShedPython/DataQGIS_processing/15kmBuffer' + str (buffr.id()) + '.shp', 15000, False, False, -1, ) # viewBuff = 0 viewBuff = QgsVectorLayer( # 'Data/temp/15kmBuffer.shp', "ViewShedPython/Data/QGIS_processing/15kmTurbineBuffer.shp", "viewbuffer", "ogr", ) print (viewBuff.isValid()) viewBuff.updateExtents() QgsMapLayerRegistry.instance().addMapLayers([viewBuff]) # #USE VIEWBUFF TO SUBSET HOUSES # Test on one or two # Get a single turbine - gosh, isn't that terse request = QgsFeatureRequest() request.setFilterFids([2500]) subset = viewBuff.getFeatures(request) # selection = turbines.getFeatures(QgsFeatureRequest().setFilterExpression(u'"index" = 2000')) housesInBuffer = GetFeaturesInBuffer(subset.next(), houses, "housesInBuffer", index) # just load subset for testing for now # housesInBuffer = QgsVectorLayer( # 'C:/Data/temp/QGIS/subsetHouses.shp', # 'turbines','ogr') # print(housesInBuffer.isValid()) # housesInBuffer.updateExtents() # QgsMapLayerRegistry.instance().addMapLayers([housesInBuffer]) # for buff in viewBuff.getFeatures(): # housesInBuffer = GetFeaturesInBuffer(buff, houses, 'housesInBuffer', 1) # make an empty line shapefile linez = QgsVectorLayer("LineString?crs=EPSG:27700", "lines", "memory") print (linez.isValid()) vpr = linez.dataProvider() vpr.addAttributes([QgsField("House", QVariant.String)]) linez.updateFields() # Make a line between each house and this within-15km turbine for house in housesInBuffer.getFeatures(): fts = turbines.getFeatures() turb = fts.next() # while using specific id request = QgsFeatureRequest() request.setFilterFids([2500]) subset = turbines.getFeatures(request) turb = subset.next() points = [turb.geometry().asPoint(), house.geometry().asPoint()] line = QgsGeometry.fromPolyline(points) # Make sure new feature has fields of the linez layer fields = vpr.fields() f = QgsFeature(fields) f.setGeometry(line) # print house.attributes()[1] f["House"] = house.attributes()[1] vpr.addFeatures([f]) linez.updateExtents() # Needs to be added as layer to be used in algorithm? Bah! QgsMapLayerRegistry.instance().addMapLayers([linez]) # See if lines cross any areas where there could be building height data processing.runalg("saga:linepolygonintersection", linez, mastermapGrid, 1, "C:/Data/temp/QGIS/polylinetest.csv")
# -*- 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)
#--- Add layer to project QgsProject.instance().addMapLayer(vlayer) #--- Add layer to project QgsMapLayerRegistry.instance().addMapLayer(vlayer) #------------------------------------------------------------------------------------------------ #----------------------------------------# #--- 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>
# ) # from processing.gui.Postprocessing import handleAlgorithmResults # # needed for open_help # from processing.tools.help import createAlgorithmHelp # # needed for qgis_session_info # from processing.algs.saga.SagaAlgorithmProvider import SagaAlgorithmProvider # from processing.algs.saga import SagaUtils # from processing.algs.grass.GrassUtils import GrassUtils # from processing.algs.grass7.Grass7Utils import Grass7Utils # from processing.algs.otb.OTBAlgorithmProvider import OTBAlgorithmProvider # from processing.algs.otb.OTBUtils import getInstalledVersion # from processing.algs.taudem.TauDEMUtils import TauDEMUtils # from osgeo import gdal # from processing.tools.system import isWindows, isMac # check if it works processing.alglist() canvas = QgsMapCanvas() layer = QgsVectorLayer("/tmp/RtmpPWMR66/points.shp", 'points', 'ogr') QgsMapLayerRegistry.instance().addMapLayer(layer) # set extent to the extent of our layer canvas.setExtent(layer.extent()) # set the map canvas layer set canvas.setLayerSet([QgsMapCanvasLayer(layer)]) canvas.resize(QSize(400, 400)) canvas.show() # well, this works # and exactly the same in R Sys.setenv(PYTHONPATH="/usr/share/qgis/python") Sys.setenv(LD_LIBRARY_PATH="/usr/lib") # setting here the QGIS_PREFIX_PATH also works instead of running it twice