Skip to content

Instantly share code, notes, and snippets.

@carlossless
Last active February 14, 2018 09:18
Show Gist options
  • Save carlossless/a8cf4196952eba56987c to your computer and use it in GitHub Desktop.
Save carlossless/a8cf4196952eba56987c to your computer and use it in GitHub Desktop.
A python script to find three coefficients that best fit empyrical data for the d=A*(r/t)^B+C rssi to distance conversion formula
from scipy.optimize import leastsq
import matplotlib.pyplot as plt
import numpy as np
# d=A*(r/t)^B+C
d = [0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0,1.2,1.4,1.6,1.8,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0,12.0,14.0,16.0,18.0,20.0,25]
r = [-20.64,-24.09,-27.55,-31.73,-35.27,-33.91,-31.36,-28.09,-32,-49.64,-52,-54.64,-55.18,-57.18,-58.64,-59.27,-72.55,-67.73,-66.65,-70,-68,-71,-74,-76,-83,-77,-83,-80,-80,-76]
t = -52.5
x = map(lambda r: r / t, r)
def residuals(p, d, x):
A, B, C = p
err = d - (A * x**B + C)
return err
p0 = [8.0, 1 / 2.3e-2, 3.14 / 3.0]
plsq = leastsq(residuals, p0, args=(d, x), factor=0.1)
def peval(x, p):
return p[0] * x**p[1] + p[2]
def drange(start, stop, step):
r = start
while r < stop:
yield r
r += step
x_true = list(drange(0.0, 1.7, 0.01))
plt.plot(map(lambda x_true: x_true * t, x_true), peval(x_true, plsq[0]), map(lambda x: x * t, x), d, '.')
plt.axis([-100, 0, -4, 50])
plt.title('Least-squares fit to noisy data')
plt.legend(['Fit', 'Noisy', 'True'])
plt.show()
print "A: %f, B: %f, C: %f" % (plsq[0][0], plsq[0][1], plsq[0][2])
@varadig
Copy link

varadig commented Feb 9, 2017

Hi, can you help me, how can I use this formula with real rssi values, to distance calculation?

@carlossless
Copy link
Author

A bit late here... But basically this piece of code is used to find approximations for values A, B and C through curve fitting via leastsq. So you can later apply these found values in the formula d=A*(r/t)^B+C that is explained here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment