Skip to content

Commit b710665

Browse files
committed
Added an additional test for haversine
1 parent ce1d8f6 commit b710665

1 file changed

Lines changed: 46 additions & 1 deletion

File tree

python/python-examples/test/test_haversine_distance.py

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
Test for haversine distance.
33
"""
44
import logging as log
5+
import numpy as np
56
from math import radians
67
import pytest
78
from sklearn.metrics.pairwise import haversine_distances
@@ -12,6 +13,11 @@
1213
pytest.param(
1314
[-34.83333, -58.5166646],
1415
[49.0083899664, 2.53844117956]
16+
),
17+
# Google location vs USDA Location
18+
pytest.param(
19+
[39.0168311, -76.92883499999999],
20+
[39.01644, -76.928925]
1521
)
1622
])
1723
def test_calculate_haversince_distance(lat_long_origin:list, lat_long_destination:list):
@@ -28,4 +34,43 @@ def test_calculate_haversince_distance(lat_long_origin:list, lat_long_destinatio
2834
sklearn_distance = km_distance_matrix_result[0][1]
2935
log.info(f"Raw Calc={km_haversine_distance}, Sklearn Calc={sklearn_distance}")
3036
# Rounding both to 8 digits of accuracy...
31-
assert km_haversine_distance == round(km_distance_matrix_result[0][1], 8)
37+
assert km_haversine_distance == round(km_distance_matrix_result[0][1], 8)
38+
39+
40+
def test_shortest_distance():
41+
# Lincoln Memorial Latlong
42+
lincoln_memorial = [38.889248, -77.050636]
43+
44+
# Ducinni's off U St
45+
ducinnis_pizza = [38.91706701509112, -77.04118715785616]
46+
47+
# Admo Jumbo Slice
48+
jumbo_slice_pizza = [38.92105748065034, -77.04170211776945]
49+
50+
# Manny Olgas Near U
51+
manny_olgas = [38.91543818061708, -77.03174726038766]
52+
53+
# Based off Haversine which is closest to Lincoln Memorial
54+
dataset = [
55+
{'name': 'Lincoln Memorial', 'geocode': lincoln_memorial},
56+
{'name': "Ducinni's Pizza", 'geocode': ducinnis_pizza},
57+
{'name': 'Jumbo Slice Pizza', 'geocode': jumbo_slice_pizza},
58+
{'name': "Manny Olga's", 'geocode': manny_olgas}
59+
]
60+
61+
# Put all these in radians
62+
radian_distances = list(map(lambda x: [radians(_) for _ in x['geocode']], dataset))
63+
64+
# Calculate the Haversine Distances
65+
distance_matrix_result = haversine_distances(radian_distances)
66+
67+
# Pull out the first Entry in the 2D array
68+
km_distance_matrix_result = distance_matrix_result * RADIUS_OF_EARTH / 1000
69+
log.info(f"\nDistance Matrix in Kilometers:\n {km_distance_matrix_result}")
70+
71+
# Get the index of the minimum distance for the lincoln memorial
72+
np_array = np.array(km_distance_matrix_result[0][1:])
73+
idx_min = np.argmin(np_array)
74+
# Closest Should be Ducinnis
75+
assert idx_min + 1 == 1
76+
log.info(f"\nClosest Jumbo Slice spot to Lincoln Memorial by Haversine Distance is {dataset[idx_min + 1]['name']}")

0 commit comments

Comments
 (0)