My layer contains buildings. They have a number (num), a height and a height class (h) between 1 and 4.
The script aims to for each building list:
- the neighboring buildings (NEIGHBORS),
- the heights of these buildings (h_n)
- and the sum of the height classes of the neighboring buildings (SUM).
The script correctly retrieves the list of neighboring buildings (NEIGHBORS), the sum of building height classes (SUM) but does not return the height classes corresponding to each neighboring building (h_n).
Can someone tell me what is blocking?
# inspired script Mr. Ujaval Gandhi
from qgis.utils import iface
from PyQt5.QtCore import QVariant
_NAME_FIELD = 'num' # numero bt
_H_FIELD = 'h' # hauteur bt
_SUM_FIELD = 'h' # somme hauteurs bts voisins
_NEW_NEIGHBORS_FIELD = 'NEIGHBORS' # numero des bts voisins
_NEW_H_NEIGHBORS_FIELD = 'H_N' # hauteur des bts voisins
_NEW_SUM_FIELD = 'SUM_H' # somme hauteur des bts voisins
layer = iface.activeLayer()
layer.startEditing()
layer.dataProvider().addAttributes(
[QgsField(_NEW_NEIGHBORS_FIELD, QVariant.String),
QgsField(_NEW_H_NEIGHBORS_FIELD, QVariant.Int),
QgsField(_NEW_SUM_FIELD, QVariant.Int)])
layer.updateFields()
feature_dict = {f.id(): f for f in layer.getFeatures()}
index = QgsSpatialIndex()
for f in feature_dict.values():
index.insertFeature(f)
for f in feature_dict.values():
print ('Working on %s' % f[_NAME_FIELD])
geom = f.geometry()
intersecting_ids = index.intersects(geom.boundingBox())
neighbors = []
h_n = []
neighbors_sum = 0
for intersecting_id in intersecting_ids:
intersecting_f = feature_dict[intersecting_id]
if (f != intersecting_f and
not intersecting_f.geometry().disjoint(geom)):
neighbors.append(intersecting_f[_NAME_FIELD])
h_n.append(intersecting_f[_H_FIELD])
neighbors_sum += intersecting_f[_SUM_FIELD]
f[_NEW_NEIGHBORS_FIELD] = ','.join(map(str, neighbors))
f[_NEW_H_NEIGHBORS_FIELD] = ','.join(str(x) for x in h_n)
f[_NEW_SUM_FIELD] = neighbors_sum
layer.updateFeature(f)
layer.commitChanges()
print ('Processing complete.')