本文整理汇总了Python中processing.core.VectorWriter.VectorWriter类的典型用法代码示例。如果您正苦于以下问题:Python VectorWriter类的具体用法?Python VectorWriter怎么用?Python VectorWriter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了VectorWriter类的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: split_into_segments
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: writeClassification
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)
示例3: QgsField
st['stot'] = {x:res[x][0] for x in list_acc}
# Prepare results
fields = [
QgsField("nodeid", QVariant.Int),
QgsField("startName", QVariant.String),
QgsField(Cost, QVariant.Double),
QgsField("isClosest", QVariant.String)
]
if Subtotal: fields.append(QgsField(Subtotal_cost, QVariant.Double))
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]
示例4: VectorWriter
# Create layer from query result
layer = db.toSqlLayer(
Query,
Geometry_field_name,
Unique_id_field_name,
newLayerName,
QgsMapLayer.VectorLayer,
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:
示例5: QgsSpatialIndex
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.features(target_layer)
origin_fields = origin_layer.pendingFields().toList()
origin_fields.append( QgsField("BEST_FIT", QVariant.Int ))
origin_fields.append( QgsField("HAUSDORFF", QVariant.Double ))
origin_fields.append( QgsField("LEN_DIFF", QVariant.Double ))
writer = VectorWriter(output, None, origin_fields, origin_layer.dataProvider().geometryType(), origin_layer.crs() )
outFeat = QgsFeature()
# populate the spatial index
for feat in target_features:
target_spatial_index.insertFeature(feat)
origin_features = processing.features(origin_layer)
for origin_feature in origin_features:
center = origin_feature.geometry().centroid().asPoint()
print str(center)
nearest_ids = target_spatial_index.nearestNeighbor(center,10)
best_fit_id = None
min_weight = None
示例6: set
arcGeom = {}
fids = set([long(y) for x in path.values() for y in x['arcs']])
for feat in processing.features(netLayer):
if feat.id() in fids:
arcGeom[str(feat.id())] = feat.geometry().exportToWkt()
# make results
fields = linesprvder.fields()
fields.append(QgsField(Cost, QVariant.Double))
if Secondary_Sum: fields.append(QgsField(Secondary_Sum_cost, QVariant.Double))
writer = VectorWriter(Results, None, fields, QGis.WKBLineString, netPrder.crs())
l = 0
resfeat = QgsFeature()
max_n = len(path)
step = max(1, lineslayer.featureCount() / 100)
for feat in processing.features(lineslayer):
if l % step == 0: progress.setPercentage(l/step)
l+=1
fid = feat.id()
if fid in path:
res = path[fid]
示例7: QgsPoint
rads = math.radians(bearing)
x, y = distance * math.sin(rads), distance * math.cos(rads)
return QgsPoint(start.x() + x, start.y() + y)
crs = QgsCoordinateReferenceSystem(crsId)
start = QgsPoint(centerx,centery)
maxdist = major_ring_spacing * major_rings
shapetype = QGis.WKBLineString
fields = [
QgsField('precedence', QVariant.String),
QgsField('theta', QVariant.Int),
QgsField('distance', QVariant.Int),
QgsField('label', QVariant.String),
]
writer = VectorWriter(graticule, None, fields, shapetype, crs)
shapetype = QGis.WKBPoint
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)
示例8: createSample
class ClassificationDecisionTree:
def createSample(self):
'''
Input sample vector
Create array from vector
Output training (list(dict)) and class (list)
'''
#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()):
#.........这里部分代码省略.........
示例9: QgsFeature
fields.append(QgsField(createUniqueFieldName('MIN', fields), QVariant.Int))
fields.append(QgsField(createUniqueFieldName('MIN_P', fields), QVariant.Double))
outFeat = QgsFeature()
features = processing.features(polygon_layer)
n = len(features)
# get all unique raster values
values = []
for stats in frequency_analysis.itervalues():
freq = stats['freq']
values = values + [ v for (v, f) in freq.iteritems()]
values = sorted(list(set(values)))
print values
layer_writer = VectorWriter(Frequency_analysis_layer, None, fields, provider.geometryType(), polygon_layer.crs())
table_writer = TableWriter(Frequency_analysis_table, None, [id_field, 'majority'] + ['value: %d' % v for v in values])
for i, feat in enumerate(features):
progress.setPercentage(int(100 * i / n))
fid = feat.id()
stats = frequency_analysis[fid]
count = stats['count']
freq = stats['freq']
if count == 0:
majority = 0
minority = 0
majority_p = 0
minority_p = 0
else:
示例10: VectorWriter
##poly=vector
##output=output vector
from qgis.core import *
from qgis.core import *
from qgis.utils import *
from processing.core.VectorWriter import VectorWriter
from math import sqrt
inputLayer = processing.getObject(poly)
features = processing.features(inputLayer)
fields = inputLayer.pendingFields().toList()
outputLayer = VectorWriter(output, None, fields, QGis.WKBPoint,
inputLayer.crs())
outFeat = QgsFeature()
for inFeat in features:
inGeom = inFeat.geometry()
if inGeom.isMultipart():
# find largest part in case of multipart
maxarea = 0
tmpGeom = QgsGeometry()
for part in inGeom.asGeometryCollection():
area = part.area()
if area > maxarea:
tmpGeom = part
maxarea = area
inGeom = tmpGeom
atMap = inFeat.attributes()
if QGis.QGIS_VERSION > '2.4':
outGeom = inGeom.pointOnSurface()
else:
outGeom = inGeom.centroid()
示例11: CreateReceiverPoints
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
#.........这里部分代码省略.........
示例12: VectorWriter
fields = zoneprovider.fields()
fields.append(QgsField("routes", QVariant.Int))
fields.append(QgsField("freq", QVariant.Int))
if Hour_details:
fields.append(QgsField("start", QVariant.String))
fields.append(QgsField("end", QVariant.String))
else:
fields.append(QgsField("amplitude", QVariant.String))
fields.append(QgsField("freq_max", QVariant.Int))
writer = VectorWriter(Results, None, fields, QGis.WKBPolygon, zoneprovider.crs())
for feat in processing.features(zonelayer):
if l % step == 0: progress.setPercentage(l/step)
l+=1
attrs = feat.attributes()
geom = feat.geometry()
if Buffer == 0: # no buffer, take object only, else buffer around centroid
near = [x for x in index.intersects(geom.boundingBox())
if geom.contains(stops[nodes_ix[x][0]])]
else:
near = index.intersects(buffRect(geom.centroid().asPoint(), Buffer))