Skip to content

Instantly share code, notes, and snippets.

@len0rd
Forked from superjax/lookup_table_generator.py
Created July 25, 2017 17:22
Show Gist options
  • Save len0rd/194cb419349d7025afba5bce53ff376a to your computer and use it in GitHub Desktop.
Save len0rd/194cb419349d7025afba5bce53ff376a to your computer and use it in GitHub Desktop.
Barometer Lookup Table python generator file
import numpy as np
import os
import matplotlib.pyplot as plt
def f(pressure):
return ((1.0 - pow(pressure/101325.0, 0.190284)) * 145366.45) * 0.3048
def finv(alt):
return 101325.0*(1-2.25577*10**-5 * alt) ** 5.25588
max_alt = 3048 # 10,000 feet
min_alt = -430 # -1400 feet (dead sea)
max_pressure = finv(min_alt)
min_pressure = finv(max_alt)
num_entries = 500
x = np.arange(min_pressure, max_pressure, (max_pressure - min_pressure) / num_entries)
lookup_table = [round(10*f(i)) for i in x]
def fast_alt(pressure):
dx = (max_pressure - min_pressure) / num_entries
global lookup_table
t = (pressure - min_pressure) / (max_pressure - min_pressure) * num_entries
index = int(t)
dp = t - index
if index >= num_entries:
out = min_alt
elif index < num_entries - 1:
out = lookup_table[index]/10.0 + dp * (lookup_table[index + 1] - lookup_table[index])/10.0
else:
out = lookup_table[index]/10.0 + dp * (lookup_table[index] - lookup_table[index - 1])/10.0
return out
def fast_alt_no_interp(pressure):
dx = (max_pressure - min_pressure) / num_entries
global lookup_table
t = (pressure - min_pressure) / (max_pressure - min_pressure) * num_entries
index = int(t)
return lookup_table[index]
y = np.arange(min_pressure, max_pressure, (max_pressure - min_pressure)/(num_entries*100))
fast = [fast_alt(i) for i in y]
truth = [f(i) for i in y]
error = [abs(i - j) for i, j in zip(fast, truth)]
file = open('table.txt', 'w')
count = 0
file.write("static const int32_t max_pressure = %d;\n" % max_pressure)
file.write("static const int32_t min_pressure = %d;\n" % min_pressure)
file.write("static const int16_t num_entries = %d;\n" % num_entries)
file.write("static const int16_t dx = %d;\n" % ((max_pressure - min_pressure) / num_entries) )
file.write("static const int16_t lookup_table[%s] = {\n" % int(len(lookup_table)))
for i in lookup_table:
count += 1
if count == 10:
file.write("%s,\n" % int(i))
count = 0
else:
file.write("%s,\t" % int(i))
file.seek(-2, os.SEEK_END)
file.truncate()
file.write("\n};")
plt.figure(1)
# plt.plot(y, [fast_alt_no_interp(i) for i in y])
plt.plot(y, [fast_alt(i) for i in y], "o")
plt.plot(y, [f(i) for i in y])
plt.figure(2)
plt.plot(y, error)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment