from Scientific.Functions.LeastSquares import leastSquaresFit
import math

class lsq:

    def __init__(self, data, M, token):
    
        self.data = data
        self.nbonds = int(M.nbonds)
        
        self.token = token
        self.lsq()

    def model(self,params, values):
        ''' This function build the equation for the force and submits it. '''
        
        x = []
        y = []
        f = 0
       
        for q in params:
            x.append(q)
        
        for q in values:
            y.append(q)
            
        for q in range(0,self.nbonds):
            f += x[q]*y[q]*y[q]

        return (  f  )
     
    def recursive(self,q,s):
         
            ''' This function is related to lsq and will build a equation file of the form:
        
        	(x, x*x, x*x*x, x*x*y, x*y*x, x*y*y, x*y, y, y*y, y*y*y)
        	if self.param_set = (x,y) and self.basis = 3 
        	It is not used in our current method - the equation file is built
        	in the model function'''
            
            for t in self.param_set[q:]:
                if len(s) <= self.basis:
                    self.set.append(s+'*'+t)
                recursive(q,s+t)

    def lsq(self):
        ''' This function uses the external program leastSquaresFit to develop the force constants.
    	
    		self.data is the list of values in the form: [((x1,y1,...),z1), ((x2,y2,...),z2) ... ]
    			where the numbers are the deviation of the particular element from the norm.
    		self.parameters is the length of parameters needed (ie the number of variables) and has the form:
    			[0,0,...]''' 
   
        num_var = len(self.data[0][0])
        
        self.parameters = [0]*num_var

        self.params, self.chisquared = leastSquaresFit(self.model, self.parameters, self.data)
        
##        for i in range(0,len(self.params)):
##                print i," ",self.params[i]
##                
        print 'ChiSquared'
        print self.chisquared
        
