public LeastSquaresRegressionResult regress(double[][] x, double[] weights, double[] y, boolean useIntercept) {
if (weights == null) {
throw new IllegalArgumentException("Cannot perform WLS regression without an array of weights");
}
checkData(x, weights, y);
double[][] dep = addInterceptVariable(x, useIntercept);
double[] w = new double[weights.length];
for (int i = 0; i < y.length; i++) {
w[i] = weights[i];
}
DoubleMatrix matrix = DoubleMatrix.copyOf(dep);
DoubleArray vector = DoubleArray.copyOf(y);
RealMatrix wDiag = new DiagonalMatrix(w);
DoubleMatrix transpose = ALGEBRA.getTranspose(matrix);
DoubleMatrix wDiagTimesMatrix = DoubleMatrix.ofUnsafe(wDiag.multiply(
new Array2DRowRealMatrix(matrix.toArrayUnsafe())).getData());
DoubleMatrix tmp = (DoubleMatrix) ALGEBRA.multiply(
ALGEBRA.getInverse(ALGEBRA.multiply(transpose, wDiagTimesMatrix)), transpose);
DoubleMatrix wTmpTimesDiag =
DoubleMatrix.copyOf(wDiag.preMultiply(new Array2DRowRealMatrix(tmp.toArrayUnsafe())).getData());
DoubleMatrix betasVector = (DoubleMatrix) ALGEBRA.multiply(wTmpTimesDiag, vector);
double[] yModel = super.writeArrayAsVector(((DoubleMatrix) ALGEBRA.multiply(matrix, betasVector)).toArray());
double[] betas = super.writeArrayAsVector(betasVector.toArray());
return getResultWithStatistics(x, convertArray(wDiag.getData()), y, betas, yModel, transpose, matrix, useIntercept);
}