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)

# define the fit function (NOTE THE INDENT!)
def fit_function(f, V0, fT):
    return  (V0/numpy.sqrt(1+(f/fT)**2))

# set the array of initial value(s) (IN THE FORM OF A LIST)
initial_values = [10.,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], pars[1]))/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 parameters: ', pars)
print('Uncertainty on fit parameters: ', numpy.sqrt(covm.diagonal()))
print('Covariance matrix: ',covm)

# determine the "correlation" and print it on the console
# (NOTE THE SYNTAX)
print('"Correlation": ',covm[0,1]/(numpy.sqrt(covm[0,0])*numpy.sqrt(covm[1,1])))

# 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 two parameters')

# 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], pars[1]), 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/fig22.pdf')

# show the plot on screen
pylab.show()