I am working on a standalone script, executed out of QGIS console, and I have noticed that the script takes a lot of time when it executes the line: layerB.commitChanges ()
How my script works ?
I have two files that are identical, one is the copy of another.
The script loads both files (fileA and fileB), then it searches for similar points (very near, distance <= 15m. ) over fileA, and deletes it over the fileB. When finished, do commit over the fileB
What would be the fastest way to do this task? I hava read this-> Is it possible to change the geometry without startEditing the layer But I do not finish understanding the proposed solution.
The input data table is approximately 200,000 points and the output table is almost half.
layerA = QgsVectorLayer("fileA.sqlite", "layerA", "ogr")
layerB = QgsVectorLayer("fileB.sqlite", "layerB", "ogr")
featA = [feat for feat in layerA.getFeatures()]
featB = [feat for feat in layerB.getFeatures()]
del_feat = []
target_spatial_index = QgsSpatialIndex()
# populate the spatial index
for f in featB:
target_spatial_index.insertFeature(f)
with edit(layerB):
for feat in featA:
# Skip if into deleted list
if feat.id() not in del_feat:
point1 = feat.geometry().asPoint()
nearest_ids = target_spatial_index.nearestNeighbor(point1,2)
high_id=0
for id in nearest_ids:
outFeat = layerB.getFeatures(QgsFeatureRequest().setFilterFid(id)).next()
#skip himself
if outFeat.id() != feat.id():
# distance between points
point2 = outFeat.geometry().asPoint()
dist = sqrt(point1.sqrDist(point2))
high_id=outFeat.id()
if dist <= 15:
# remove from spatial index
target_spatial_index.deleteFeature(outFeat)
layerB.deleteFeatures([high_id])
# add to list of deleted
del_feat.append(high_id)
layerB.commitChanges()
crs=QgsCoordinateReferenceSystem("epsg:32629")
print "Saving file..."
# Save memory layer to file
error = QgsVectorFileWriter.writeAsVectorFormat(layerB, "fileB.sqlite", "UTF-8", crs , "spatialite")