def test_SagaVectorAlgorithWithUnsupportedInputAndOutputFormat(self): '''this tests both the exporting to shp and then the format change in the output layer''' layer = processing.getobject(polygonsGeoJson()); feature = layer.getFeatures().next() selected = [feature.id()] layer.setSelectedFeatures(selected) outputs=processing.runalg("saga:polygoncentroids",polygonsGeoJson(),True, ProcessingUtils.getTempFilename("geojson")) layer.setSelectedFeatures([]) output=outputs['CENTROIDS'] layer=QGisLayers.getObjectFromUri(output, True) fields=layer.pendingFields() expectednames=['ID','POLY_NUM_A','POLY_ST_A'] expectedtypes=['Real','Real','String'] names=[str(f.name()) for f in fields] types=[str(f.typeName()) for f in fields] self.assertEqual(expectednames, names) self.assertEqual(expectedtypes, types) features=processing.getfeatures(layer) self.assertEqual(1, len(features)) feature=features.next() attrs=feature.attributes() expectedvalues=["0","1.1","string a"] values=[str(attr) for attr in attrs] self.assertEqual(expectedvalues, values) wkt='POINT(270787.49991451 4458955.46775295)' self.assertEqual(wkt, str(feature.geometry().exportToWkt()))
def test_SagaVectorAlgorithmWithSelection(self): layer = processing.getobject(polygons2()); feature = layer.getFeatures().next() selected = [feature.id()] layer.setSelectedFeatures(selected) outputs=processing.runalg("saga:polygoncentroids",polygons2(),True,None) layer.setSelectedFeatures([]) output=outputs['CENTROIDS'] layer=QGisLayers.getObjectFromUri(output, True) fields=layer.pendingFields() expectednames=['ID','POLY_NUM_B','POLY_ST_B'] expectedtypes=['Real','Real','String'] names=[str(f.name()) for f in fields] types=[str(f.typeName()) for f in fields] self.assertEqual(expectednames, names) self.assertEqual(expectedtypes, types) features=processing.getfeatures(layer) self.assertEqual(1, len(features)) feature=features.next() attrs=feature.attributes() expectedvalues=["2","1","string a"] values=[str(attr) for attr in attrs] self.assertEqual(expectedvalues, values) wkt='POINT(270806.69221918 4458924.97720492)' self.assertEqual(wkt, str(feature.geometry().exportToWkt()))
def test_attributeValues(self): layer = processing.getobject(points()) attributeValues = values(layer, "ID") i = 1 for value in attributeValues['ID']: self.assertEqual(int(i), int(value)) i += 1 self.assertEquals(13, i)
def test_featuresWithSelection(self): layer = processing.getobject(points()) feature = layer.getFeatures().next() selected = [feature.id()] layer.setSelectedFeatures(selected) features = processing.getfeatures(layer) self.assertEqual(1, len(features)) layer.setSelectedFeatures([])
def test_attributeValues(self): layer = processing.getobject(points()) attributeValues = values(layer, "ID") i = 1 for value in attributeValues['ID']: self.assertEqual(int(i), int(value)) i+=1 self.assertEquals(13,i)
# calculate distances between origin and target feature D = cdist(geom1, geom2, 'euclidean') H1 = np.max(np.min(D, axis=1)) H2 = np.max(np.min(D, axis=0)) distances.append(max(H1, H2)) # repeat the calculation in reverse order D = cdist(geom2, geom1, 'euclidean') H1 = np.max(np.min(D, axis=1)) H2 = np.max(np.min(D, axis=0)) distances.append(max(H1, H2)) hausdorff = max(distances) return hausdorff origin_layer = processing.getobject(origin_layer) target_layer = processing.getobject(target_layer) target_id_column_index = target_layer.fieldNameIndex(target_id_column_index) """ origin_layer = l1 target_layer = l2 target_id_column_index = 0 interval = 1 """ target_spatial_index = QgsSpatialIndex() target_features = processing.getfeatures(target_layer) origin_fields = origin_layer.pendingFields().toList() origin_fields.append(QgsField("BEST_FIT", QVariant.Int)) origin_fields.append(QgsField("HAUSDORFF", QVariant.Double))
def test_featuresWithoutSelection(self): layer = processing.getobject(points()) features = processing.getfeatures(layer) self.assertEqual(12, len(features))
#Algorithm body #================================== from qgis.core import * from PyQt4.QtCore import * import networkx as nx import processing as st from math import sqrt,degrees,atan2,floor,atan,radians,tan,fabs Point_Precision=5 Lengths = {} progress.setText('Splitting Lines') SC = st.runalg("grass:v.split.length",Centerline,eval(Split_by_Distance),None,None,None,2,None) #Split Centerlines layer = st.getobject(SC["output"]) layer2 = st.getobject(Mask) layer3 = st.getobject(Centerline) field_names = ['Distance','RDistance','SP_Dist','SP_RDist','Width','Deviation','DWidth','DWidth2','Diff','Angle','Sinuosity','Centerline'] fields = QgsFields() fields.append( QgsField('FID', QVariant.Int )) for name in field_names: fields.append( QgsField(name, QVariant.Double )) edges = {} feats = {f["FID"]:f for f in layer2.getFeatures()} #Get Geometries of Mask Feature ShortestPaths = {f["FID"]:f for f in layer3.getFeatures()} #Get Geometries of Original Centerline Total = layer.featureCount()
if d not in data: if '.describe()' in Field: data[d] = [eval('g.%s.tolist()'%(Field))] else: data[d] = [(FID,eval('g.%s.tolist()'%(Field)))] if FID not in fields: fields.update(FID) else: if '.describe()' in Field: data[d].append(eval('g.%s.tolist()'%(Field))) else: data[d].append((FID,eval('g.%s.tolist()'%(Field)))) if FID not in fields: fields.update(FID) layer = st.getobject(Target_Feature) if '.describe()' in Field: fields = [ "t_count","count","mean","std","25%","50%","75%","min","max"] for field_name in fields: if layer.fieldNameIndex(field_name) == -1: layer.dataProvider().addAttributes([QgsField(field_name,QVariant.Double)]) layer.startEditing() progress.setText('Updating Fields') Total = layer.featureCount() for enum,feature in enumerate(layer.getFeatures()): progress.setPercentage(int((100 * enum)/Total)) ID = feature[Target_Join_Field] if feature[ID] in data: value = data[ID]
##Sortby_Optional=string #Algorithm #================================== import pysal as ps import processing as st from itertools import izip from pandas import * from qgis.core import * from PyQt4.QtCore import QVariant dbf = Feature.replace('.shp','.dbf') dbf = ps.open(dbf) d = {col: dbf.by_col(col) for col in dbf.header} df = DataFrame(d) layer = st.getobject(Feature) progress.setText('Calculating Fields to Update') if Groupby_Optional: data = {} for n,g in df.groupby(Groupby_Optional.split(',')): if Sortby_Optional: g.sort(columns=Sortby_Optional,inplace=True) data.update(dict(izip(g.index,eval(Expression)))) else: if Sortby_Optional: df.sort(columns=Sortby_Optional,inplace=True) data = dict(izip(df.index,eval(Expression))) if layer.fieldNameIndex(Update_Field) == -1: layer.dataProvider().addAttributes([QgsField(Update_Field,QVariant.Double)])
def test_getobject(self): layer = processing.getobject(points()); self.assertIsNotNone(layer) layer = processing.getobject("points"); self.assertIsNotNone(layer)
##Calculate_Width_By=field Centerline ##Calculate_Distance_By=field Centerline ##Custom_Distance_Field_Optional=string ##Max_Width_Optional=string ##Width=output vector # Algorithm body # ================================== from qgis.core import * from PyQt4.QtCore import * import networkx as nx import processing as st from math import sqrt Lengths = {} layer = st.getobject(Centerline) layer2 = st.getobject(Polyline_Mask) if layer.fieldNameIndex("Distance") == -1: layer.dataProvider().addAttributes([QgsField("Distance", QVariant.Double)]) if layer.fieldNameIndex("RDistance") == -1: layer.dataProvider().addAttributes([QgsField("RDistance", QVariant.Double)]) if layer.fieldNameIndex("Width") == -1: layer.dataProvider().addAttributes([QgsField("Width", QVariant.Double)]) if layer.fieldNameIndex("Diff") == -1: layer.dataProvider().addAttributes([QgsField("Diff", QVariant.Double)]) edges = {} feats = [f for f in layer2.getFeatures()] layer.startEditing() layer.commitChanges() # Force creation of fields mentioned above Total = layer.featureCount()
##[SAFARI]=group ##Voronoi_Lines=vector ##Method=string ShortestPath ##Threshold=number 0 ##Groupby_Field=field Voronoi_Lines ##Output=output vector #Algorithm body #================================== import networkx as nx import os import processing as st from qgis.core import * from PyQt4.QtCore import QVariant layer = st.getobject(Voronoi_Lines) Point_Precision=5 Total = layer.featureCount() edges = {} progress.setText('Calculating Edges') for enum,feature in enumerate(layer.getFeatures()): try: progress.setPercentage(int((100 * enum)/Total)) points = feature.geometry().asPolyline() pnts1 = (round(points[0][0],Point_Precision),round(points[0][1],Point_Precision)) pnts2 = (round(points[-1][0],Point_Precision),round(points[-1][1],Point_Precision)) Length = feature.geometry().length() ID = feature[Groupby_Field] if ID in edges: edges[ID].add_edge(pnts1,pnts2,weight=Length) else:
##Max_Width=number 2500 ##Join_Mask_By=field Centerline ##Width=output vector #Algorithm body #================================== from qgis.core import * from PyQt4.QtCore import * import networkx as nx import processing as st from math import sqrt,degrees,atan2,floor,atan,radians,tan,fabs Point_Precision=5 Lengths = {} layer = st.getobject(Centerline) layer2 = st.getobject(Mask) field_names = ['Distance','RDistance','Width','Diff'] fields = QgsFields() fields.append( QgsField('FID', QVariant.Int )) fields.append( QgsField('Mask_FID', QVariant.Int )) for name in field_names: fields.append( QgsField(name, QVariant.Double )) edges = {} feats = {f["FID"]:f for f in layer2.getFeatures()} #Get Geometries of Mask Feature layer.startEditing() layer.commitChanges() #Force creation of fields mentioned above Total = layer.featureCount()
# calculate distances between origin and target feature D = cdist(geom1,geom2,'euclidean') H1 = np.max(np.min(D, axis=1)) H2 = np.max(np.min(D, axis=0)) distances.append( max(H1,H2) ) # repeat the calculation in reverse order D = cdist(geom2,geom1,'euclidean') H1 = np.max(np.min(D, axis=1)) H2 = np.max(np.min(D, axis=0)) distances.append( max(H1,H2) ) hausdorff = max(distances) return hausdorff origin_layer = processing.getobject(origin_layer) target_layer = processing.getobject(target_layer) target_id_column_index = target_layer.fieldNameIndex(target_id_column_index) """ origin_layer = l1 target_layer = l2 target_id_column_index = 0 interval = 1 """ target_spatial_index = QgsSpatialIndex() target_features = processing.getfeatures(target_layer) origin_fields = origin_layer.pendingFields().toList() origin_fields.append( QgsField("BEST_FIT", QVariant.Int )) origin_fields.append( QgsField("HAUSDORFF", QVariant.Double ))
##[SAFARI]=group ##Polyline=vector ##Groupby_Field=field Polyline ##Loops=number 1 ##Threshold=number 2 ##Threshold_Field_Optional=string ##Output=output vector #Algorithm body #================================== import networkx as nx import processing as st from qgis.core import * from PyQt4.QtCore import QVariant layer = st.getobject(Polyline) Total = layer.featureCount() edges = {} progress.setText('Calculating Edges') for enum,feature in enumerate(layer.getFeatures()): try: progress.setPercentage(int((100 * enum)/Total)) points = feature.geometry().asPolyline() pnts1 = points[0][0],points[0][1] pnts2 = points[-1][0],points[-1][1] if Threshold_Field_Optional: Weight = feature[Threshold_Field_Optional] else: Weight = 1 ID = feature[Groupby_Field]
#Definition of inputs and outputs #================================== ##[SAFARI]=group ##Polygon=vector ##Singlepart=boolean True ##Area_Threshold=number 0 ##Output=output vector #Algorithm body #================================== from qgis.core import * from PyQt4.QtCore import * import processing as st layer = st.getobject(Polygon) fields= layer.pendingFields() crs = layer.crs() writer = QgsVectorFileWriter(Output, "CP1250", fields, 3,layer.crs(), "ESRI Shapefile") fet = QgsFeature(fields) Total = layer.featureCount() progress.setText('Extracting Parts') for enum,feature in enumerate(layer.getFeatures()): progress.setPercentage(int((100 * enum)/Total)) geomType = feature.geometry() if geomType.isMultipart(): multiPart = geomType.asMultiPolygon() geom = [] for part in multiPart:
def test_getobject(self): layer = processing.getobject(points()) self.assertIsNotNone(layer) layer = processing.getobject("points") self.assertIsNotNone(layer)
##Calculate_Width_By=field Centerline ##Calculate_Distance_By_Optional=string ##Custom_Distance_Field_Optional=string ##Distance=number 1000 ##Width=output vector #Algorithm body #================================== from qgis.core import * from PyQt4.QtCore import * import networkx as nx import processing as st from math import sqrt Lengths = {} layer = st.getobject(Centerline) if layer.fieldNameIndex("Distance") == -1: layer.dataProvider().addAttributes([QgsField("Distance",QVariant.Double)]) if layer.fieldNameIndex("RDistance") == -1: layer.dataProvider().addAttributes([QgsField("RDistance",QVariant.Double)]) edges = {} layer.startEditing() layer.commitChanges() #Force creation of fields mentioned above Total = layer.featureCount() if Calculate_Distance_By_Optional: progress.setText('Calculating Edges') for enum,feature in enumerate(layer.getFeatures()):
#Algorithm body #================================== import processing as st import os from qgis.core import * from PyQt4.QtCore import * from itertools import combinations,chain from math import sqrt Precision=5 keepNodes=set([]) progress.setText('Extracting Nodes') layer2 = st.getobject(Polygons) Total = layer2.featureCount() def densify(polyline, interval): #based on DensifyGeometriesInterval.py output = [] for i in xrange(len(polyline) - 1): p1 = polyline[i] p2 = polyline[i + 1] output.append(p1) # Calculate necessary number of points between p1 and p2 pointsNumber = sqrt(p1.sqrDist(p2)) / interval if pointsNumber > 1: multiplier = 1.0 / float(pointsNumber) else: multiplier = 1