Skip to content

Instantly share code, notes, and snippets.

@XavierTolza
Created September 28, 2021 15:59
Show Gist options
  • Save XavierTolza/e1846509b0afbc9f2170efb5606147c3 to your computer and use it in GitHub Desktop.
Save XavierTolza/e1846509b0afbc9f2170efb5606147c3 to your computer and use it in GitHub Desktop.
Fit 1st order
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import minimize
from scipy.signal import lfilter
t = np.linspace(0, 10, 1000)
y = (1 - np.exp(-t / 1))
y += np.random.normal(0, 0.05, y.shape)
# plt.plot(t, y)
# plt.show()
def get_ba(x, order=1):
b, a = x[:2 + order - 1], x[2 + order - 1:]
return b, a
def get_y(x, *args):
return lfilter(*get_ba(x, *args), t)
def f(x, *args, **kwargs):
res = np.linalg.norm(y - get_y(x, *args, **kwargs))
return res
order = 1
x0 = np.array([1, -1, 1, -1])
res = minimize(f, x0, args=(order,))
y_found = get_y(res.x, order)
plt.plot(t, y, label="data")
plt.plot(t, y_found, ls=':', label="fit")
plt.legend()
plt.show()
print(res.x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment