Skip to content

Commit

Permalink
add haversine
Browse files Browse the repository at this point in the history
  • Loading branch information
shaunwbell committed Feb 6, 2024
1 parent 4eb2e44 commit 99c7000
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
43 changes: 43 additions & 0 deletions src/ecofocipy/math/haversine.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#!/usr/bin/env python
# Haversine formula example in Python
# Author: Wayne Dyck

import math
import numpy as np

def distance(origin, destination):
lat1, lon1 = origin
lat2, lon2 = destination
radius = 6371 # km

dlat = math.radians(lat2-lat1)
dlon = math.radians(lon2-lon1)
a = math.sin(dlat/2) * math.sin(dlat/2) + math.cos(math.radians(lat1)) \
* math.cos(math.radians(lat2)) * math.sin(dlon/2) * math.sin(dlon/2)
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
d = radius * c

return d

def nearest_point(origin, latpoints, lonpoints, grid='1d'):

if grid == '1d':
dist = np.zeros((np.shape(latpoints)[0], np.shape(lonpoints)[0]))

for i, lat in enumerate(latpoints):
for j, lon in enumerate(lonpoints):
dist[i,j] = distance(origin,[lat,lon])

lati, loni = np.where(dist == dist.min())
return (dist.min(), latpoints[lati[0]], lonpoints[loni[0]], lati[0], loni[0] )

elif grid == '2d':
dist = np.zeros_like(latpoints)

for i, latrow in enumerate(latpoints):
for j, lonrow in enumerate(latrow):
dist[i,j] = distance(origin,[latpoints[i,j],lonpoints[i,j]])

lati, loni = np.where(dist == dist.min())

return (dist.min(), latpoints[lati[0]][loni[0]], lonpoints[lati[0]][loni[0]], lati[0], loni[0] )
1 change: 0 additions & 1 deletion tools/find_closest_ctd.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@
import mysql.connector

# User defined
import io_utils.ConfigParserLocal as ConfigParserLocal
import calc.haversine as sphered

__author__ = "Shaun Bell"
Expand Down

0 comments on commit 99c7000

Please sign in to comment.