import pylab
import numpy
from scipy.optimize import curve_fit

# data load
f,V,df,dV=pylab.loadtxt('D:/stash/dida13_14/lab2_13_14/bode/lp.txt',unpack=True)
# set the parameter
V0 = 9.9

# define the fit function (NOTE THE INDENT!)
def fit_function(f, fT):
    return  (V0/numpy.sqrt(1+(f/fT)**2))

# set the array of initial value(s) (IN THE FORM OF A LIST)
initial_values = [5.e2]

# call the minimization procedure (NOTE THE ARGUMENTS)
pars, covm = curve_fit(fit_function, f, V, initial_values, dV)

# calculate the resulting chisquare and the number of dof
chisq = (((V - fit_function(f, pars[0]))/dV)**2).sum()
ndof = len(f) - len(pars)

# print the results on the console in an "expert" mode
print('Chisquare/ndof = %f/%d' % (chisq, ndof))
print('Fit parameter(s): ', pars)
print('Uncertainty on fit parameter(s): ', numpy.sqrt(covm.diagonal()))

# bellurie 
pylab.rc('font',size=16)
pylab.xlabel('$f$  [Hz]')
pylab.ylabel('$V_{out}$  [V]')
pylab.xscale('log'); pylab.yscale('log')
pylab.xlim(80,1.1e5)
pylab.ylim(4.e-2,11.)
pylab.title('Low-pass: fit with one parameter')

# data plot (NOTE THE ORDER OF ARGUMENTS)
pylab.errorbar(f,V,dV,df,linestyle = '', color = 'black', marker = '.')

func_grid = numpy.logspace(2, 5, 100)
pylab.plot(func_grid, fit_function(func_grid, pars[0]), color = 'black')

# save the plot as a pdf file somewhere (in my own directories!)
pylab.savefig('D:/stash/dida14_15/lab2_14_15/bode_14_15/fig1.pdf')

# show the plot on screen
pylab.show()