-
Notifications
You must be signed in to change notification settings - Fork 0
/
optimaze-1.py
39 lines (29 loc) · 1.17 KB
/
optimaze-1.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#Suppose it is believed some measured data follow a sinusoidal pattern
#y_i=Asin(2*pi*k*x_i + theta)
#where the parameters A, k , and theta are unknown. The residual vector is
#e_i=|y_i - A*sin(2*pi*k*x_i+ theta)|
#By defining a function to compute the residuals and (selecting an appropriate starting position),
#the least-squares fit routine can be used to find the best-fit parameters
#\hat{A},\,\hat{k},\,\hat{\theta}. This is shown in the following example:
from numpy import arange, sin, pi, random, array
x = arange(0, 6e-2, 6e-2 / 30)
A, k, theta = 10, 1.0 / 3e-2, pi / 6
y_true = A * sin(2 * pi * k * x + theta)
y_meas = y_true + 2*random.randn(len(x))
def residuals(p, y, x):
A, k, theta = p
err = y - A * sin(2 * pi * k * x + theta)
return err
def peval(x, p):
return p[0] * sin(2 * pi * p[1] * x + p[2])
p0 = [8, 1 / 2.3e-2, pi / 3]
print(array(p0))
from scipy.optimize import leastsq
plsq = leastsq(residuals, p0, args=(y_meas, x))
print(plsq[0])
print(array([A, k, theta]))
import matplotlib.pyplot as plt
plt.plot(x, peval(x, plsq[0]),x,y_meas,'o',x,y_true)
plt.title('Least-squares fit to noisy data')
plt.legend(['Fit', 'Noisy', 'True'])
plt.show()