本文整理汇总了Python中processing.core.VectorWriter.VectorWriter.addFeature方法的典型用法代码示例。如果您正苦于以下问题:Python VectorWriter.addFeature方法的具体用法?Python VectorWriter.addFeature怎么用?Python VectorWriter.addFeature使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类processing.core.VectorWriter.VectorWriter
的用法示例。
在下文中一共展示了VectorWriter.addFeature方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: split_into_segments
# 需要导入模块: from processing.core.VectorWriter import VectorWriter [as 别名]
# 或者: from processing.core.VectorWriter.VectorWriter import addFeature [as 别名]
def split_into_segments(input_file, output_file):
'function to split a line vector into its segments. The part between two vertexes. Normalized direction of each segment is calculates.Result is writen to a new shapefile'
# import moduls
from qgis.core import*
from PyQt4.QtCore import *
import math
from processing.core.VectorWriter import VectorWriter
# open input file as QGIS layer and assigne to variable
layer=QgsVectorLayer(input_file, "feature_layer", "ogr")
# fetch data provider
provider=layer.dataProvider()
# get attribute fields of layer
fields = layer.pendingFields().toList()
# add new attribute fields to store, feature id, direction, match id, match feature Id
fields.append(QgsField("featureId", QVariant.Int))
fields.append(QgsField("direction", QVariant.Double))
fields.append(QgsField("matchId", QVariant.String))
fields.append(QgsField("matchFeatId", QVariant.Int))
# define output location
segment=output_file
# define feature writer
writer = VectorWriter(segment, None, fields, provider.geometryType(), layer.crs())
# define output feature
outFeat = QgsFeature()
# for each feature in layer
features=layer.getFeatures()
for feature in features:
geom= feature.geometry()
xy=geom.asPolyline()
# for each point pair in feature
for x in range(0, len(xy)-1):
line_start=xy[x]
line_end=xy[x+1]
# define geometry of ouput feature (a new segment)
outFeat.setGeometry(QgsGeometry.fromPolyline([line_start,line_end]))
# copy attribute information form orginal feature
attri = feature.attributes()
# add feature id information
attri.append(int(feature["id_clip"]))
# add direction information
directionlist=[]
directionlist.append(line_start.azimuth(line_end))
directionlist.append(line_end.azimuth(line_start))
direction=directionlist[[abs(e) for e in directionlist].index(min([abs(e) for e in directionlist]))]
attri.append(float(direction))
# assigne attribute information to output feature
outFeat.setAttributes(attri)
# write output feature to segment shapefile
writer.addFeature(outFeat)
del writer
return
示例2: VectorWriter
# 需要导入模块: from processing.core.VectorWriter import VectorWriter [as 别名]
# 或者: from processing.core.VectorWriter.VectorWriter import addFeature [as 别名]
writer = VectorWriter(Results, None, fields, QGis.WKBPoint, networkPrder.crs())
l = 0
node_feat = QgsFeature()
for k,v in Nodes.iteritems():
progress.setPercentage(int(100 * l/max_n))
l+=1
geom = QgsGeometry().fromPoint(G.vertex(v).point())
node_feat.setGeometry(geom)
minlst = [(s['l'][v], s['name']) for s in startpts if s['l'][v] != -1]
if len(minlst) != 0:
minst = min(minlst, key=itemgetter(0))[1]
for start in startpts:
if start['l'][v] != -1:
attrs = [k, start['name'], start['l'][v], 'N']
if start['name'] == minst: attrs[3] = 'Y'
if Subtotal: attrs.append(start['stot'][v])
node_feat.setAttributes(attrs)
writer.addFeature(node_feat)
del writer
progress.setText("{0:.1f} secs".format(time.time()-t0))
示例3: VectorWriter
# 需要导入模块: from processing.core.VectorWriter import VectorWriter [as 别名]
# 或者: from processing.core.VectorWriter.VectorWriter import addFeature [as 别名]
Avoid_select_by_id
)
if layer.isValid():
# Create writer
writer = VectorWriter(
output,
None,
layer.dataProvider().fields(),
layer.dataProvider().geometryType(),
layer.crs()
)
# Export features
features = layer.getFeatures()
for feat in features:
writer.addFeature(feat)
del writer
# Log number of features retrieves
progress.setText('<b>|| The query returned %s features</b>' % layer.featureCount())
else:
progress.setText('<b>## The layer is invalid - Please check your query</b>')
else:
progress.setText('<b>## Database cannot be accessed</b>')
else:
progress.setText('<b>## Cannot connect to the specified database connection name: "%s".</b>' % connectionName)
示例4: densify
# 需要导入模块: from processing.core.VectorWriter import VectorWriter [as 别名]
# 或者: from processing.core.VectorWriter.VectorWriter import addFeature [as 别名]
target_feature = target_layer.getFeatures(QgsFeatureRequest().setFilterFid(id)).next()
print "Target id: "+str(target_feature.attributes()[target_id_column_index])
target_geom = densify(target_feature.geometry().asPolyline(), interval)
hausdorff = calculateHausdorffDistance(origin_geom,target_geom)
#print "Hausdorff distance: "+str(hausdorff)
length_difference = abs(origin_feature.geometry().length() - target_feature.geometry().length())
weight = hausdorff * hausdorff_distance_weight + length_difference * length_difference_weight
if min_weight == None or weight < min_weight:
min_weight = weight
best_hausdorff_distance = hausdorff
best_fit_id = target_feature.attributes()[target_id_column_index]
best_length_difference = length_difference
print "Best fit: "+str(best_fit_id)
print "- distance: "+str(best_hausdorff_distance)
print "- len diff: "+str(best_length_difference)
outFeat.setGeometry( origin_feature.geometry() )
atMap = origin_feature.attributes()
atMap.append(int(best_fit_id))
atMap.append(float(best_hausdorff_distance))
atMap.append(float(best_length_difference))
outFeat.setAttributes( atMap )
writer.addFeature( outFeat )
del writer
示例5: QgsGeometry
# 需要导入模块: from processing.core.VectorWriter import VectorWriter [as 别名]
# 或者: from processing.core.VectorWriter.VectorWriter import addFeature [as 别名]
if fid in path:
res = path[fid]
polylist = []
for x in [arcGeom[x] for x in res['arcs']]:
geom = QgsGeometry().fromWkt(x)
if geom.isMultipart():
geom = geom.asGeometryCollection()
polylist.extend([x.asPolyline() for x in geom])
else: polylist.append(geom.asPolyline())
stpt = G.vertex(res['st']).point()
endpt = G.vertex(res['end']).point()
if len(polylist) == 0:
resfeat.setGeometry(QgsGeometry().fromPolyline([stpt, endpt]))
else:
pline = mergePolylines(polylist)
pline.reverse()
pline = [stpt] + pline + [endpt]
resfeat.setGeometry(QgsGeometry().fromPolyline(pline))
attrs = feat.attributes()
attrs.append(res['cost'])
if Secondary_Sum: attrs.append(res['scost'])
resfeat.setAttributes(attrs)
writer.addFeature(resfeat)
del writer
示例6: QgsField
# 需要导入模块: from processing.core.VectorWriter import VectorWriter [as 别名]
# 或者: from processing.core.VectorWriter.VectorWriter import addFeature [as 别名]
fields = [
QgsField('label', QVariant.String),
]
point_writer = VectorWriter(gratlables, None, fields, shapetype, crs)
majorticks = set(range(0, 360, major_degree_spacing))
minorticks = set(range(0, 360, minor_degree_spacing))
ticks = sorted(majorticks | minorticks)
print ticks
for theta in ticks:
precedence = 'major' if theta in majorticks else 'minor'
point = mkpoint(start, maxdist, theta)
line = QgsGeometry.fromPolyline([start, point])
print line
writer.addFeature(mkfeature(line, [precedence, theta, -1, str(theta)]))
point = mkpoint(start, maxdist + label_offset, theta)
point = QgsGeometry.fromPoint(point)
point_writer.addFeature(mkfeature(point, [str(theta)]))
majorticks = set(range(major_ring_spacing, maxdist+1, major_ring_spacing))
minorticks = set(range(minor_ring_spacing, maxdist, minor_ring_spacing))
for distance in sorted(majorticks | minorticks):
precedence = 'major' if distance in majorticks else 'minor'
buf = QgsGeometry.fromPoint(start).buffer(distance, buffer_segments)
writer.addFeature(mkfeature(buf, [precedence, -1, distance, '%d'%(distance / 1e3)]))
del writer
del point_writer
示例7: createSample
# 需要导入模块: from processing.core.VectorWriter import VectorWriter [as 别名]
# 或者: from processing.core.VectorWriter.VectorWriter import addFeature [as 别名]
#.........这里部分代码省略.........
#Open layer sample
layer_sample = processing.getObject(Vector_samples)
#Get index fields
idx_field_class = layer_sample.fieldNameIndex(Classes_field)
#iniciar variaveis auxiliares
self.classes=[]
self.training=[]
#Get names fields sample
layer_features = layer_sample.getFeatures()
fields = layer_sample.pendingFields()
#Get names fields sample
fields_names = [str(i.name()) for i in fields]
#Remover field class
fields_names.remove(Classes_field)
#Loop about features sample
for feat in layer_features:
#Get values attibutes
attributes = feat.attributes()
#Remove values classes e add in variable
v_class = attributes.pop(idx_field_class)
#Append value class
self.classes.append(v_class)
#Create dict from attr
atr = dict(zip(fields_names, attributes))
#Append in training
self.training.append(atr)
def createDatas(self):
'''
Input datas vector
Create array from vector
Output datas (list(dict))
'''
#Open layer datas
self.layer_datas = processing.getObject(Vector_datas)
#iniciar variaveis auxiliares
self.datas=[]
#Get names fields sample
features_datas = self.layer_datas.getFeatures()
#Get fields vector datas
fields = self.layer_datas.pendingFields()
#Get names fields sample
fields_names = [str(i.name()) for i in fields]
#Loop features datas vector
for feat in features_datas:
#create datas from dict
atr = dict(zip(fields_names, feat.attributes()))
self.datas.append(atr)
def classifierTree(self,Max_depth):
'''
Create model tree
Input training (list(dicy)), class (list) and datas (list(dict))
Output list with classification of Datas
'''
#Create fit transform
trans_train = vec.fit_transform(self.training).toarray()
del(self.training)
trans_datas = vec.fit_transform(self.datas).toarray()
#Choose type classification
clf = tree.DecisionTreeClassifier( max_depth = Max_depth)
#Crate model classification tree
modelTree = clf.fit(trans_train, self.classes)
print 'max_n_classes, ', modelTree.tree_.max_n_classes
print 'node_count: ', modelTree.tree_.node_count
print 'min_density: ', modelTree.tree_.min_density
print 'n_outputs: ', modelTree.tree_.n_outputs
print 'n_features: ', modelTree.tree_.n_features
print 'n__classes: ', modelTree.tree_.n_classes
print 'n_samples: ', modelTree.tree_.n_samples
del(trans_train)
del(self.classes)
#Apply model classification in Datas
self.classificationDatas = modelTree.predict(trans_datas)
with open("/home/ruiz/tree.dot", 'w') as f:
f = tree.export_graphviz(modelTree, out_file=f)
def writeClassification(self):
#Create vector to write
provider = self.layer_datas.dataProvider()
#fields
fields = provider.fields()
fields=[i for i in fields]
fields.append(QgsField("class", QVariant.Int))
#Create shape writer
self.writer = VectorWriter(Output_classification, None, fields, provider.geometryType(), self.layer_datas.crs())
for i, feat in enumerate(self.layer_datas.getFeatures()):
#Add features write
fet = QgsFeature()
fet.setGeometry(feat.geometry())
attrs=feat.attributes()
attrs.append(int(self.classificationDatas[i]))
fet.setAttributes(attrs)
self.writer.addFeature(fet)
del(self.writer)
示例8: freq_min_max
# 需要导入模块: from processing.core.VectorWriter import VectorWriter [as 别名]
# 或者: from processing.core.VectorWriter.VectorWriter import addFeature [as 别名]
if count == 0:
majority = 0
minority = 0
majority_p = 0
minority_p = 0
else:
minority, majority = freq_min_max(freq)
minority = int(minority)
majority = int(majority)
minority_p = float(freq[minority]) / count
majority_p = float(freq[majority]) / count
# write to layer
outFeat.setGeometry(feat.geometry())
attrs = feat.attributes() + [majority, majority_p, minority, minority_p]
outFeat.setAttributes(attrs)
layer_writer.addFeature(outFeat)
# write to table
row = [feat[id_field], majority]
for v in values:
if v in freq:
row.append(float(freq[v]) / count)
else:
row.append(0)
table_writer.addRecord(row)
progress.setPercentage(100)
del table_writer
del layer_writer
示例9: QgsPoint
# 需要导入模块: from processing.core.VectorWriter import VectorWriter [as 别名]
# 或者: from processing.core.VectorWriter.VectorWriter import addFeature [as 别名]
maxarea = area
inGeom = tmpGeom
atMap = inFeat.attributes()
if QGis.QGIS_VERSION > '2.4':
outGeom = inGeom.pointOnSurface()
else:
outGeom = inGeom.centroid()
if not inGeom.contains(outGeom):
# weight point outside the polygon
# find intersection of horizontal line through the weight pont
rect = inGeom.boundingBox()
horiz = QgsGeometry.fromPolyline([QgsPoint(rect.xMinimum(), outGeom.asPoint()[1]), QgsPoint(rect.xMaximum(), outGeom.asPoint()[1])])
line = horiz.intersection(inGeom)
if line.isMultipart():
# find longest intersection
mline = line.asMultiPolyline()
l = 0
for i in range(len(mline)):
d = sqrt((mline[i][0][0] - mline[i][1][0])**2 + (mline[i][0][1] - mline[i][1][1])**2)
if d > l:
l = d
xMid = (mline[i][0][0] + mline[i][1][0]) / 2.0
yMid = (mline[i][0][1] + mline[i][1][1]) / 2.0
else:
xMid = (line.vertexAt(0).x() + line.vertexAt(1).x()) / 2.0
yMid = (line.vertexAt(0).y() + line.vertexAt(1).y()) / 2.0
outGeom = QgsGeometry.fromPoint(QgsPoint(xMid, yMid))
outFeat.setAttributes(atMap)
outFeat.setGeometry(outGeom)
outputLayer.addFeature(outFeat)
示例10: CreateReceiverPoints
# 需要导入模块: from processing.core.VectorWriter import VectorWriter [as 别名]
# 或者: from processing.core.VectorWriter.VectorWriter import addFeature [as 别名]
def CreateReceiverPoints(self, buildings_layer,receiver_points_layer_path):
# defines emission_points layer
receiver_points_fields = [QgsField("id_pt", QVariant.Int), QgsField("id_bui", QVariant.Int)]
receiver_points_writer = VectorWriter(receiver_points_layer_path, None, receiver_points_fields, 0, buildings_layer.crs())
# gets features from layer
buildings_feat_all = buildings_layer.dataProvider().getFeatures()
# creates SpatialIndex
buildings_spIndex = QgsSpatialIndex()
buildings_feat_all_dict = {}
for buildings_feat in buildings_feat_all:
buildings_spIndex.insertFeature(buildings_feat)
buildings_feat_all_dict[buildings_feat.id()] = buildings_feat
# defines distanze_point
distance_point = 0.1
# re-gets features from layer
buildings_feat_all = buildings_layer.dataProvider().getFeatures()
buildings_feat_total = buildings_layer.dataProvider().featureCount()
pt_id = 0
buildings_feat_number = 0
for buildings_feat in buildings_feat_all:
buildings_feat_number = buildings_feat_number + 1
bar = buildings_feat_number/float(buildings_feat_total)*100
self.progressBar.setValue(bar)
buildings_pt = buildings_feat.geometry().asPolygon()
# creates the search rectangle
rect = QgsRectangle()
rect.setXMinimum( buildings_feat.geometry().boundingBox().xMinimum() - distance_point )
rect.setXMaximum( buildings_feat.geometry().boundingBox().xMaximum() + distance_point )
rect.setYMinimum( buildings_feat.geometry().boundingBox().yMinimum() - distance_point )
rect.setYMaximum( buildings_feat.geometry().boundingBox().yMaximum() + distance_point )
buildings_selection = buildings_spIndex.intersects(rect)
for i in range(0,len(buildings_pt)):
for ii in range(0,len(buildings_pt[i])-1):
x1 = buildings_pt[i][ii][0]
x2 = buildings_pt[i][ii+1][0]
y1 = buildings_pt[i][ii][1]
y2 = buildings_pt[i][ii+1][1]
xm = ( x1 + x2 )/2
ym = ( y1 + y2 )/2
if y2 == y1:
dx = 0
dy = distance_point
elif x2 == x1:
dx = distance_point
dy = 0
else:
m = ( y2 - y1 )/ ( x2 - x1 )
m_p = -1/m
dx = sqrt((distance_point**2)/(1 + m_p**2))
dy = sqrt(((distance_point**2)*(m_p**2))/(1 + m_p**2))
if (x2 >= x1 and y2 >= y1) or (x2 < x1 and y2 < y1):
pt1 = QgsPoint(xm + dx, ym - dy)
pt2 = QgsPoint(xm - dx, ym + dy)
if (x2 >= x1 and y2 < y1) or (x2 < x1 and y2 >= y1):
pt1 = QgsPoint(xm + dx, ym + dy)
pt2 = QgsPoint(xm - dx, ym - dy)
pt = QgsFeature()
# pt1
pt.setGeometry(QgsGeometry.fromPoint(pt1))
intersect = 0
for buildings_id in buildings_selection:
if buildings_feat_all_dict[buildings_id].geometry().intersects(pt.geometry()) == 1:
intersect = 1
break
if intersect == 0:
pt.setAttributes([pt_id, buildings_feat.id()])
receiver_points_writer.addFeature(pt)
pt_id = pt_id + 1
# pt2
pt.setGeometry(QgsGeometry.fromPoint(pt2))
intersect = 0
for buildings_id in buildings_selection:
if buildings_feat_all_dict[buildings_id].geometry().intersects(pt.geometry()) == 1:
intersect = 1
break
if intersect == 0:
pt.setAttributes([pt_id, buildings_feat.id()])
receiver_points_writer.addFeature(pt)
pt_id = pt_id + 1
#.........这里部分代码省略.........
示例11: range
# 需要导入模块: from processing.core.VectorWriter import VectorWriter [as 别名]
# 或者: from processing.core.VectorWriter.VectorWriter import addFeature [as 别名]
if Hour_details:
# loop on index with at least 1 transit stop in range
for i in [x for x in range(len(v_freq)) if v_freq[x] != 0]:
t = i * stepMin
attrs.append(v_routes[i])
attrs.append(v_freq[i])
attrs.append(str(dt.datetime(Day[2], Day[1], Day[0], t/60, t%60)))
t1 = t + stepMin
if t1 >= 1440: t1 = t1 - 1440
attrs.append(str(dt.datetime(Day[2], Day[1], Day[0], t1/60, t1%60)))
feat.setAttributes(attrs)
writer.addFeature(feat)
else:
amplfr = [x for x in v_freq if x > 0]
attrs.append(sum(v_routes))
attrs.append(sum(v_freq))
attrs.append(len(amplfr))
attrs.append(max(amplfr))
feat.setAttributes(attrs)
writer.addFeature(feat)
del writer