def generate_unlinks(network,id_column): network_filepath=network.dataProvider().dataSourceUri() network_dir=os.path.dirname(network_filepath) network_basename=QFileInfo(network_filepath).baseName() output_path=network_dir + "/"+ network_basename +"_unlinks.shp" processing.runandload("qgis:lineintersections", network, network,id_column,id_column,output_path) Intersections = QgsVectorLayer(output_path,"Unlinks","ogr") QgsMapLayerRegistry.instance().addMapLayer(Intersections) mega_list=[] for f in network.getFeatures(): Endpoints=f.geometry().asPolyline() for i in Endpoints: mega_list.append(i) #delete points if they are endpoints of lines #keep only unlinks points_to_del=[] for f in Intersections.getFeatures(): point=f.geometry().asPoint() if point in mega_list: points_to_del.append(f.id()) Intersections.startEditing() Intersections.dataProvider().deleteFeatures(points_to_del) Intersections.commitChanges()
def run_script(iface): line = QgsVectorLayer('/home/zia/Documents/Test/QGIS_Python_Book/path/path.shp', 'Line', 'ogr') QgsMapLayerRegistry.instance().addMapLayer(line) # The following grass function cant be executed. But the same can be viewed from processing toolbox. #processing.runandload('grass:v.to.points', line, '1000', False, False, True, '435727.015026, 458285.819185, 5566442.32879, 5591754.78979', -1, 0.0001, 0, None) processing.runandload('qgis:randompointsinextent', '435727.015026, 458285.819185, 5566442.32879, 5591754.78979', 100, 100, None)
def FillHoles(self): try: processing.runandload('qgis:deleteholes', self.iface.activeLayer(), "memory: WeedingPlan") except: w = QWidget() QMessageBox.warning(w, "Message", "Cannot dissolve selected layer!")
def calculateIntersection(self): # use the buffer to cut from another layer cutter = uf.getLegendLayerByName(self.iface, "Buffers") # use the selected layer for cutting layer = self.getSelectedLayer() if cutter.featureCount() > 0: # get the intersections between the two layers intersection = processing.runandload('qgis:intersection', layer, cutter, None) intersection_layer = uf.getLegendLayerByName( self.iface, "Intersection") # prepare results layer save_path = "%s/dissolve_results.shp" % QgsProject.instance( ).homePath() # dissolve grouping by origin id dissolve = processing.runandload('qgis:dissolve', intersection_layer, False, 'id', save_path) dissolved_layer = uf.getLegendLayerByName(self.iface, "Dissolved") dissolved_layer.setLayerName('Buffer Intersection') # close intersections intermediary layer QgsMapLayerRegistry.instance().removeMapLayers( [intersection_layer.id()]) # add an 'area' field and calculate # functiona can add more than one filed, therefore names and types are lists uf.addFields(dissolved_layer, ["area"], [QtCore.QVariant.Double]) uf.updateField(dissolved_layer, "area", "$area")
def workerFinished(self, WeedingPlanLayer): self.WaitWorker = self.WaitWorker +1 if WeedingPlanLayer is not None: feature_list = WeedingPlanLayer.getFeatures() Lista = [] for feat in feature_list: Lista.append(feat) self.WeedingPlanLayerProvider.addFeatures(Lista) self.iface.messageBar().pushMessage('Weeding plan complete!') else: # notify the user that something went wrong self.iface.messageBar().pushMessage('Weeding plan aborted!', level=QgsMessageBar.CRITICAL, duration=3) #print self.WaitWorker if self.WaitWorker == 4: self.worker.deleteLater() self.thread.quit() self.thread.wait() self.thread.deleteLater() VectorLayerName = self.FieldcomboBox.itemData(self.FieldcomboBox.currentIndex()) VectorLayer = QgsMapLayerRegistry.instance().mapLayer(VectorLayerName) self.WeedingPlanLayer.updateExtents() QgsMapLayerRegistry.instance().addMapLayer(self.WeedingPlanLayer) processing.runandload("qgis:clip",self.WeedingPlanLayer , VectorLayer, 'memory: WeedingPlanAreas') QgsMapLayerRegistry.instance().removeMapLayer(self.WeedingPlanLayer.id()) del self.WeedingPlanLayer del self.WeedingPlanLayerProvider self.iface.messageBar().popWidget(self.messageBar)
def clipLayer(self): inputlayer = uf.getLegendLayerByName(self.iface, "buildings") cliplayer = uf.getLegendLayerByName(self.iface, "selected boundaries") processing.runandload("qgis:clip", inputlayer, cliplayer, "memory:clippedlayer") layer = QgsMapLayerRegistry.instance().mapLayersByName("memory:clippedlayer")[0] toc = self.iface.legendInterface() groups = toc.groups() groupIndex = groups.index(u'working files') toc.setLayerVisible(layer, True) inputlayer2 = uf.getLegendLayerByName(self.iface, "green") cliplayer = uf.getLegendLayerByName(self.iface, "selected boundaries") processing.runandload("qgis:clip", inputlayer2, cliplayer, "memory:greenlayer") layer2 = QgsMapLayerRegistry.instance().mapLayersByName("memory:greenlayer")[0] toc = self.iface.legendInterface() groups = toc.groups() groupIndex = groups.index(u'working files') # move layer to output folder toc.moveLayer(layer, groupIndex) toc.moveLayer(layer2, groupIndex) toc.setLayerVisible(layer2, True) vLayer = uf.getLegendLayerByName(self.iface, "selected boundaries") canvas = self.iface.mapCanvas() extent = vLayer.extent() canvas.setExtent(extent) mc = self.iface.mapCanvas() for layer in mc.layers(): if layer.type() == layer.VectorLayer: layer.removeSelection() mc.refresh()
def clipLayer(self): inputlayer = uf.getLegendLayerByName(self.iface, "buildings") cliplayer = uf.getLegendLayerByName(self.iface, "selected boundaries") processing.runandload("qgis:clip", inputlayer, cliplayer, "memory:clippedlayer") layer = QgsMapLayerRegistry.instance().mapLayersByName( "memory:clippedlayer")[0] toc = self.iface.legendInterface() groups = toc.groups() groupIndex = groups.index(u'working files') toc.setLayerVisible(layer, True) inputlayer2 = uf.getLegendLayerByName(self.iface, "green") cliplayer = uf.getLegendLayerByName(self.iface, "selected boundaries") processing.runandload("qgis:clip", inputlayer2, cliplayer, "memory:greenlayer") layer2 = QgsMapLayerRegistry.instance().mapLayersByName( "memory:greenlayer")[0] toc = self.iface.legendInterface() groups = toc.groups() groupIndex = groups.index(u'working files') # move layer to output folder toc.moveLayer(layer, groupIndex) toc.moveLayer(layer2, groupIndex) toc.setLayerVisible(layer2, True) vLayer = uf.getLegendLayerByName(self.iface, "selected boundaries") canvas = self.iface.mapCanvas() extent = vLayer.extent() canvas.setExtent(extent) mc = self.iface.mapCanvas() for layer in mc.layers(): if layer.type() == layer.VectorLayer: layer.removeSelection() mc.refresh()
def Dissolve(self): try: processing.runandload("qgis:dissolve",self.iface.activeLayer() , True,'', 'memory: WeedingPlan') except: w = QWidget() QMessageBox.warning(w, "Message", "Can't dissolve selected layer!")
def inwijk(self): layer = uf.getLegendLayerByName(self.iface, "Joined layer") if layer: QgsMapLayerRegistry.instance().removeMapLayers([layer]) processing.runandload( 'qgis:joinattributesbylocation', 'OneStartPoint', 'Wijk_Rott', u'within', 0, 0, '', 0, os.path.join(os.path.dirname(__file__), 'SampleData', 'Joined layer.shp'))
def calculateIntersection(self): # use the buffer to cut from another layer cutter = uf.getLegendLayerByName(self.iface, "Buffers") # use the selected layer for cutting layer = uf.getLegendLayerByName(self.iface, "green") # get the intersections between the two layers intersection = processing.runandload('qgis:intersection',layer,cutter,None) intersection_layer = uf.getLegendLayerByName(self.iface, "Intersection") # prepare results layer save_path = "%s/dissolve_results.shp" % QgsProject.instance().homePath() # dissolve grouping by origin id dissolve = processing.runandload('qgis:dissolve',intersection_layer,False,'id',save_path) dissolved_layer = uf.getLegendLayerByName(self.iface, "Dissolved") # close intersections intermediary layer """ QgsMapLayerRegistry.instance().removeMapLayers([intersection_layer.id()])""" # add an 'area' field and calculate # functiona can add more than one filed, therefore names and types are lists wanted_layer = uf.getLegendLayerByName(self.iface, "Buffers") dissolved_layer = uf.getLegendLayerByName(self.iface, "Dissolved") uf.addFields(dissolved_layer,["green_area"], [QtCore.QVariant.Double]) uf.updateField(dissolved_layer, "green_area","$area") dissolved_layer.updateFields() save_path = "%s/dissolve_results.shp" % QgsProject.instance().homePath() shp = uf.getLegendLayerByName(self.iface, "Buffers") csv = uf.getLegendLayerByName(self.iface, "Dissolved") # Set properties for the join shpField='id' csvField='id' joinObject = QgsVectorJoinInfo() joinObject.joinLayerId = csv.id() joinObject.joinFieldName = csvField joinObject.targetFieldName = shpField joinObject.memoryCache = True shp.addJoin(joinObject) # add an 'total_area' field and calculate straal = float(self.bufferLineEdit.text()) uf.addFields(wanted_layer, ["total_area"], [QtCore.QVariant.Double]) uf.updateField(wanted_layer, "total_area"," 3.14159265359 * ((%d)^2)" % straal ) # add an 'percentage_green' field and calculate uf.addFields(wanted_layer, ["green_perc"], [QtCore.QVariant.Double]) uf.updateField(wanted_layer, "green_perc","(%s /%s)* 100" % ('Dissolved_green_area', 'total_area')) layer1 = QgsMapLayerRegistry.instance().mapLayersByName("Buffers")[0] layer2 = QgsMapLayerRegistry.instance().mapLayersByName("Intersection")[0] layer3 = QgsMapLayerRegistry.instance().mapLayersByName("Dissolved")[0] toc = self.iface.legendInterface() groups = toc.groups() groupIndex2 = groups.index(u'output') groupIndex = groups.index(u'working files') # move layer to output folder toc.moveLayer(layer1, groupIndex2) toc.moveLayer(layer2, groupIndex) toc.moveLayer(layer3, groupIndex)
def count_hazard_level_per_barangay(self, infraWithHazard, brgy, brgyNames, hazardType): names0 = [] brgyDict = {} processing.runandload("qgis:joinattributesbylocation", infraWithHazard, brgy, u"intersects", 0.00000, 0, "mean", 1, "memory:") out1 = QgsMapLayerRegistry.instance().mapLayersByName("Joined layer")[0] brgyNameIndex = out1.fieldNameIndex(brgyNames) hazardTypeIndex = out1.fieldNameIndex(hazardType) features = out1.getFeatures() for f in features: try: attr = f.attributes() names0.append(str(attr[brgyNameIndex])) except IndexError: pass names = list(set(names0)) for n in names: brgyDict[n] = [0,0,0] features2 = out1.getFeatures() for f in features2: try: attr = f.attributes() brgyName = str(attr[brgyNameIndex]) hazardLevel = str(attr[hazardTypeIndex]) if hazardLevel.capitalize() == "Low": brgyDict[brgyName][0] += 1 elif hazardLevel.capitalize() == "Medium": brgyDict[brgyName][1] += 1 elif hazardLevel.capitalize() == "High": brgyDict[brgyName][2] += 1 except IndexError: pass #toRemove = QgsMapLayerRegistry.instance().mapLayersByName("Joined layer")[0] QgsMapLayerRegistry.instance().removeMapLayers([out1.id()]) return brgyDict
def calculateRoute(self): # origin and destination must be in the set of tied_points options = len(self.tied_points) if options > 1: # origin and destination are given as an index in the tied_points list origin = 0 destination = random.randint(1, options - 1) # calculate the shortest path for the given origin and destination path = uf.calculateRouteDijkstra(self.graph, self.tied_points, origin, destination) # store the route results in temporary layer called "Routes" routes_layer = uf.getLegendLayerByName(self.iface, "Routes") # create one if it doesn't exist if not routes_layer: attribs = ['id'] types = [QtCore.QVariant.String] routes_layer = uf.createTempLayer( 'Routes', 'LINESTRING', self.network_layer.crs().postgisSrid(), attribs, types) uf.loadTempLayer(routes_layer) # insert route line for route in routes_layer.getFeatures(): print route.id() uf.insertTempFeatures(routes_layer, [path], [['testing', 100.00]]) buffer = processing.runandload('qgis:fixeddistancebuffer', routes_layer, 10.0, 5, False, None)
def calculateIntersection(self): # use the buffer to cut from another layer cutter = uf.getLegendLayerByName(self.iface, "Buffers") # use the selected layer for cutting layer = self.getSelectedLayer() if cutter.featureCount() > 0: # get the intersections between the two layers intersection = processing.runandload('qgis:intersection',layer,cutter,None) intersection_layer = uf.getLegendLayerByName(self.iface, "Intersection") # prepare results layer save_path = "%s/dissolve_results.shp" % QgsProject.instance().homePath() # dissolve grouping by origin id dissolve = processing.runandload('qgis:dissolve',intersection_layer,False,'id',save_path) dissolved_layer = uf.getLegendLayerByName(self.iface, "Dissolved") # close intersections intermediary layer QgsMapLayerRegistry.instance().removeMapLayers([intersection_layer.id()]) # add an 'area' field and calculate # functiona can add more than one filed, therefore names and types are lists uf.addFields(dissolved_layer, ["area"], [QtCore.QVariant.Double]) uf.updateField(dissolved_layer, "area","$area")
def topology_check(self, directory, lyr1, lyr2, campo1, campo2, nome1, nome2, nome3, e): processing.runandload("saga:polygonselfintersection", lyr1, campo1, directory + os.sep + nome1 + ".shp") self.elab_self_intersect(nome1, campo1) self.remove_record(nome1) e.write( " Eseguito! Il file contenente le aree di self-intersection del layer '" + lyr1 + "' e' stato salvato nella directory '\\elab\\" + nome1 + ".shp'\n") processing.runandload("saga:polygonselfintersection", lyr2, campo2, directory + os.sep + nome2 + ".shp") self.elab_self_intersect(nome2, campo2) self.remove_record(nome2) e.write( " Eseguito! Il file contenente le aree di self-intersection del layer '" + lyr2 + "' e' stato salvato nella directory '\\elab\\" + nome2 + ".shp'\n") processing.runandload("saga:intersect", lyr1, lyr2, True, directory + os.sep + nome3 + ".shp") self.elab_intersect(nome3) self.remove_record(nome3) e.write( " Eseguito! Il file contenente le aree di intersezione tra '" + lyr1 + "' e '" + lyr2 + "' e' stato salvato nella directory '\\elab\\" + nome3 + ".shp'\n\n")
def calculateRoute(self): # origin and destination must be in the set of tied_points options = len(self.tied_points) if options > 1: # origin and destination are given as an index in the tied_points list origin = 0 destination = random.randint(1,options-1) # calculate the shortest path for the given origin and destination path = uf.calculateRouteDijkstra(self.graph, self.tied_points, origin, destination) # store the route results in temporary layer called "Routes" routes_layer = uf.getLegendLayerByName(self.iface, "Routes") # create one if it doesn't exist if not routes_layer: attribs = ['id'] types = [QtCore.QVariant.String] routes_layer = uf.createTempLayer('Routes','LINESTRING',self.network_layer.crs().postgisSrid(), attribs, types) uf.loadTempLayer(routes_layer) # insert route line for route in routes_layer.getFeatures(): print route.id() uf.insertTempFeatures(routes_layer, [path], [['testing',100.00]]) buffer = processing.runandload('qgis:fixeddistancebuffer',routes_layer,10.0,5,False,None)
def topology_check(self, directory, lyr1, lyr2, campo1, campo2, nome1, nome2, nome3, f, e): processing.runandload("saga:polygonselfintersection", lyr1, campo1, directory + os.sep + nome1 + ".shp") self.elab_self_intersect(nome1) self.remove_record(nome1) f.write( " Fatto! Il file contenente le auto-intersezioni del layer '" + lyr1 + "' e' stato salvato nella directory '\\allegati\\log\\analisi\\" + nome1 + ".shp'\n") e.write(" Done! File containing auto-intersections of '" + lyr1 + "' layer has been saved in '\\allegati\\log\\analisi\\" + nome1 + ".shp'\n") processing.runandload("saga:polygonselfintersection", lyr2, campo2, directory + os.sep + nome2 + ".shp") self.elab_self_intersect(nome2) self.remove_record(nome2) f.write( " Fatto! Il file contenente le auto-intersezioni del layer '" + lyr2 + "' e' stato salvato nella directory '\\allegati\\log\\analisi\\" + nome2 + ".shp'\n") e.write(" Done! File containing auto-intersections of '" + lyr2 + "' layer has been saved in '\\allegati\\log\\analisi\\" + nome2 + ".shp'\n") processing.runandload("saga:intersect", lyr1, lyr2, True, directory + os.sep + nome3 + ".shp") self.elab_intersect(nome3) self.remove_record(nome3) f.write( " Fatto! Il file contenente le intersezioni tra i layer '" + lyr1 + "' e '" + lyr2 + "' e' stato salvato nella directory '\\allegati\\log\\analisi\\" + nome3 + ".shp'\n\n") e.write(" Done! File containing intersections between '" + lyr1 + "' and '" + lyr2 + "' layers was saved in '\\allegati\\log\\analisi\\" + nome3 + ".shp'\n\n")
def identify_gap(self, e, lyr, dir_out): if lyr.wkbType() == QGis.WKBPolygon and lyr.name( ) != 'comune_progetto' or lyr.wkbType( ) == QGis.WKBMultiPolygon and lyr.name() != 'comune_progetto': if lyr.featureCount() > 0: e.write( " - Sto eseguendo il controllo relativo alla presenza di gap su '" + lyr.name() + "'...\n") output1 = dir_out + os.sep + "elab" + os.sep + lyr.name( ) + "_diss.shp" output2 = dir_out + os.sep + "elab" + os.sep + lyr.name( ) + "_fill.shp" output3 = dir_out + os.sep + "elab" + os.sep + lyr.name( ) + "_gap.shp" processing.runandload("qgis:dissolve", lyr, True, "", output1) processing.runandload("qgis:fillholes", output1, 1, output2) processing.runandload("qgis:difference", output2, output1, False, output3) try: layer_name = QgsMapLayerRegistry.instance( ).mapLayersByName("Difference")[0] except: layer_name = QgsMapLayerRegistry.instance( ).mapLayersByName("Differenza")[0] layer_name.setLayerName(lyr.name() + "_gap") layer_name.startEditing() for fc in layer_name.getFeatures( QgsFeatureRequest().setFilterExpression( "$geometry IS NULL").setSubsetOfAttributes( []).setFlags(QgsFeatureRequest.NoGeometry)): layer_name.deleteFeature(fc.id()) layer_name.commitChanges() e.write(" Eseguito! Il file contenente i gap del layer '" + lyr.name() + "' e' stato salvato nella directory '\\elab\\" + lyr.name() + "_gap.shp'\n\n")
def test_runandload(self): processing.runandload("qgis:countpointsinpolygon", polygons(), points(), "NUMPOINTS", None) layer = getfromname("Result") self.assertIsNotNone(layer)
def calculateIntersection(self): # use the buffer to cut from another layer cutter = uf.getLegendLayerByName(self.iface, "Buffers") # use the selected layer for cutting layer = uf.getLegendLayerByName(self.iface, "green") # get the intersections between the two layers intersection = processing.runandload('qgis:intersection', layer, cutter, None) intersection_layer = uf.getLegendLayerByName(self.iface, "Intersection") # prepare results layer save_path = "%s/dissolve_results.shp" % QgsProject.instance().homePath( ) # dissolve grouping by origin id dissolve = processing.runandload('qgis:dissolve', intersection_layer, False, 'id', save_path) dissolved_layer = uf.getLegendLayerByName(self.iface, "Dissolved") # close intersections intermediary layer """ QgsMapLayerRegistry.instance().removeMapLayers([intersection_layer.id()])""" # add an 'area' field and calculate # functiona can add more than one filed, therefore names and types are lists wanted_layer = uf.getLegendLayerByName(self.iface, "Buffers") dissolved_layer = uf.getLegendLayerByName(self.iface, "Dissolved") uf.addFields(dissolved_layer, ["green_area"], [QtCore.QVariant.Double]) uf.updateField(dissolved_layer, "green_area", "$area") dissolved_layer.updateFields() save_path = "%s/dissolve_results.shp" % QgsProject.instance().homePath( ) shp = uf.getLegendLayerByName(self.iface, "Buffers") csv = uf.getLegendLayerByName(self.iface, "Dissolved") # Set properties for the join shpField = 'id' csvField = 'id' joinObject = QgsVectorJoinInfo() joinObject.joinLayerId = csv.id() joinObject.joinFieldName = csvField joinObject.targetFieldName = shpField joinObject.memoryCache = True shp.addJoin(joinObject) # add an 'total_area' field and calculate straal = float(self.bufferLineEdit.text()) uf.addFields(wanted_layer, ["total_area"], [QtCore.QVariant.Double]) uf.updateField(wanted_layer, "total_area", " 3.14159265359 * ((%d)^2)" % straal) # add an 'percentage_green' field and calculate uf.addFields(wanted_layer, ["green_perc"], [QtCore.QVariant.Double]) uf.updateField( wanted_layer, "green_perc", "(%s /%s)* 100" % ('Dissolved_green_area', 'total_area')) layer1 = QgsMapLayerRegistry.instance().mapLayersByName("Buffers")[0] layer2 = QgsMapLayerRegistry.instance().mapLayersByName( "Intersection")[0] layer3 = QgsMapLayerRegistry.instance().mapLayersByName("Dissolved")[0] toc = self.iface.legendInterface() groups = toc.groups() groupIndex2 = groups.index(u'output') groupIndex = groups.index(u'working files') # move layer to output folder toc.moveLayer(layer1, groupIndex2) toc.moveLayer(layer2, groupIndex) toc.moveLayer(layer3, groupIndex)
def run(self): """Run method that performs all the real work""" # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: # Do something useful here - delete the line containing pass and # substitute with your code. #-----clear cLayer = iface.mapCanvas().currentLayer() QgsMapLayerRegistry.instance().removeMapLayer(cLayer) cLayer = iface.mapCanvas().currentLayer() QgsMapLayerRegistry.instance().removeMapLayer(cLayer) line_Dxf = self.dlg.lineEdit.text() db = os.path.expanduser( '~\\.qgis2\\python\\plugins\\ParcelChecker\\qgis.dbf') outputs_QGISEXPLODELINES_1 = processing.runalg( 'qgis:explodelines', line_Dxf, None) outputs_GRASS7VCLEAN_1 = processing.runalg( 'grass7:v.clean', outputs_QGISEXPLODELINES_1['OUTPUT'], 1, 0.001, ('0,2000,0,2000'), -1.0, 0.0001, None, None) outputs_GRASS7VCLEAN_2 = processing.runalg( 'grass7:v.clean', outputs_GRASS7VCLEAN_1['output'], 0, 0.001, ('0,2000,0,2000'), -1.0, 0.0001, None, None) outputs_QGISFIELDCALCULATOR_1 = processing.runalg( 'qgis:fieldcalculator', outputs_GRASS7VCLEAN_2['output'], 'ex', 0, 10.0, 4.0, True, '$length', None) outputs_QGISJOINATTRIBUTESTABLE_1 = processing.runandload( 'qgis:joinattributestable', outputs_QGISFIELDCALCULATOR_1['OUTPUT_LAYER'], db, 'layer', 'layer', None) #---- ---------------iface activity-------------------------------------- cLayer = iface.mapCanvas().currentLayer() expr = QgsExpression("ex=0") it = cLayer.getFeatures(QgsFeatureRequest(expr)) ids = [i.id() for i in it] cLayer.setSelectedFeatures(ids) cLayer.startEditing() for fid in ids: cLayer.deleteFeature(fid) cLayer.commitChanges() #---- ---------------iface activity 02-------------------------------------- cLayer = iface.mapCanvas().currentLayer() expr = QgsExpression(" \"layer_2\" is NULL") it = cLayer.getFeatures(QgsFeatureRequest(expr)) ids = [i.id() for i in it] cLayer.setSelectedFeatures(ids) cLayer.startEditing() for fid in ids: cLayer.deleteFeature(fid) cLayer.commitChanges() #------------------ cLayer = iface.mapCanvas().currentLayer() layer = self.iface.activeLayer() myfilepath = iface.activeLayer().dataProvider().dataSourceUri() QgsMapLayerRegistry.instance().removeMapLayer(cLayer) layer = QgsVectorLayer(myfilepath, os.path.basename(line_Dxf[:-4]), 'ogr') QgsMapLayerRegistry.instance().addMapLayer(layer) cLayer = iface.mapCanvas().currentLayer() outputs_QGISPOLYGONIZE_1 = processing.runalg( 'qgis:polygonize', cLayer, False, True, None) outputs_QGISPOINTONSURFACE_1 = processing.runandload( 'qgis:pointonsurface', line_Dxf, None) cLayer = iface.mapCanvas().currentLayer() expr = QgsExpression(" \"Layer\" is not 'LOTNO'") it = cLayer.getFeatures(QgsFeatureRequest(expr)) ids = [i.id() for i in it] cLayer.setSelectedFeatures(ids) cLayer.startEditing() for fid in ids: cLayer.deleteFeature(fid) cLayer.commitChanges() outputs_QGISJOINATTRIBUTESBYLOCATION_1 = processing.runandload( 'qgis:joinattributesbylocation', outputs_QGISPOLYGONIZE_1['OUTPUT'], cLayer, ['contains'], 0.0, 0, 'sum,mean,min,max,median', 1, None) b = r"" + line_Dxf[:-4] + "Report01.txt" file = open(b, 'w') cLayer = iface.mapCanvas().currentLayer() #------------------------------------------------------------------------ cLayer = iface.mapCanvas().currentLayer() layer = self.iface.activeLayer() myfilepath = iface.activeLayer().dataProvider().dataSourceUri() outputs_QGISDISSOLVE_2 = processing.runandload( 'qgis:dissolve', cLayer, False, 'Text', None) layer = self.iface.activeLayer() myfilepath2 = iface.activeLayer().dataProvider().dataSourceUri() QgsMapLayerRegistry.instance().removeMapLayer(cLayer) outputs_QGISDISSOLVE_3 = processing.runandload( 'qgis:dissolve', myfilepath, False, 'Text', None) #---- ---------------iface activity 03-------------------------------------- cLayer = iface.mapCanvas().currentLayer() expr = QgsExpression(" \"Layer\" is NULL") it = cLayer.getFeatures(QgsFeatureRequest(expr)) ids = [i.id() for i in it] cLayer.setSelectedFeatures(ids) cLayer.startEditing() for fid in ids: cLayer.deleteFeature(fid) cLayer.commitChanges() feats_count = cLayer.featureCount() file.write('----------Processed result of the plan--------"\n') file.write('\nNo of Lots ') file.write(str(feats_count)) #----------------------------------------------------------------------------------------- cLayer = iface.mapCanvas().currentLayer() layer = self.iface.activeLayer() QgsMapLayerRegistry.instance().removeMapLayer(cLayer) cLayer = iface.mapCanvas().currentLayer() QgsMapLayerRegistry.instance().removeMapLayer(cLayer) cLayer = iface.mapCanvas().currentLayer() QgsMapLayerRegistry.instance().removeMapLayer(cLayer) layer = QgsVectorLayer(myfilepath, os.path.basename(line_Dxf[:-4]), 'ogr') QgsMapLayerRegistry.instance().addMapLayer(layer) #---- ---------------iface activity 05-------------------------------------- cLayer = iface.mapCanvas().currentLayer() expr = QgsExpression(" \"area\" is 0") it = cLayer.getFeatures(QgsFeatureRequest(expr)) ids = [i.id() for i in it] cLayer.setSelectedFeatures(ids) cLayer.startEditing() for fid in ids: cLayer.deleteFeature(fid) cLayer.commitChanges() count1 = cLayer.featureCount() file.write('\nNo of Polygons ') file.write(str(count1)) expr = QgsExpression(" \"Text\" is NULL") it = cLayer.getFeatures(QgsFeatureRequest(expr)) ids = [i.id() for i in it] cLayer.setSelectedFeatures(ids) count2 = len(ids) file.write('\nNo of Polygons unloted ') file.write(str(count2)) if str(count1 < count2): file.write( '\nplease numbered the unloted lots and re do the processed ' ) now = datetime.datetime.now() date = str(now) a1 = str(now.strftime("%Y-%m-%d")) file.write("\nDate : " + a1 + "\n") file.write( '\n------------------------- R&D @ SGO ------------------------' ) file.close() layer = iface.activeLayer() layer.setCustomProperty("labeling", "pal") layer.setCustomProperty("labeling/enabled", "true") layer.setCustomProperty("labeling/fontFamily", "Arial") layer.setCustomProperty("labeling/fontSize", "10") layer.setCustomProperty("labeling/fieldName", "Text") layer.setCustomProperty("labeling/placement", "4") iface.mapCanvas().refresh() from PyQt4.QtGui import * window = iface.mainWindow() QMessageBox.information( window, "Info", "Process complete....!\n \n (if unloted polygon exist, dont goto the next step)" ) pass
def controllo(self): self.help_button.clicked.connect(lambda: webbrowser.open( 'https://www.youtube.com/watch?v=zv25F_apEMM&t=3s')) DIZIO_LYR = { "Siti puntuali": { u'pkuid': 'integer', u'ubicazione_prov': 'text', u'ubicazione_com': 'text', u'id_spu': 'text', u'indirizzo': 'text', u'coord_x': 'real', u'coord_y': 'real', u'mod_identcoord': 'text', u'desc_modcoord': 'text', u'quota_slm': 'real', u'modo_quota': 'text', u'data_sito': 'text', u'note_sito': 'text' }, "Siti lineari": { u'pkuid': 'integer', u'ubicazione_prov': 'text', u'ubicazione_com': 'text', u'id_sln': 'text', u'acoord_x': 'real', u'acoord_y': 'real', u'bcoord_x': 'real', u'bcoord_y': 'real', u'mod_identcoord': 'text', u'desc_modcoord': 'text', u'aquota': 'real', u'bquota': 'real', u'data_sito': 'text', u'note_sito': 'text' }, "Elementi geologici e idrogeologici puntuali": { u'pkuid': 'integer', u'Tipo_gi': 'text', u'Valore': 'real', u'Valore2': 'real', u'ID_gi': 'integer' }, "Elementi puntuali": { u'pkuid': 'integer', u'Tipo_ep': 'integer', u'ID_ep': 'integer' }, "Elementi lineari": { u'pkuid': 'integer', u'Tipo_el': 'integer', u'ID_el': 'integer' }, "Forme": { u'pkuid': 'integer', u'Tipo_f': 'integer', u'ID_f': 'integer' }, "Unita' geologico-tecniche": { u'pkuid': 'integer', u'Tipo_gt': 'text', u'Stato': 'integer', u'Gen': 'text', u'Tipo_geo': 'text', u'ID_gt': 'integer' }, "Instabilita' di versante": { u'pkuid': 'integer', u'Tipo_i': 'integer', u'FRT': 'real', u'FRR': 'real', u'IL': 'real', u'DISL': 'real', u'FA': 'real', u'FV': 'real', u'Ft': 'real', u'FH0105': 'real', u'FH0510': 'real', u'FH0515': 'real', u'FPGA': 'real', u'FA0105': 'real', u'FA0408': 'real', u'FA0711': 'real', u'SPETTRI': 'text', u'LIVELLO': 'integer', u'CAT': 'text', u'ID_i': 'integer', u'AMB': 'text' }, "Isobate liv 1": { u'pkuid': 'integer', u'Quota': 'real', u'ID_isosub': 'integer' }, "Zone stabili liv 1": { u'pkuid': 'integer', u'Tipo_z': 'integer', u'FA': 'real', u'FV': 'real', u'Ft': 'real', u'FH0105': 'real', u'FH0510': 'real', u'FH0515': 'real', u'FPGA': 'real', u'FA0105': 'real', u'FA0408': 'real', u'FA0711': 'real', u'SPETTRI': 'text', u'LIVELLO': 'integer', u'CAT': 'text', u'ID_z': 'integer' }, "Zone instabili liv 1": { u'pkuid': 'integer', u'Tipo_i': 'integer', u'FRT': 'real', u'FRR': 'real', u'IL': 'real', u'DISL': 'real', u'FA': 'real', u'FV': 'real', u'Ft': 'real', u'FH0105': 'real', u'FH0510': 'real', u'FH0515': 'real', u'FPGA': 'real', u'FA0105': 'real', u'FA0408': 'real', u'FA0711': 'real', u'SPETTRI': 'text', u'LIVELLO': 'integer', u'CAT': 'text', u'ID_i': 'integer', u'AMB': 'text' }, "Isobate liv 2": { u'pkuid': 'integer', u'Quota': 'real', u'ID_isosub': 'integer' }, "Zone stabili liv 2": { u'pkuid': 'integer', u'Tipo_z': 'integer', u'FA': 'real', u'FV': 'real', u'Ft': 'real', u'FH0105': 'real', u'FH0510': 'real', u'FH0515': 'real', u'FPGA': 'real', u'FA0105': 'real', u'FA0408': 'real', u'FA0711': 'real', u'SPETTRI': 'text', u'LIVELLO': 'integer', u'CAT': 'text', u'ID_z': 'integer' }, "Zone instabili liv 2": { u'pkuid': 'integer', u'Tipo_i': 'integer', u'FRT': 'real', u'FRR': 'real', u'IL': 'real', u'DISL': 'real', u'FA': 'real', u'FV': 'real', u'Ft': 'real', u'FH0105': 'real', u'FH0510': 'real', u'FH0515': 'real', u'FPGA': 'real', u'FA0105': 'real', u'FA0408': 'real', u'FA0711': 'real', u'SPETTRI': 'text', u'LIVELLO': 'integer', u'CAT': 'text', u'ID_i': 'integer', u'AMB': 'text' }, "Isobate liv 3": { u'pkuid': 'integer', u'Quota': 'real', u'ID_isosub': 'integer' }, "Zone stabili liv 3": { u'pkuid': 'integer', u'Tipo_z': 'integer', u'FA': 'real', u'FV': 'real', u'Ft': 'real', u'FH0105': 'real', u'FH0510': 'real', u'FH0515': 'real', u'FPGA': 'real', u'FA0105': 'real', u'FA0408': 'real', u'FA0711': 'real', u'SPETTRI': 'text', u'LIVELLO': 'integer', u'CAT': 'text', u'ID_z': 'integer' }, "Zone instabili liv 3": { u'pkuid': 'integer', u'Tipo_i': 'integer', u'FRT': 'real', u'FRR': 'real', u'IL': 'real', u'DISL': 'real', u'FA': 'real', u'FV': 'real', u'Ft': 'real', u'FH0105': 'real', u'FH0510': 'real', u'FH0515': 'real', u'FPGA': 'real', u'FA0105': 'real', u'FA0408': 'real', u'FA0711': 'real', u'SPETTRI': 'text', u'LIVELLO': 'integer', u'CAT': 'text', u'ID_i': 'integer', u'AMB': 'text' } } SHP_VALIDATORE = [ "geotec_self_inters", "stab_1_self_inters", "instab_1_self_inters", "ms1_inters_stab_instab", "stab_2_self_inters", "instab_2_self_inters", "ms2_inters_stab_instab", "stab_3_self_inters", "instab_3_self_inters", "ms3_inters_stab_instab" ] dir_progetto = QgsProject.instance().fileName() indagini_punti = True indagini_linee = True intersezioni_geotec = True intersezioni_ms1 = True intersezioni_ms2 = True intersezioni_ms3 = True self.disableButton() self.show() result = self.exec_() if result: try: dict_layer = {} pathname = QgsProject.instance().readPath( "./") + os.sep + "allegati" + os.sep + "log" logfile_ita = pathname + os.sep + str( time.strftime("%Y-%m-%d_%H-%M-%S", time.gmtime())) + "_log_controllo.txt" logfile_eng = pathname + os.sep + str( time.strftime("%Y-%m-%d_%H-%M-%S", time.gmtime())) + "_validation_log.txt" f = open(logfile_ita, 'a') e = open(logfile_eng, 'a') f.write("REPORT DI CONTROLLO E VALIDAZIONE:" + "\n----------------------------------\n\n") e.write("VALIDATION SUMMARY REPORT:" + "\n------------------------------\n\n") if os.path.exists(pathname + os.sep + "analisi"): shutil.rmtree(pathname + os.sep + "analisi") os.makedirs(pathname + os.sep + "analisi") else: os.makedirs(pathname + os.sep + "analisi") f.write("1) Controllo dei layer di progetto:\n") e.write("1) Presence of project layers:\n") root = QgsProject.instance().layerTreeRoot() added = self.checkLayers(root, dict_layer, DIZIO_LYR) if len(added) == 0: f.write( " I layer fondamentali del progetto sono tutti presenti!" ) e.write(" The project layers are all present!") else: f.write(" Mancano i seguenti layer:\n") e.write(" The following layers are missing:\n") for x in added: f.write(" - " + x + "\n") e.write(" - " + x + "\n") if "Siti puntuali" in added or "Indagini puntuali" in added or "Parametri puntuali" in added or "Curve di riferimento" in added: indagini_punti = False if "Siti lineari" in added or "Indagini lineari" in added or "Parametri lineari" in added: indagini_linee = False if "Unita' geologico-tecniche" in added: intersezioni_geotec = False if "Zone stabili liv 1" in added or "Zone instabili liv 1" in added: intersezioni_ms1 = False if "Zone stabili liv 2" in added or "Zone instabili liv 2" in added: intersezioni_ms2 = False if "Zone stabili liv 3" in added or "Zone instabili liv 3" in added: intersezioni_ms3 = False f.write("\n\n2) Controllo geometrico:\n") e.write("\n\n2) Geometric control:\n") for nome in constants.LISTA_LAYER: if nome in [ "Indagini puntuali", "Parametri puntuali", "Curve di riferimento", "Indagini lineari", "Parametri lineari" ]: pass else: f.write( " Sto eseguendo il controllo geometrico del layer '" + nome + "'\n") e.write( " I am performing geometric validation of the '" + nome + "' layer\n") features = QgsMapLayerRegistry.instance( ).mapLayersByName(nome)[0] for feature in features.getFeatures(): geom = feature.geometry() if geom: err = geom.validateGeometry() if err: f.write( ' %d individuato errore geometrico (feature %d)\n' % (len(err), feature.id())) e.write( ' %d identified geometric error (feature %d)\n' % (len(err), feature.id())) f.write(" Ho terminato l'analisi del layer '" + nome + "'\n\n") e.write(" I finished the analysis of the layer '" + nome + "'\n\n") f.write("3) Controllo topologico:\n") e.write("3) Topological control:\n") f.write( " Sto eseguendo il controllo topologico per il livello 'Carta Geotecnica'...\n" ) e.write( " I am performing topological validation of 'Carta Geotecnica' level...\n" ) if intersezioni_geotec is True: processing.runandload( "saga:polygonselfintersection", "Unita' geologico-tecniche", "ID_gt", pathname + os.sep + "analisi" + os.sep + "geotec_self_inters.shp") self.elab_self_intersect("geotec_self_inters") self.remove_record("geotec_self_inters") f.write( " Fatto! Il file contenente le auto-intersezioni del layer 'Unita' geologico-tecniche' e' stato salvato nella directory '\\allegati\\log\\analisi\\geotec_self_inters.shp'\n\n" ) e.write( " Done! File containing auto-intersections of 'Unita' geologico-tecniche' layer has been saved in '\\allegati\\log\\analisi\\geotec_self_inters.shp'\n\n" ) else: f.write( " Non e' possibile eseguire il controllo topologico in quanto manca/mancano uno o piu' layer!\n\n" ) e.write( " Topological validation can not be performed because one or more layers is/are missing!\n\n" ) f.write( " Sto eseguendo il controllo topologico per il livello 'MS1'...\n" ) e.write( " I am performing topological validation of the 'MS1' level...\n" ) if intersezioni_ms1 is True: self.topology_check(pathname + os.sep + "analisi", "Zone stabili liv 1", "Zone instabili liv 1", "ID_z", "ID_i", "stab_1_self_inters", "instab_1_self_inters", "ms1_inters_stab_instab", f, e) else: f.write( " Non e' possibile eseguire il controllo topologico in quanto manca/mancano uno o piu' layer!\n\n" ) e.write( " Topological validation can not be performed because one or more layers is/are missing!\n\n" ) f.write( " Sto eseguendo il controllo topologico per il livello 'MS2'...\n" ) e.write( " I am performing topological validation of the 'MS2' level...\n" ) if intersezioni_ms2 is True: self.topology_check(pathname + os.sep + "analisi", "Zone stabili liv 2", "Zone instabili liv 2", "ID_z", "ID_i", "stab_2_self_inters", "instab_2_self_inters", "ms2_inters_stab_instab", f, e) else: f.write( " Non e' possibile eseguire il controllo topologico in quanto manca/mancano uno o piu' layer!\n\n" ) e.write( " Topological validation can not be performed because one or more layers is/are missing!\n\n" ) f.write( " Sto eseguendo il controllo topologico per il livello 'MS3'...\n" ) e.write( " I am performing topological validation of the 'MS3' level...\n" ) if intersezioni_ms3 is True: self.topology_check(pathname + os.sep + "analisi", "Zone stabili liv 3", "Zone instabili liv 3", "ID_z", "ID_i", "stab_3_self_inters", "instab_3_self_inters", "ms3_inters_stab_instab", f, e) else: f.write( " Non e' possibile eseguire il controllo topologico in quanto manca/mancano uno o piu' layer!\n\n" ) e.write( " Topological validation can not be performed because one or more layers is/are missing!\n\n" ) f.write("\nAnalisi terminata!") e.write("\nAnalysis completed!") QMessageBox.information( None, u'INFORMATION!', u"Validation summary report was saved in the project folder '...\\allegati\\log'" ) for layer in iface.mapCanvas().layers(): if layer.name() in SHP_VALIDATORE: feats_count = layer.featureCount() if feats_count == 0: QgsMapLayerRegistry.instance().removeMapLayer( layer) root = QgsProject.instance().layerTreeRoot() root.addGroup("Validazione") toc = iface.legendInterface() groups = toc.groups() groupIndex = groups.index("Validazione") canvas = iface.mapCanvas() layers = canvas.layers() for i in layers: if i.name() in SHP_VALIDATORE: alayer = i toc.moveLayer(i, groupIndex) canvas.refresh() except IOError: QMessageBox.warning( None, u'WARNING!', u"Open a Seismic Microzonation project before starting this tool!" ) except Exception as z: QMessageBox.critical(None, u'ERROR!', u'Error:\n"' + str(z) + '"')
def run(self): """Run method that performs all the real work""" # show the dialog self.dlg.show() # Clear all input line self.dlg.Contour_Layer.clear() self.dlg.River_Layer.clear() self.dlg.Contour_Elev_Field.clear() self.dlg.Output_Directory.clear() # Load all active layers layers = self.iface.legendInterface().layers() idx = 0 for layer in layers: try: layer.wkbType() if layer.wkbType() == 2: self.layers_dict.update({idx: layer}) self.dlg.Contour_Layer.addItem(layer.name(), layer) self.dlg.River_Layer.addItem(layer.name(), layer) idx += 1 except: pass # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: # Do something useful here - delete the line containing pass and # substitute with your code. # pass # Initial Input Parameter contour_layer = self.layers_dict[ self.dlg.Contour_Layer.currentIndex()] contour_elev_field = self.dlg.Contour_Elev_Field.currentText() river_layer = self.layers_dict[self.dlg.River_Layer.currentIndex()] output_directory = self.dlg.Output_Directory.text() # Get data CRS contour_crs = contour_layer.crs().authid() river_crs = river_layer.crs().authid() if contour_crs == river_crs: shpdriver = ogr.GetDriverByName('ESRI Shapefile') # Intersect line output_point = os.path.join(output_directory, "point_of_intersect.shp") if os.path.exists(output_point): shpdriver.DeleteDataSource(output_point) processing.runandload("qgis:lineintersections", contour_layer, river_layer, str(contour_elev_field), '', output_point) intersect_points_layer = QgsVectorLayer( output_point, 'point_of_intersect', 'ogr') # Split lines with lines output_split_lines = os.path.join(output_directory, "splited_lines.shp") if os.path.exists(output_split_lines): shpdriver.DeleteDataSource(output_split_lines) processing.runalg('saga:splitlineswithlines', river_layer, contour_layer, 1, output_split_lines) splited_lines_layer = QgsVectorLayer(output_split_lines, 'splited_lines', 'ogr') # Join Attributes output_joint_lines = os.path.join(output_directory, "joint_lines.shp") if os.path.exists(output_joint_lines): shpdriver.DeleteDataSource(output_joint_lines) processing.runalg("qgis:joinattributesbylocation", splited_lines_layer, intersect_points_layer, u'intersects', 0, 1, 'max,min', 0, output_joint_lines) joint_lines_layer = QgsVectorLayer(output_joint_lines, 'joint_lines', 'ogr') # Dissolve contour layers contour_dissolved = os.path.join(output_directory, "dissolved_contour.shp") processing.runalg("qgis:dissolve", contour_layer, "false", str(contour_elev_field), contour_dissolved) contour_dissolved_layer = QgsVectorLayer( contour_dissolved, 'contour_dissolved', 'ogr') # Dissolve river layers river_dissolved = os.path.join(output_directory, "dissolved_river.shp") processing.runalg("qgis:dissolve", joint_lines_layer, "false", 'min' + str(contour_elev_field), river_dissolved) river_dissolved_layer = QgsVectorLayer(river_dissolved, 'river_dissolved', 'ogr') # Generate Poliylines Vector for every features root = QgsProject.instance().layerTreeRoot() contourGroup = root.addGroup("Contour Group") riverGroup = root.addGroup("River Group") # Contour dataSource_contour = ogr.Open( contour_dissolved_layer.dataProvider().dataSourceUri(). split("|")[0], 0) layerContour = dataSource_contour.GetLayer() n = 0 for feature in layerContour: n += 1 geom = feature.GetGeometryRef() contour_directory = os.path.join(output_directory, 'contour') if not os.path.exists(contour_directory): os.mkdir(contour_directory) output_vector_contour = os.path.join( contour_directory, str(int(feature.GetField(contour_elev_field))) + 'b.shp') output_prj_contour = os.path.join( contour_directory, str(int(feature.GetField(contour_elev_field))) + 'b.prj') data_source_contour = shpdriver.CreateDataSource( output_vector_contour) srs = osr.SpatialReference() srs.ImportFromEPSG( int(contour_dissolved_layer.crs().authid().split(":") [1])) srs.MorphToESRI() prj_file = open(output_prj_contour, 'w') prj_file.write(srs.ExportToWkt()) prj_file.close() output_vector_contour = output_vector_contour.encode( 'utf-8') layer_contour = data_source_contour.CreateLayer( output_vector_contour, srs, ogr.wkbLineString) layer_contour.CreateField( ogr.FieldDefn("ELEV", ogr.OFTReal)) fet = ogr.Feature(layer_contour.GetLayerDefn()) fet.SetField("ELEV", feature.GetField(contour_elev_field)) fet.SetGeometry(geom) layer_contour.CreateFeature(fet) data_source_contour.Destroy() if self.dlg.autoAdd.isChecked(): vectorLyr = QgsVectorLayer( output_vector_contour, str(int(feature.GetField(contour_elev_field))) + 'b', "ogr") contourGroup.insertChildNode( 1, QgsLayerTreeLayer(vectorLyr)) QgsMapLayerRegistry.instance().addMapLayer( vectorLyr, False) dataSource_contour.Destroy() # River dataSource_river = ogr.Open( river_dissolved_layer.dataProvider().dataSourceUri().split( "|")[0], 0) layerRiver = dataSource_river.GetLayer() n = 0 for feature in layerRiver: n += 1 geom = feature.GetGeometryRef() river_directory = os.path.join(output_directory, 'river') if not os.path.exists(river_directory): os.mkdir(river_directory) output_vector_river = os.path.join( river_directory, str(int(feature.GetField('min' + contour_elev_field))) + 'a.shp') output_prj_river = os.path.join( river_directory, str(int(feature.GetField('min' + contour_elev_field))) + 'a.prj') data_source_river = shpdriver.CreateDataSource( output_vector_river) srs = osr.SpatialReference() srs.ImportFromEPSG( int(river_dissolved_layer.crs().authid().split(":") [1])) srs.MorphToESRI() prj_file = open(output_prj_river, 'w') prj_file.write(srs.ExportToWkt()) prj_file.close() output_vector_river = output_vector_river.encode('utf-8') layer_river = data_source_river.CreateLayer( output_vector_river, srs, ogr.wkbLineString) layer_river.CreateField(ogr.FieldDefn("ELEV", ogr.OFTReal)) fet = ogr.Feature(layer_river.GetLayerDefn()) fet.SetField("ELEV", feature.GetField('min' + contour_elev_field)) fet.SetGeometry(geom) layer_river.CreateFeature(fet) data_source_river.Destroy() if self.dlg.autoAdd.isChecked(): vectorLyr = QgsVectorLayer( output_vector_river, str( int( feature.GetField('min' + contour_elev_field))) + 'a', "ogr") riverGroup.insertChildNode( 1, QgsLayerTreeLayer(vectorLyr)) QgsMapLayerRegistry.instance().addMapLayer( vectorLyr, False) dataSource_river.Destroy() else: raise Exception( 'Contour and river are not in the same Coordinate Reference System.' )
def test_runandload(self): processing.runandload("qgis:countpointsinpolygon",polygons(),points(),"NUMPOINTS", None) layer = getObjectFromName("Result") self.assertIsNotNone(layer)
def gdal_polygonize(self, layer, f): output_file = f + '/temp_pol.shp' result = processing.runandload('gdalogr:polygonize', layer, "DN", "test1", "test2", self.outputFile)
def run_summary(self): brgy = QgsMapLayerRegistry.instance().mapLayersByName(self.summBrgyComboBox.currentText())[0] muniField = self.muniFieldComboBox.currentText() statFieldName = self.fieldComboBox.currentText() statField = indicators.get_indicator_code_from_name(statFieldName) statField0 = get_field(brgy, statField) dissolveField = get_field(brgy, muniField) stat = self.statComboBox.currentText() fieldList = get_list_of_fields(brgy, [muniField, statField]) munis = list(set([m[0] for m in fieldList])) munisDict = {} for m in munis: munisDict[m] = [] for f in fieldList: munisDict[f[0]].append(f[1]) processing.runandload("qgis:dissolve", brgy, False, muniField, "memory:") out1 = QgsMapLayerRegistry.instance().mapLayersByName("Dissolved")[0] res = out1.dataProvider().addAttributes([QgsField(stat, statField0.type())]) out1.updateFields() statIndex = out1.fieldNameIndex(stat) muniIndex = out1.fieldNameIndex(muniField) if stat == "SUM": features = out1.getFeatures() for f in features: out1.startEditing() attr = f.attributes() f[statIndex] = sum(munisDict[attr[muniIndex]]) out1.updateFeature(f) if stat == "MEAN": features = out1.getFeatures() for f in features: out1.startEditing() attr = f.attributes() f[statIndex] = round(1.0*sum(munisDict[attr[muniIndex]])/len(munisDict[attr[muniIndex]]), 2) out1.updateFeature(f) if stat == "MIN": features = out1.getFeatures() for f in features: out1.startEditing() attr = f.attributes() f[statIndex] = min(munisDict[attr[muniIndex]]) out1.updateFeature(f) if stat == "MAX": features = out1.getFeatures() for f in features: out1.startEditing() attr = f.attributes() f[statIndex] = min(munisDict[attr[muniIndex]]) out1.updateFeature(f) if stat == "PERCENTAGE": sumDict = {} total = 0 features = out1.getFeatures() for f in features: attr = f.attributes() sumDict[attr[muniIndex]] = sum(munisDict[attr[muniIndex]]) total += sum(munisDict[attr[muniIndex]]) features2 = out1.getFeatures() for f in features2: out1.startEditing() attr = f.attributes() f[statIndex] = round(100.0*sumDict[attr[muniIndex]]/total, 2) out1.updateFeature(f) out1.commitChanges() processing.runandload("qgis:deleteholes", out1, "memory:") out2 = QgsMapLayerRegistry.instance().mapLayersByName("Cleaned")[0] out2.setLayerName("{} ({})".format(stat, statFieldName)) QgsMapLayerRegistry.instance().removeMapLayers([out1.id()]) if self.labelCheckBox.isChecked(): add_labels(out2, stat) if self.symCheckBox.isChecked(): pass # Delete other fields remove_other_fields_summary(out2, muniField)
# Performing a Union on Vector Shapes # https://github.com/GeospatialPython/Learn/raw/master/union.zip import processing processing.runandload("qgis:union", "/qgis_data/union/building.shp", "/qgis_data/union/walkway.shp", "/qgis_data/union/union.shp")
def test_runandload(self): processing.runandload('qgis:countpointsinpolygon', polygons(), points(), 'NUMPOINTS', None) layer = getObjectFromName('Result') self.assertIsNotNone(layer)
# Make a globe-like azimuthal orthographic projection # https://github.com/GeospatialPython/Learn/raw/master/countries.zip import processing pth = "/qgis_data/countries.shp" clipped = "/qgis_data/clipped_countries.shp" warped = "/qgis_data/sphere.shp" x = 22 y = 36 processing.runalg( "cliptohemisphere:clipavectorlayertothehemispherecentredonauserspecifiedpoint", pth, y, x, 500, clipped, progress=None) processing.runandload("qgis:reprojectlayer", clipped, "EPSG:53032", warped)
def run(self): """Run method that performs all the real work""" # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: # Do something useful here - delete the line containing pass and # substitute with your code. selectedLayerIndex = self.dlg.comboBox.currentText() filename = self.work_path + '/' + selectedLayerIndex msg = 'The input shapefile will be {}'.format(filename) path = str(filename) layer = iface.addVectorLayer(path, '', "ogr") self.iface.messageBar().pushInfo('Open', msg) selectedLayerIndex2 = self.dlg.comboBox_2.currentText() selectedLayerIndex3 = self.dlg.comboBox_3.currentText() selectedLayerIndex4 = self.dlg.comboBox_4.currentText() filename2 = self.work_path + '/' + selectedLayerIndex2 filename3 = self.work_path + '/' + selectedLayerIndex3 filename4 = self.work_path + '/' + selectedLayerIndex4 path2 = str(filename2) path3 = str(filename3) path4 = str(filename4) mainworkpath = self.work_path + '/' trtshp = path4 layer = QgsVectorLayer(trtshp, 'Franklin tracts', 'ogr') shpname = path4 dbfname = path3 outshpname = mainworkpath layer = QgsVectorLayer(shpname, 'Tracts', 'ogr') layer.isValid() table = QgsVectorLayer(dbfname, 'Population', 'ogr') table.isValid() info = QgsVectorJoinInfo() info.joinLayerId = table.id() info.joinFieldName = 'GEO_ID' info.targetFieldName = 'STFID2' info.setJoinFieldNamesSubset(['P001001']) info.memoryCache = True layer.addJoin(info) QgsVectorFileWriter.writeAsVectorFormat(layer, outshpname, 'CP120', None, 'ESRI Shapefile') layer_joined = QgsVectorLayer(outshpname, 'Joined', 'ogr') layer_joined.isValid() layer.dataProvider().fields().count() layer_joined.dataProvider().fields().count() shp1 = path4 shp2 = path layer_joined = QgsVectorLayer(shp1, 'Franklin tracts', 'ogr') layer2 = QgsVectorLayer(shp2, 'Public libraries', 'ogr') registry = QgsMapLayerRegistry.instance() registry.addMapLayers([layer2, layer_joined]) shpname = 'H:/qgis2/Data/trt00_shp.shp' layer = QgsVectorLayer(shpname, 'county', 'ogr') pointLayer = path outshp = 'H:/qgis2/Data/thiessen' extnt = layer.extent().toString() extent = extnt.replace(":", ",").replace(" ", "") bbox = extent processing.runandload("grass7:v.voronoi", pointLayer, False, False, bbox, -1, 0.0001, 0, outshp) processing.runandload('qgis:intersection', shp1, "Voronoi diagram", True, "intersect") processing.runalg('qgis:addfieldtoattributestable', "Intersection", "AreaNew", 1, 20, 0, mainworkpath + "shp3") processing.runalg( 'qgis.fieldcalculator', "shp3", "AreaNew", 1, 20, 0, )
epsg = theLayerActive.crs().authid() uri = "Point?crs=" + epsg + "&field=id:integer" "&index=yes" mem_layer = QgsVectorLayer(uri, 'SplitPoints', 'memory') prov = mem_layer.dataProvider() feats = [QgsFeature() for i in range(len(points))] for i, feat in enumerate(feats): feat.setAttributes([i]) feat.setGeometry(QgsGeometry.fromWkt(points[i])) prov.addFeatures(feats) QgsMapLayerRegistry.instance().addMapLayer(mem_layer) progress.setPercentage(50) progress.setText( "Building segmented line layer named 'Intersection'...") time.sleep(2) Intersection = processing.runandload('saga:splitlinesatpoints', theLayerActive, mem_layer, 1, 0.001, None) if len(QgsMapLayerRegistry.instance().mapLayersByName( 'Intersection')) == 0: QMessageBox.information( None, "Error!", "Segmented line layer named 'Intersection' not created. Ending script." ) while len(QgsMapLayerRegistry.instance().mapLayersByName( 'SplitPoints')) > 0: layer = QgsMapLayerRegistry.instance().mapLayersByName( 'SplitPoints')[0] QgsMapLayerRegistry.instance().removeMapLayer( layer.id()) else: theactivelayer = iface.activeLayer()
# Merging Shapefiles # https://github.com/GeospatialPython/Learn/raw/master/tiled_footprints.zip # See also: processing.alghelp("qgis:mergevectorlayers") import glob import processing pth = "/qgis_data/tiled_footprints/" files = glob.glob(pth + "*.shp") out = pth + "merged.shp" processing.runandload("saga:mergelayers", ";".join(files), "True", "True", out)
rasterPth = pth + "elevation.asc" vectorPth = pth + "paths.shp" pointsPth = pth + "points.shp" elvPointsPth = pth + "elvPoints.shp" settings = QSettings() originalSetting = settings.value("/Projections/defaultBehaviour", "prompt", type=str) settings.setValue("/Projections/defaultBehaviour", "useProject") rasterLyr = QgsRasterLayer(rasterPth, "Elevation") crs = QgsCoordinateReferenceSystem() crs.createFromSrid(4326) rasterLyr.setCrs(crs) settings.setValue("/Projections/defaultBehaviour", originalSetting) rasterLyr.isValid() # True vectorLyr = QgsVectorLayer(vectorPth, "Path", "ogr") vectorLyr.isValid() # True QgsMapLayerRegistry.instance().addMapLayers([rasterLyr]) QgsMapLayerRegistry.instance().addMapLayers([vectorLyr, rasterLyr]) processing.runalg("saga:convertlinestopoints", vectorLyr, False, 1, pointsPth) processing.runandload("saga:addgridvaluestopoints", pointsPth, rasterPth, 0, elvPointsPth)
# Creating Vector Contours from Elevation Data # https://github.com/GeospatialPython/Learn/raw/master/dem.zip import processing rasterLyr = QgsRasterLayer("/qgis_data/rasters/dem.asc", "DEM") rasterLyr.isValid() # True QgsMapLayerRegistry.instance().addMapLayers([rasterLyr]) processing.runandload("gdalogr:contour", rasterLyr, 50.0, "Elv", None, "/qgis_data/rasters/contours.shp")
def polygonizeRaster(iface, dlg, dir_dest, rasterToPolygonizeName, vectorPolygonName): # Fonction de vectorisation li = layerList(iface) rasterToPolygonize = li[rasterToPolygonizeName] messInfo(dlg, "Vectorisation du raster: " + rasterToPolygonizeName) messInfo(dlg, "") outputVectorPath = dir_dest + os.sep + vectorPolygonName + EXT_VECTOR if os.path.exists(outputVectorPath): try: os.remove(outputVectorPath) except: QMessageBox.information( None, "Attention !!!", unicode( outputVectorPath + u" ne peut pas être effacé. Vérifiez que le fichier n'est pas verrouillé par un autre utilisateur ou que le fichier peut être effacé manuellement." ).encode('latin 1')) messErreur( dlg, unicode(outputVectorPath + u" ne peut pas être effacé.").encode('latin 1')) return None if rasterToPolygonize: try: processing.runandload('gdalogr:polygonize', rasterToPolygonize, 'DN', outputVectorPath) except: messErreur( dlg, unicode(u"Erreur pendant l'exécution de gdalogr:polygonize."). encode('latin 1')) return None else: messErreur( dlg, u"fin de traitement sur gdalogr:polygonize, " + rasterToPolygonizeName + " n'est pas valide.") return None layer = None for elem in li: if elem in (u'Vectorisé', 'Vectorized', 'Output layer', vectorPolygonName + EXT_VECTOR): layer = li[elem] if not layer: messErreur( dlg, unicode( u"fin de traitement sur gdalogr:polygonize. Vérifiez que vous avez bien les droits d'écriture sur le répertoire: " + dir_dest).encode('latin 1')) return None messInfo(dlg, "Fin vectorisation du raster: " + rasterToPolygonizeName) messInfo(dlg, "") return layer
t.start() print "interpolating " + date outputs_1=processing.runalg("saga:multilevelbsplineinterpolation",SNWD_data_uri,"Value",1,0.0001,50,"-124.763068,-66.949895,24.523096,49.384358",0.025,None) t.cancel() print "b-spline interpolation took " + str(time.time()-t_spline_start) + " seconds." #clip to state shapefile print "masking " + date outputs_2=processing.runalg("gdalogr:cliprasterbymasklayer",outputs_1['USER_GRID'],lower_48_shapefile,"-9999",False,False,"",None) #Gaussian filter to reduce "holes" t = threading.Timer(20.0, kill_saga_cmd) #ends unresponsive saga_cmd.exe after 20 seconds, which is about double the amount of time this step usually takes t.start() t_filter_start=time.time() print "filtering " + date outputs_3=processing.runandload("saga:gaussianfilter",outputs_2['OUTPUT'], 5, 1, 10,None) t.cancel() print "gaussian filter took " + str(time.time()-t_filter_start) + " seconds." #identify raster layer layers = iface.legendInterface().layers() for layer in layers: if 'Filtered Grid' in layer.name(): #render fcn = QgsColorRampShader() fcn.setColorRampType(QgsColorRampShader.INTERPOLATED) #Snow Depth Color Gradient (same as that used by http://www.instantweathermaps.com/ ) colormap = [] colormap.append(QgsColorRampShader.ColorRampItem(0,QColor(255,255,255,0),'0 Inches')) colormap.append(QgsColorRampShader.ColorRampItem(2.5399,QColor(255,255,255,0),'0.099 Inches')) colormap.append(QgsColorRampShader.ColorRampItem(2.54,QColor(230,255,225,76.5),'0.1 Inches'))
QgsMapLayerRegistry.instance().addMapLayer(short_paths) network.removeSelection() network.select(f) New_feat=[] for f in network.selectedFeatures(): fet = QgsFeature() fet.setGeometry(QgsGeometry().fromPoint(QgsPoint(i[0],i[1]))) fet.setAttributes (f.attributes()) New_feat.append(fet) pr=short_paths.dataProvider() short_paths.addFeatures(New_feat) processing.runandload("qgis:explodelines",network,new_path_expl) """Make groups to subgraph""" network=iface.mapCanvas().currentLayer() G=nx.Graph() for f in network.getFeatures(): f_geom=f.geometry() id=f.id() p0=f_geom.asPolyline()[0] p1=f_geom.asPolyline()[-1] G.add_edge(p0,p1,{'fid':id}) groups=[] for i in connected_components(G): groups.append(list(i))
def gdal_polygonize(self, layer, f): #output_file = f + '/temp_pol.shp' result = processing.runandload('gdalogr:polygonize', layer, "DN", "output")
def saga_map_calculator(self, tempLayer): rasterFilterSaga = 'ifelse(g1 = 0, 0/0, g1)' output_alg = processing.runandload('saga:rastercalculator', tempLayer, '', rasterFilterSaga, False, 7, None)
#======================================================== # Creating an elevation hillshade #======================================================== #Import the processing module: import processing # Load and validate the layer: rasterLyr = QgsRasterLayer("/qgis_data/rasters/dem.asc","Hillshade") rasterLyr.isValid() #Run the Hillshade algorithm, providing the algorithm name, layer reference, #band number, compute edges option, zevenbergen option for smoother terrain, #z-factor elevation exaggeration number, scaling ratio of vertical to horizontal units, #azimuth (angle of the light source), altitude (height of the light source), and output #image's name: processing.runandload("gdalogr:hillshade", rasterLyr, 1,False, False, 1.0, 1.0, 315.0, 45.0,"/qgis_data/rasters/hillshade.tif") # Verify that the output image, hillshade.tif, looks similar to the following #image in QGIS. It should be automatically #======================================================== # Creating vector contours from elevation data #======================================================== #Import the processing module. import processing # Load and validate the DEM: rasterLyr = QgsRasterLayer("/qgis_data/rasters/dem.asc","DEM") rasterLyr.isValid() # Add the DEM to the map using the mapLayerRegistry method:
# join meridian motorways, a-roads and b-roads in one shapefile meridian_motorways_path = 'C:/Users/I.Kolovou/Desktop/itn/motorway_polyline_sample.shp' meridian_a_roads_path = 'C:/Users/I.Kolovou/Desktop/itn/a_road_polyline_sample.shp' meridian_b_roads_path = 'C:/Users/I.Kolovou/Desktop/itn/b_road_polyline_sample.shp' meridian_motorways = QgsVectorLayer(meridian_motorways_path, "meridian_motorways", "ogr") meridian_a_roads = QgsVectorLayer(meridian_a_roads_path, "meridian_a_roads", "ogr") meridian_b_roads = QgsVectorLayer(meridian_b_roads_path, "meridian_b_roads", "ogr") meridian_shp_path = 'C:/Users/I.Kolovou/Desktop/itn/meridian.shp' # TODO: add class column for motorways, a roads and b roads processing.runalg("qgis:mergevectorlayers", [meridian_motorways, meridian_a_roads, meridian_b_roads], meridian_shp_path) meridian = QgsVectorLayer(meridian_shp_path, "meridian_sample", "ogr") meridian_buffer_shp_path = 'C:/Users/I.Kolovou/Desktop/itn/meridian_buffer.shp' meridian_buffer = processing.runandload("qgis:fixeddistancebuffer", meridian, 10, 5, False, meridian_buffer_shp_path) # create a graph from os road layer def update_feat_id_col(shp, col_name, start): pr = shp.dataProvider() fieldIdx = shp.dataProvider().fields().indexFromName(col_name) if fieldIdx == -1: pr.addAttributes([QgsField(col_name, QVariant.Int)]) fieldIdx = shp.dataProvider().fields().indexFromName(col_name) fid = 1 updateMap = {} if start == 0: for f in shp.dataProvider().getFeatures(): updateMap[f.id()] = {fieldIdx: f.id()} elif start == 1: