1 package org.simantics.spreadsheet.graph.formula;
3 import org.apache.commons.math3.stat.regression.OLSMultipleLinearRegression;
4 import org.simantics.spreadsheet.graph.CellFormulaFunction;
5 import org.simantics.spreadsheet.graph.CellValueVisitor;
6 import org.simantics.spreadsheet.graph.SpreadsheetGraphUtils;
7 import org.simantics.spreadsheet.graph.SpreadsheetMatrix;
8 import org.simantics.spreadsheet.graph.parser.ast.AstArgList;
10 public class LinestFormulaFunction implements CellFormulaFunction<SpreadsheetMatrix> {
13 public SpreadsheetMatrix evaluate(CellValueVisitor visitor, AstArgList args) {
14 if (args.values.size() != 4)
15 throw new IllegalStateException();
17 Object ys = args.values.get(0).accept(visitor);
18 Object xs = args.values.get(1).accept(visitor);
20 if (xs instanceof SpreadsheetMatrix) {
22 OLSMultipleLinearRegression reg = new OLSMultipleLinearRegression();
24 SpreadsheetMatrix xsm = (SpreadsheetMatrix) xs;
25 SpreadsheetMatrix ysm = (SpreadsheetMatrix) ys;
27 if (xsm.getWidth() > 1) {
29 double y[] = new double[ysm.values.length];
30 double x[][] = new double[ysm.values.length][xsm.getWidth()];
32 for (int i = 0; i < ysm.values.length; i++) {
33 y[i] = SpreadsheetGraphUtils.asNumber(ysm.values[i]);
34 for (int j = 0; j < xsm.getWidth(); j++) {
35 x[i][j] = SpreadsheetGraphUtils.asNumber(xsm.get(i, j));
39 reg.newSampleData(y, x);
41 int width = xsm.getWidth() + 1;
42 SpreadsheetMatrix result = new SpreadsheetMatrix(width, 5);
43 double[] pars = reg.estimateRegressionParameters();
44 for (int i = 0; i < width; i++)
45 result.set(0, width - i - 1, pars[i]);
46 double[] errs = reg.estimateRegressionParametersStandardErrors();
47 for (int i = 0; i < width; i++)
48 result.set(1, width - i - 1, errs[i]);
50 double sstotal = reg.calculateTotalSumOfSquares();
51 double ssresid = reg.calculateResidualSumOfSquares();
52 double ssreg = sstotal - ssresid;
54 double r2 = ssreg / sstotal;
55 double sey = reg.estimateRegressionStandardError();
59 result.set(2, 1, sey);
62 result.set(4, 0, ssreg);
63 result.set(4, 1, ssresid);
64 result.set(2,2, FormulaError2.NA.getString());
65 result.set(3,2, FormulaError2.NA.getString());
66 result.set(4,2, FormulaError2.NA.getString());