Skip to content

Instantly share code, notes, and snippets.

@maxineauma
Created June 27, 2019 04:26
Show Gist options
  • Save maxineauma/eefaacc248e9206006183a0e0d533a32 to your computer and use it in GitHub Desktop.
Save maxineauma/eefaacc248e9206006183a0e0d533a32 to your computer and use it in GitHub Desktop.
trilateration method w/ distance
# All of these should be installed with pip:
from geopy.distance import great_circle
import pandas as pd
import numpy as np
import statsmodels.formula.api as smf
import scipy
# Location of each WAP and distance to each (RSSI should be used to calculate the approximate distances)
# This is all just sample data, and should be replaced with actual data.
locations = {
'latitude': [40.208606, 40.208760, 40.208605, 40.208432, 40.208343, 40.208329], # each latitude value
'longitude': [-74.040819, -74.041015, -74.040785, -74.040731, -74.041041, -74.040804], # each longitude value
'distance': [38.45, 25.61, 41.34, 51.13, 38.04, 52.33] # each distance from device to each lat,long value
}
locations_df = pd.DataFrame(data=locations)
# haversine distance formula
def haversine(lon1, lat1, lon2, lat2):
lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2])
dlon = lon2 - lon1
dlat = lat2 - lat1
a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2.0)**2
c = 2 * np.arcsin(np.sqrt(a))
km = 6367 * c
m = km*1000
return m
# mean squared error
def mse(x, locations, distances):
mse = 0.0
for location, distance in zip(locations, distances):
distance_calculated = haversine(x[0], x[1], location[0], location[1])
mse += np.power(distance_calculated - distance, 2.0)
return mse / len(locations)
loc = []
for lat, lon in zip(locations_df['latitude'], locations_df['longitude']):
loc.append([lat,lon])
dis = locations_df['distance']
# calculate the coordinate estimate
result = scipy.optimize.minimize(
mse,
[np.mean(locations_df['latitude']),np.mean(locations_df['longitude'])],
args=(loc,dis),
method='L-BFGS-B',
options={
'ftol':1e-02,
'maxiter':1000
}
)
print(result.x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment