package app.PREDICTION;

/**
 * Created by Petr Flégl on 23.1.2017.
 */
public class MultiLinearRegression {

    Matrix x;
    Matrix y;
    boolean bias;



    public MultiLinearRegression(Matrix x, Matrix y, boolean bias){

        this.x = x;
        this.y = y;
        this.bias = bias;


    }

    public Matrix calculate() throws NoSquareException {
        if (bias)
            this.x = x.insertColumnWithValue1();
        checkDiemnsion();
        Matrix Xtr = MatrixMathematics.transpose(x); //X'
        Matrix XXtr = MatrixMathematics.multiply(Xtr,x); //X'X
        Matrix inverse_of_XXtr = MatrixMathematics.inverse(XXtr); //(X'X)^-1
        if (inverse_of_XXtr == null) {
            return null;
        }
        Matrix XtrY = MatrixMathematics.multiply(Xtr,y); //X'Y
        return MatrixMathematics.multiply(inverse_of_XXtr,XtrY); //(X'X)^-1 X'Y
    }
    void checkDiemnsion() {
        if (x == null)
            throw new NullPointerException("X matrix cannot be null.");
        if (y == null)
            throw new NullPointerException("Y matrix cannot be null.");

        if (x.getNcols() > x.getNrows()) {
            throw new IllegalArgumentException("The number of columns in X matrix (descriptors) cannot be more than the number of rows");
        }
        if (x.getNrows() != y.getNrows()) {
            throw new IllegalArgumentException("The number of rows in X matrix should be the same as the number of rows in Y matrix. ");
        }
    }

}
