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)

# limit the range by killing data points if R value is less than R_lim_low
R_lim_low = 0.3
index_kill=[]
for counter in range (0,len(R)):
    if R[counter] < R_lim_low:
        index_kill.append(counter)

R = numpy.delete(R,index_kill)
I = numpy.delete(I,index_kill)
dR = numpy.delete(dR,index_kill)    
dI = numpy.delete(dI,index_kill) 

# calculate the log10 of the data and the associated uncertainties
x = numpy.log10(R)
y = numpy.log10(I)
dy = dI/(I*numpy.log(10))
dx = dR/(R*numpy.log(10))
 

# define the fit function (NOTE THE INDENT!)
def fit_function(x, a):
    return  (a - x)

# set the array of initial value(s)
initial_values = (numpy.log10(5.))

# make the simple calculations needed for the linear fit
n = len(x)
a = numpy.sum(x/n+y/n)
delta_a = numpy.sqrt(numpy.sum(dy**2+dx**2)/n**2)

# calculate the resulting chisquare and the number of dof
chisq = ((y - fit_function(x, a))**2/(dy**2+dx**2)).sum()
ndof = len(x) - 1

# calculate V_0 and delta V_0 from a and delta a
V0 = 10**a
deltaV0 = delta_a * (10**a) *a/10

# print the results on the console (with bellurie)
print('a = %f +- %f' % (a, delta_a))
print('V_0 = %f +- %f' % (V0, deltaV0))
print('Chisquare/ndof = %f/%d' % (chisq, ndof))

# bellurie 
pylab.rc('font',size=16)
pylab.xlabel('log(R/R0) , with R0 = 1 kohm')
pylab.ylabel('log(I/I0) , with I0 = 1 mA')

pylab.title('Analytical fit of the linearized subset')

# data plot
pylab.errorbar(x,y,dy,dx,linestyle = '', color = 'black', marker = '.')

func_grid = numpy.linspace(numpy.log10(R_lim_low), 3, 100)
pylab.plot(func_grid, fit_function(func_grid, a), color = 'black')

# save the plot as a pdf file somewhere (in my own directories!)
pylab.savefig('D:/stash/dida14_15/lab2_14_15/lin_vs_num/fig3.pdf')

# show the plot on screen
pylab.show()





# bellurie 
pylab.rc('font',size=16)
pylab.xlabel('log(R)')
pylab.ylabel('log(I)')
pylab.minorticks_on()
pylab.title('Fit of a subset with a linear model')

# data plot
pylab.errorbar(x,y,dy,dx,linestyle = '', color = 'black', marker = '.')

func_grid = numpy.linspace(numpy.log10(R_lim_low), 3, 100)
pylab.plot(func_grid, a-func_grid, color = 'black')

# calculate the resulting chisquare and the number of dof
#chisq = (((y - (a - x))/(dy+numpy.abs(dx/y)))**2).sum()
chisq = ((y - (a - x))**2/(dy**2+(dx/y)**2)).sum()
ndof = len(x) - 1

V0 = 10**a; dV0 = da/a

# print the results on the console (with bellurie)
print('V_0 = %f +- %f' % (V0, dV0))
print('Chisquare/ndof = %f/%d' % (chisq, ndof))

# save the plot as a pdf file somewhere (in my own directories!)
pylab.savefig('D:/stash/dida14_15/lab2_14_15/lin_vs_num/fig2.pdf')

# show the plot on screen
pylab.show()

