# Fixing the maximum distance within a cluster

I am trying to cluster geographical locations in such a way that all the locations inside each cluster are at max within 25 miles of each other. For this, I am using Agglomerative clustering. I am using a custom distance function to calculate the distances between each location. I do not want to specify the number of clusters. Instead, I want the model to cluster until all the locations within each cluster are within 25 miles of each other. I have tried doing this in both Scipy and Sklearn but haven't made any progress. Below is the approach that I have tried. It only gives me one cluster. Please help. Thanks in advance.

from scipy.cluster.hierarchy import fclusterdata

max_dist = 25
# dist is a custom function that calculates the distance (in miles) between two locations using the geographical coordinates

fclusterdata(locations_in_RI[['Latitude', 'Longitude']].values, t=max_dist, metric=dist, criterion='distance')

• This is in general a difficult problem. I have had success with simulated spatial annealing (SSA). – whuber Mar 19 '19 at 14:26
• Is there any way I can do this using Python? – Karthik Katragadda Mar 19 '19 at 14:38
• I'm sure there is. I don't know of any Python implementations of SSA offhand, so you would have to research that. – whuber Mar 19 '19 at 16:35

You need to use method="complete" otherwise it will not be a pairwise limit, obviously.