import pylab
import numpy
from scipy.optimize import curve_fit

# data load
R,I,dR,dI=pylab.loadtxt('D:/stash/dida14_15/lab2_14_15/fitte_ohm/data.txt',unpack=True)

# set the constant parameter(s)
V0 = 4.94

# define the fit function (NOTE THE INDENT!)
def fit_function(R, rint):
    return  (V0/(R+rint))

# set the array of initial value(s)
initial_values = (0.1)

# call the minimization procedure (NOTE THE ARGUMENTS)
pars, covm = curve_fit(fit_function, R, I, initial_values, dI)

# extract the estimated standard deviation of the parameter(s) 
delta_rint = numpy.sqrt(covm.diagonal())

# calculate the resulting chisquare and the number of dof
chisq = (((I - fit_function(R, pars))/dI)**2).sum()
ndof = len(R) - len(pars)

# print the results on the console (with bellurie)
print('r_int = %f +- %f' % (pars, delta_rint))
print('Chisquare/ndof = %f/%d' % (chisq, ndof))

# bellurie 
pylab.rc('font',size=16)
pylab.xlabel('R  [kohm]')
pylab.ylabel('I  [mA]')
pylab.xscale('log'); pylab.yscale('log')
pylab.title('Fit with one parameter')

# data plot
pylab.errorbar(R,I,dI,dR,linestyle = '', color = 'black', marker = '.')

func_grid = numpy.logspace(-2, 3, 100)
pylab.plot(func_grid, fit_function(func_grid, pars), color = 'black')

# the following three lines are needed if you want to have the
# residual plot superposed to data and best-fit
#pylab.plot(R,I-fit_function(R,pars),'bs')
#pylab.xlim(1e-2,1e3)
#pylab.legend(['data','best-fit','residuals'],fontsize=14)
#pylab.title('Fit with one parameter and residual plot')

# save the plot as a pdf file somewhere (in my own directories!)
pylab.savefig('D:/stash/dida14_15/lab2_14_15/fitte_ohm/fig6.pdf')

# show the plot on screen
pylab.show()