Created
March 31, 2015 17:47
-
-
Save gicmo/c9bc76e76902f3e5872d to your computer and use it in GitHub Desktop.
Fit a sine using least squares
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import numpy as np | |
import scipy.optimize as optimize | |
import matplotlib.pylab as plt | |
import csv | |
import argparse | |
def main(): | |
parser = argparse.ArgumentParser(description='iris - sine fitter') | |
parser.add_argument('data', type=str) | |
args = parser.parse_args() | |
x = [] | |
y = [] | |
with open(args.data, 'rb') as csvfile: | |
reader = csv.reader(csvfile, delimiter=',', quotechar='#') | |
for row in reader: | |
x.append(float(row[0])) | |
y.append(float(row[1])) | |
x = np.array(x) | |
y = np.array(y) | |
def func(p, x): | |
return p[2] + p[0] * np.sin(x - p[1]) | |
def fitfunc(p, x, y): | |
return y - func(p, x) | |
kd,cov,infodict,mesg,ier = optimize.leastsq(fitfunc, (0.2, 1.9, 0.67), args=(x, y), full_output=True) | |
#print (kd, cov, infodict, mesg, ier) | |
print(kd) | |
x_uq = np.unique(x) | |
y_fit = func(kd, x_uq) | |
plt.scatter(x, y, color='dodgerblue', label='data') | |
plt.plot(x_uq, y_fit, 'k--') | |
plt.show() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment