I have written a custom processing tool, which I use within a large graphical model in QGIS. I am looking for a way to speed it up.
First step of this processing tool is to connect every point of one input layer to every point of another input layer and measure its line length. This takes quite a while, because usually both layers have more than 10000 points. But I am only interested in point pairs within a given distance to each other. So currently I am going to delete the lines afterwards, which are too long. I think this is quite ineffective, and therefore wanted to ask if there is an easy way to speed up this step, by using a spatial index or something like that. I could create one by using index = QgsSpatialIndex(layer.getFeatures())
, but how would I proceed to only connect points I am interested in?
This is a minimal part of my current code:
Memorylayer_VL = QgsVectorLayer(str('LineString?crs=25832')), "tmp_lines", "memory")
Memorylayer_PR = Memorylayer_VL.dataProvider()
maxdistance = 150
# iterate over stop features and create lines
for stop_feat in stop_layer.getFeatures():
point1 = QgsPoint(stop_feat.geometry().asPoint())
for source_feat in possibility_layer.getFeatures():
point2 = QgsPoint(source_feat.geometry().asPoint())
temp_feat = QgsFeature(fields)
temp_feat.setGeometry(QgsGeometry.fromPolyline([point1, point2]))
temp_feat["line_length"] = temp_feat.geometry().length()
# Only add lines shorter than maxdistance and longer than 1m (Already simplified like this using @BERAs suggestion in comments)
# However, couldn't using a spatial index even have more effect?
if (temp_feat.geometry().length() < maxdistance) and (tmp_line_feat.geometry().length() > 1):
Memorylayer_PR.addFeature(temp_feat)
Memorylayer_VL.updateFields()
Memorylayer_VL.commitChanges()
# Doing more processing stuff on the just created lines layer....