WeightedLeastSquaresRegression extends LeastSquaresRegression { @Override public LeastSquaresRegressionResult regress(final double[][] x, final double[][] weights, final double[] y, final boolean useIntercept) { if (weights == null) { throw new IllegalArgumentException("Cannot perform WLS regression without an array of weights"); } checkData(x, weights, y); s_logger .info("Have a two-dimensional array for what should be a one-dimensional array of weights. The weights used in this regression will be the diagonal elements only"); final double[] w = new double[weights.length]; for (int i = 0; i < w.length; i++) { w[i] = weights[i][i]; } return regress(x, w, y, useIntercept); }  @Override LeastSquaresRegressionResult regress(final double[][] x, final double[][] weights, final double[] y, final boolean useIntercept); LeastSquaresRegressionResult regress(final double[][] x, final double[] weights, final double[] y, final boolean useIntercept);  }
@Test public void test() { final double a0 = 2.3; final double a1 = -4.5; final double a2 = 0.76; final double a3 = 3.4; final int n = 30; final double[][] x = new double[n][3]; final double[] yIntercept = new double[n]; final double[] yNoIntercept = new double[n]; final double[][] w1 = new double[n][n]; final double[] w2 = new double[n]; double y, x1, x2, x3; for (int i = 0; i < n; i++) { x1 = i; x2 = x1 * x1; x3 = Math.sqrt(x1); x[i] = new double[] {x1, x2, x3}; y = x1 * a1 + x2 * a2 + x3 * a3; yNoIntercept[i] = y; yIntercept[i] = y + a0; for (int j = 0; j < n; j++) { w1[i][j] = RANDOM.nextDouble(); } w1[i][i] = 1.; w2[i] = 1.; } final WeightedLeastSquaresRegression wlsRegression = new WeightedLeastSquaresRegression(); final OrdinaryLeastSquaresRegression olsRegression = new OrdinaryLeastSquaresRegression(); try { wlsRegression.regress(x, (double[]) null, yNoIntercept, false); Assert.fail(); } catch (final IllegalArgumentException e) { } LeastSquaresRegressionResult wls = wlsRegression.regress(x, w1, yIntercept, true); LeastSquaresRegressionResult ols = olsRegression.regress(x, yIntercept, true); assertRegressions(n, 4, wls, ols); wls = wlsRegression.regress(x, w1, yNoIntercept, false); ols = olsRegression.regress(x, yNoIntercept, false); assertRegressions(n, 3, wls, ols); wls = wlsRegression.regress(x, w2, yIntercept, true); ols = olsRegression.regress(x, yIntercept, true); assertRegressions(n, 4, wls, ols); wls = wlsRegression.regress(x, w2, yNoIntercept, false); ols = olsRegression.regress(x, yNoIntercept, false); assertRegressions(n, 3, wls, ols); }