This depends on how you define inter-cluster distance. There are a number of ways to do it.
Let us take a the endpoints of the distances being measured to be the centers of the clusters of turtles.
While this is a good technique for, say, K-means clustering, it doesn't work as well for DBSCAN as the clusters can be concave. Thus, the center may be outside of the cluster! Regardless, I'll include as an option.
First, let's define our distance measure:
Mean distance between points in clusters:
to-report cluster-distance [ cluster1 cluster2 ]
report mean [ mean [ distance myself ] of cluster2 ] of cluster1
end
Minimum distance between points in clusters:
to-report cluster-distance [ cluster1 cluster2 ]
report min [ min [ distance myself ] of cluster2 ] of cluster1
end
Distance between centroids
Assuming world wrapping is off:
to-report cluster-distance [ cluster1 cluster2 ]
let x1 mean [ xcor ] of cluster1
let y1 mean [ ycor ] of cluster1
let x2 mean [ xcor ] of cluster2
let y2 mean [ ycor ] of cluster2
report sqrt ((x1 - x2) ^ 2 + (y1 - y2) ^ 2)
end
If world wrapping is on
; This is super complicated because, with wrapping on, xcor and ycor are
; more like angles rather than cartesian coordinates. So, this converts
; them to angles, gets the mean of those angles, and converts them back.
; Related SO question: https://stackoverflow.com/questions/24786908/get-mean-heading-of-neighboring-turtles
to-report xcor-mean [ xcors ]
let angles map [ x -> 360 * (x - (min-pxcor - 0.5)) / world-width ] xcors
let mean-x mean map cos angles
let mean-y mean map sin angles
report (atan mean-y mean-x) / 360 * world-width + (min-pxcor - 0.5)
end
to-report ycor-mean [ ycors ]
let angles map [ y -> 360 * (y - (min-pycor - 0.5)) / world-height ] ycors
let mean-x mean map cos angles
let mean-y mean map sin angles
report (atan mean-y mean-x) / 360 * world-height + (min-pycor - 0.5)
end
to-report cluster-distance [ cluster1 cluster2 ]
let x1 xcor-mean [ xcor ] of cluster1
let y1 ycor-mean [ ycor ] of cluster1
let x2 xcor-mean [ xcor ] of cluster2
let y2 ycor-mean [ ycor ] of cluster2
report sqrt ((x1 - x2) ^ 2 + (y1 - y2) ^ 2)
end
Averaging the distances
Once we have a distance measure, getting the average distance is relatively simple using map
. Note that the remove
below is necessary as we don't want to include a cluster's distance to itself in the mean. Note also that this code is a little inefficient in that it calculates all distances twice, but that also greatly simplifies it:
...
; This line is modified so that we get a list of turtle sets rather than
; a list of lists.
let clusters map turtle-set dbscan:cluster-by-location red-grey-turtles 3 3
let avg-distance mean map [ c1 ->
mean map [ c2 ->
cluster-distance c1 c2
] remove c1 clusters ; Get distance to all other clusters but c1
] clusters