package org.fda.regression;


import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.apache.commons.math3.stat.regression.OLSMultipleLinearRegression;
import org.fda.data.Reference;
import org.fda.data.ReferenceSet;
import org.apache.commons.math3.linear.SingularMatrixException;
/**
 *
 * @author Gokhan.Yavas
 */
public class RegressionModule {
    private static RegressionSubModel getModel(List<DataValue> alldata, Reference r){
        RegressionSubModel rm=null;
        Collections.sort(alldata); 
        int lowIndex=0;
        int highIndex = alldata.size()-1;

        double[] y = new double[highIndex-lowIndex+1];
        double[][] x = new double[highIndex-lowIndex+1][];

        for(int z=lowIndex; z<=highIndex; z++){
            y[z-lowIndex] = alldata.get(z).getMis();
            x[z-lowIndex]= new double[]{alldata.get(z).getLength(), alldata.get(z).getThre()}; 
        }

        OLSMultipleLinearRegression regression = new OLSMultipleLinearRegression();
        regression.newSampleData(y, x);                                
        try{
            double[] beta = regression.estimateRegressionParameters();                       
            rm =new RegressionSubModel(beta[1], beta[2], beta[0], alldata); 
        }
        catch(SingularMatrixException ex){
            //System.out.println("No solution to the regression model for "+r.getRefID()+", setting the coefficients to 0");
            rm =new RegressionSubModel(0, 0, 0, alldata); 
        }

        return rm;
        
    }
    
    public static RegressionModel process(Map<Reference, List<DataValue>> alldata, ReferenceSet chrset){
        RegressionModel rm = new RegressionModel(chrset, alldata);
               
        for(Reference r : alldata.keySet()){           
            rm.addSubModel(r, getModel(alldata.get(r), r));
        }        
        return rm;
    }
    
}
