#!/usr/bin/env python
# Exercise (b)
import pylab as n
import numpy.random as r
import sys
import os
def generate (seq_0, start, stop,save=False):
x = n.linspace ( start, stop, 100 )
y = n.poly1d ( seq_0 )
e = r.random_integers ( -250, 250, size=(100) ) * 1e-2
if save:
file = open ( 'xy-points.txt', 'w' )
for i in range ( 100 ):
file.write ( '%f\t%f\n' % ( x[i], y(x[i]) + e[i] ) )
file.close()
else:
return (x, y(x)+e)
def fit_from_file():
file = open ( 'xy-points.txt', 'r' )
x, y = [], []
lines = file.readlines()
file.close()
for line in lines:
line = line.split()
x.append ( float ( line[0] ) )
y.append ( float ( line[1] ) )
fit_curve = n.polyfit ( x, y, 2 )
fit_curve = n.poly1d ( fit_curve )
return x, y, fit_curve(x)
def fit(x,y):
fit_curve = n.polyfit ( x, y, 2 )
fit_curve = n.poly1d ( fit_curve )
return fit_curve(x)
def plotten ( x, y, fit ):
lines = n.plot ( x, y, 'ro', x, fit, 'g:', lw = 3 )
patch = []
a,b = n.argmin(abs(x)), n.argmin(abs(x-n.pi/3.))
F = fit.copy()
F[:a] = 0
F[b:] = 0
n.fill_between(x,fit,y2=0,where=F,alpha=.5,facecolor='c')
n.legend ( [lines], ( 'Datenpunkte', 'Fitkurve' ) )
n.show()
if __name__ == '__main__':
usage_string = """Usage: ./aufg3_2.py -<option>
Values for <option>:
'no-gen <filename>' Do no generate data"""
x,y = None, None
if len(sys.argv) > 1:
if '-no-gen' in sys.argv:
i = sys.argv.index('-no-gen')
if os.path.isfile(sys.argv[i+1]):
x,y,f = fit_from_file()
if not (x and y):
x,y = generate((2,-4,3),-1,5)
f = fit(x,y)
plotten(x,y,f)