import numpy as np
import matplotlib.pyplot as plt
from numpy.polynomial.polynomial import Polynomial
points = [
(0,1),
(0.01,1.03),
(0.02,1.03),
(0.03,1.06),
(0.04,1.18),
(0.05,1.38),
(0.06,1.63),
(0.07,2.09),
(0.08,2.69),
(0.09,3.54),
(0.1,4.79),
(0.11,6.41),
(0.12,8.9),
(0.13,12.06),
(0.14,16.36),
(0.15,22.1),
(0.16,29.48),
(0.17,39.05),
(0.18,50.99),
(0.19,65.32),
(0.2,81.79),
(0.21,99.78),
(0.22,117.72),
(0.23,134.26),
(0.24,146.9),
(0.25,153.68)]
x = np.array([point[0] for point in points])
y = np.array([point[1] for point in points])
spl = Polynomial.fit(x, y, 16) # highest order without ringing
roots_arr = [0,0.10]
for n in range(1,5):
dspl = spl.deriv(n)
roots = dspl.roots()
for r in roots:
if isinstance(r,complex):
if abs(r.imag) > 0.001:
continue
r = r.real
if not (0.11 < r < 0.25):
continue
r = round(r, 2)
if r == 0.24:
continue
roots_arr.append(r)
roots = np.array(roots_arr)
x_fine = np.linspace(0, 0.25, 1000)
y_fine = spl(x_fine)
# check fit
if False:
y_spl_err = spl(x)-y
plt.plot(x,y_spl_err,'.')
plt.show()
plt.plot(x_fine,y_fine,'-',x,y,'.')
plt.show()
roots_y = spl(roots)
plt.plot(x_fine,y_fine,'-',roots,roots_y,'o')
plt.grid(False)
plt.axis('off')
for i in range(len(roots)):
plt.annotate(f'{roots_y[i]:.0f}x @ {roots[i]:.2f}%', (roots[i], roots_y[i]), textcoords="offset points", xytext=(0,10), ha='right')
plt.savefig('BAC_driving_risk.svg')
plt.show()