# What algorithm does QGIS use to calculate Nearest Neighbor Index?

I'm carrying out nearest neighbor analysis on a set of geological features in QGIS, trying to find out whether they're clustered or not. I've calculated the nearest neighbor distances using the 'Distance Matrix' tool and I'm now exploring the 'Nearest Neighbor Analysis' tool.

Does anyone out there know what the algorithms behind the NN Analysis tool are? What method does it use to generate its expected distance and NN index (comparison with Poisson points?)? How does it measure the area? e.g. does it use minimum convex hull or minimum bounding rectangle?

I became a bit suspicious when I tried the tool on a set of randomly generated points, it returned NN index values of 0.81 and a Z-score of -2.5, indicating clustering in what should be randomly distributed points.

Can anyone shed any light on this? I've tried to find more information in the QGIS documentation, but there's not information about the algorithms that are used to calculate these values.

You can check the source code for the Nearest Neighbour Analysis tool from GitHub. More specifically, the following lines of code which shows how the different parameters are calculated:

``````do = float(sumDist) / count
de = float(0.5 / math.sqrt(count / A))
d = float(do / de)
SE = float(0.26136 / math.sqrt(( count ** 2) / A))
zscore = float((do - de) / SE)
``````

where

``````do = "Observed mean distance"
de = "Expected mean distance"
d = "Nearest neighbour index"
zscore = "Z-Score"
``````
• So D_e is the theoretical expected value on an infinite plane and does not account for study area boundaries. – Nate Wessel Sep 25 '18 at 16:37
• A = layer.extent() – Christophe Nov 20 '18 at 11:24