I have a point-based vector layer, where each point represents a road accident. I am trying to write a function that:
- Loops through my accident layer
- creates a buffer, of a given radius, around each point/accident
- counts the number of accidents, from the accident layer, within each buffer
- if the number of accidents within (i.e. that intersect) the buffer is above a given threshold, then add this buffer as a polygon to a separate, pre-defined layer
What I have so far:
def get_clusters(layer, out_layer, buff_size, acc_threshold):
segs = 100 #buffer segments
source_layer = core.QgsMapLayerRegistry.instance().mapLayersByName(layer)[0]
# get CRS
CRS = source_layer.crs().authid()
# make the output layer
cluster_layer = QgsVectorLayer("Polygon?crs={0}".format(CRS),out_layer,"memory")
# set up loop and empty list for areas of interest
my_clusters = []
for accident_feature in source_layer.getFeatures():
acc_buffer = accident_feature.geometry().buffer(buff_size,segs)
# At this point I'm not sure how to proceed. I think I need to use something like
request = QgsFeatureRequest().setFilterRect(acc_buffer.geometry().boundingBox())
areas_of_interest = source_layer.getFeatures(request)
for area in areas_of_interest:
## pseudo-code - haven't got far enough to test this
if area.featureCount() >= acc_threshold:
my_clusters.append(area.id())
but that's about as far as I can get. I need the intersection-object to be a circle (i.e. just the buffer polygon), but I can't find something like setFilterArea that I could pass the acc_buffer.geometry() in to.
I hope the above is clear, if someone could point me in the right direction I'm quite content working out the rest for myself but currently I'm a bit stuck!
writeAsVectorFormat(layer, r'c:\QGIS_testing\accidents.csv', "utf-8", None, "CSV", layerOptions='GEOMETRY=AS_XYZ')to export the file as CSV, this appears to have worked. Unable to open using loadtxt thoughIOError: [Errno 22] invalid mode ('U') or filename: 'C:\\QGIS_testing\x07ccidents.csv'. Filename is different to the input? – Alex Jul 07 '16 at 14:52'C:\\QGIS_testing\\x07ccidents.csv'? Remember that your csv should contains only X,Y values. – dmh126 Jul 07 '16 at 14:57layerOptions='GEOMETRY=AS_WKT'but it still exports with all attributes so I'll do some more looking around to see how to export X, Y only – Alex Jul 07 '16 at 16:10