Skip to content

Instantly share code, notes, and snippets.

@cpatdowling
Created February 15, 2022 01:15
Show Gist options
  • Save cpatdowling/b4d6b2a56a7f43741465e3f8d1d1a1ea to your computer and use it in GitHub Desktop.
Save cpatdowling/b4d6b2a56a7f43741465e3f8d1d1a1ea to your computer and use it in GitHub Desktop.
This is an example of using sklearn's haversine distance to compute pairwise distances between lat-long pairs. This is then used to find locations or in this instance blockfaces at incremental distances away from each known location
### compute pairwise distnances
from sklearn.metrics.pairwise import haversine_distances
import numpy as np
#here we make up a bunch of random coordinates
lats = np.random.uniform(45,47,size=(100,))
longs = np.random.uniform(-120,-100,size=(100,))
coords = list(zip(lats, longs))
#this list of coords would map to unique blockfaces/element keys
#for a list of lat long pairs
coords_in_rads = [np.radians(pair) for pair in coords]
pairwise_angular_distances = haversine_distances(coords_in_rads)
pairwise_distance_in_meters = pairwise_angular_distances * 6371000
#the list of coords, this matrix records the distnace in meters between two blockfaces
#such that elements i and j of the coordinate list, pairwise_distance_in_meters[i,j] is the
#distance between them
print(pairwise_distance_in_meters)
distance_increment = 1e4 #increment in 1km amounts, for example, this would be median blockface
#length in our case
for k in range(1,13): #fix some number of steps away we consider
#here we create a temporary dict that will store blockface indecies as keys, and a
#list of neighbors within distance k
blockface_to_neigbors = {}
for i in range(len(coords)):
blockface_to_neighbors[i] = []
#get the arguments of coord list that are block-faces within k*1km of blockface number 5
distances = np.where(pairwise_distance_in_meters > k*1000)
#we might use this to get blockfaces boundary "blockfaces away" distances
#distances = np.where((pairwise_distance_in_meters < (k+1)*1000) & (pairwise_distance_in_meters > k*1000))
for i, source in enumerate(list(distances[0])):
blockface_to_neighbors[source].append(distances[1][i])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment