# Reglin.py computes and displays mean value and the slope (linear regression)
#   Copyright (C) 2009  Jacques Flamand
#
#    This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.
#------------------------------------------------------------------------------

# compute and display the mean value and the slope (linear regresion)
# for a set of value read from a file which name is given as argument

import sys
filename=sys.argv[1]
# first compute the number of values (n)
f=open(filename, 'r')
n=0
for line in f:
  n=n+1
print 'Number of values :',n
#create a list of x values arbitrarly starting from 1
x=[0]    # create list
x[:]=[]  #empty list
for i in range(n) :
  x=x+[i+1.0]
print 'x serie :', x
#create a list with each values from the input files as character strings
f=open(filename, 'r')
ychar=f.readlines()
f.close()
#create another list with each values from the input files as floats
y=[0]
y[:]=[]
for yc in ychar :
  y=y+[float(yc)]
print 'y serie :', y
# compute the mean value of x :
xmean=0
for z in x :
  xmean=xmean+z
xmean=xmean/n  
print 'mean value of x : ', xmean
# compute the mean value of y :
ymean=0
for z in y :
  ymean=ymean+z
ymean=ymean/n  
print 'mean value of y : ', ymean
#compute the slope (formulas from http://fr.wikipedia.org/wiki/R%C3%A9gression_lin%C3%A9aire)
SXY=0
i=0
for z in y :
  SXY=SXY+((x[i]-xmean)*(z-ymean))
  i=i+1
SXY=SXY/n
print 'SXY : ',SXY   
S2X=0
for z in x :
  S2X=S2X+(z-xmean)**2
S2X=S2X/n
print 'S2X : ',S2X
slope=SXY/S2X
print 'slope : ',slope

 
 
  















