Java Code Examples for org.apache.commons.math3.stat.regression.SimpleRegression#addData()

The following examples show how to use org.apache.commons.math3.stat.regression.SimpleRegression#addData() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AlgorithmUtil.java    From LibreAlarm with GNU General Public License v3.0 6 votes vote down vote up
@NonNull
private static PredictionData getPredictionData(int attempt, String tagId, ArrayList<GlucoseData> trendList) {
    PredictionData predictedGlucose = new PredictionData();
    SimpleRegression regression = new SimpleRegression();
    for (int i = 0; i < trendList.size(); i++) {
        regression.addData(trendList.size() - i, (trendList.get(i)).glucoseLevel);
    }
    predictedGlucose.glucoseLevel = (int)regression.predict(15 + PREDICTION_TIME);
    predictedGlucose.trend = regression.getSlope();
    predictedGlucose.confidence = regression.getSlopeConfidenceInterval();
    predictedGlucose.errorCode = PredictionData.Result.OK;
    predictedGlucose.realDate = trendList.get(0).realDate;
    predictedGlucose.sensorId = tagId;
    predictedGlucose.attempt = attempt;
    predictedGlucose.sensorTime = trendList.get(0).sensorTime;
    return predictedGlucose;
}
 
Example 2
Source File: Calibration.java    From orbit-image-analysis with GNU General Public License v3.0 6 votes vote down vote up
public double getSlope(BufferedImage bi1, BufferedImage bi2, int u, int v,  int s, int n) throws IOException {
   
    Raster r1 = bi1.getRaster().createTranslatedChild(0,0);
    Raster r2 = bi2.getRaster().createTranslatedChild(0,0);
    if (r1.getNumBands()>1) throw new IllegalArgumentException("only 1-banded rasters allowed here");
    if (r2.getNumBands()>1) throw new IllegalArgumentException("only 1-banded rasters allowed here");
    SimpleRegression reg = new SimpleRegression(true);
    int minX = u<0?u*-1:0;
    int minY = v<0?v*-1:0;
    int maxX = u>0?bi1.getWidth()-u: bi1.getWidth();
    int maxY = v>0?bi1.getHeight()-v: bi1.getHeight();
    for (int x=minX; x<maxX; x++) {
         for (int y=minY; y<maxY; y++) {
             double d1 = r1.getSampleDouble(x+u,y+v,0);
             if (d1> intensityThreshold) {
                 double d2 = r2.getSampleDouble(x, y, 0);
                 reg.addData(d2, d1);
             }
         }
     }

    double slope = reg.getSlope();
    double intercept = reg.getIntercept();
    logger.info("i,j: "+s+","+n+": "+ "slope: "+slope+" ; intercept: "+intercept);
    return slope;
}
 
Example 3
Source File: TestRealRegrInterceptAggregation.java    From presto with Apache License 2.0 5 votes vote down vote up
private void testNonTrivialAggregation(Float[] y, Float[] x)
{
    SimpleRegression regression = new SimpleRegression();
    for (int i = 0; i < x.length; i++) {
        regression.addData(x[i], y[i]);
    }
    float expected = (float) regression.getIntercept();
    checkArgument(Float.isFinite(expected) && expected != 0.f, "Expected result is trivial");
    testAggregation(expected, createBlockOfReals(y), createBlockOfReals(x));
}
 
Example 4
Source File: SurfactantAnalysis.java    From act with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Perform linear regression over a list of X/Y coordinates
 * @param coords A set of coordinates over which to perform linear regression.
 * @return The slope and intercept of the regression line.
 */
public Pair<Double, Double> performRegressionOverXYPairs(List<Pair<Double, Double>> coords) {
  SimpleRegression regression = new SimpleRegression(true);
  for (Pair<Double, Double> c : coords) {
    regression.addData(c.getLeft(), c.getRight());
  }
  // Note: the regress() call can raise an exception for small molecules.  We should probably handle that gracefully.
  RegressionResults result = regression.regress();
  return Pair.of(regression.getSlope(), regression.getIntercept());
}
 
Example 5
Source File: StraightLineProblem.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Directly solve the linear problem, using the {@link SimpleRegression}
 * class.
 */
public double[] solve() {
    final SimpleRegression regress = new SimpleRegression(true);
    for (double[] d : points) {
        regress.addData(d[0], d[1]);
    }

    final double[] result = { regress.getSlope(), regress.getIntercept() };
    return result;
}
 
Example 6
Source File: StraightLineProblem.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Directly solve the linear problem, using the {@link SimpleRegression}
 * class.
 */
public double[] solve() {
    final SimpleRegression regress = new SimpleRegression(true);
    for (double[] d : points) {
        regress.addData(d[0], d[1]);
    }

    final double[] result = { regress.getSlope(), regress.getIntercept() };
    return result;
}
 
Example 7
Source File: StraightLineProblem.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Directly solve the linear problem, using the {@link SimpleRegression}
 * class.
 */
public double[] solve() {
    final SimpleRegression regress = new SimpleRegression(true);
    for (double[] d : points) {
        regress.addData(d[0], d[1]);
    }

    final double[] result = { regress.getSlope(), regress.getIntercept() };
    return result;
}
 
Example 8
Source File: PearsonsCorrelation.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Computes the Pearson's product-moment correlation coefficient between the two arrays.
 *
 * </p>Throws IllegalArgumentException if the arrays do not have the same length
 * or their common length is less than 2</p>
 *
 * @param xArray first data array
 * @param yArray second data array
 * @return Returns Pearson's correlation coefficient for the two arrays
 * @throws DimensionMismatchException if the arrays lengths do not match
 * @throws MathIllegalArgumentException if there is insufficient data
 */
public double correlation(final double[] xArray, final double[] yArray) {
    SimpleRegression regression = new SimpleRegression();
    if (xArray.length != yArray.length) {
        throw new DimensionMismatchException(xArray.length, yArray.length);
    } else if (xArray.length < 2) {
        throw new MathIllegalArgumentException(LocalizedFormats.INSUFFICIENT_DIMENSION,
                                               xArray.length, 2);
    } else {
        for(int i=0; i<xArray.length; i++) {
            regression.addData(xArray[i], yArray[i]);
        }
        return regression.getR();
    }
}
 
Example 9
Source File: StraightLineProblem.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Directly solve the linear problem, using the {@link SimpleRegression}
 * class.
 */
public double[] solve() {
    final SimpleRegression regress = new SimpleRegression(true);
    for (double[] d : points) {
        regress.addData(d[0], d[1]);
    }

    final double[] result = { regress.getSlope(), regress.getIntercept() };
    return result;
}
 
Example 10
Source File: StraightLineProblem.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Directly solve the linear problem, using the {@link SimpleRegression}
 * class.
 */
public double[] solve() {
    final SimpleRegression regress = new SimpleRegression(true);
    for (double[] d : points) {
        regress.addData(d[0], d[1]);
    }

    final double[] result = { regress.getSlope(), regress.getIntercept() };
    return result;
}
 
Example 11
Source File: PearsonsCorrelation.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Computes the Pearson's product-moment correlation coefficient between the two arrays.
 *
 * </p>Throws IllegalArgumentException if the arrays do not have the same length
 * or their common length is less than 2</p>
 *
 * @param xArray first data array
 * @param yArray second data array
 * @return Returns Pearson's correlation coefficient for the two arrays
 * @throws DimensionMismatchException if the arrays lengths do not match
 * @throws MathIllegalArgumentException if there is insufficient data
 */
public double correlation(final double[] xArray, final double[] yArray) {
    SimpleRegression regression = new SimpleRegression();
    if (xArray.length != yArray.length) {
        throw new DimensionMismatchException(xArray.length, yArray.length);
    } else if (xArray.length < 2) {
        throw new MathIllegalArgumentException(LocalizedFormats.INSUFFICIENT_DIMENSION,
                                               xArray.length, 2);
    } else {
        for(int i=0; i<xArray.length; i++) {
            regression.addData(xArray[i], yArray[i]);
        }
        return regression.getR();
    }
}
 
Example 12
Source File: StraightLineProblem.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Directly solve the linear problem, using the {@link SimpleRegression}
 * class.
 */
public double[] solve() {
    final SimpleRegression regress = new SimpleRegression(true);
    for (double[] d : points) {
        regress.addData(d[0], d[1]);
    }

    final double[] result = { regress.getSlope(), regress.getIntercept() };
    return result;
}
 
Example 13
Source File: TestDoubleRegrSlopeAggregation.java    From presto with Apache License 2.0 5 votes vote down vote up
private void testNonTrivialAggregation(Double[] y, Double[] x)
{
    SimpleRegression regression = new SimpleRegression();
    for (int i = 0; i < x.length; i++) {
        regression.addData(x[i], y[i]);
    }
    double expected = regression.getSlope();
    checkArgument(Double.isFinite(expected) && expected != 0.0, "Expected result is trivial");
    testAggregation(expected, createDoublesBlock(y), createDoublesBlock(x));
}
 
Example 14
Source File: StraightLineProblem.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Directly solve the linear problem, using the {@link SimpleRegression}
 * class.
 */
public double[] solve() {
    final SimpleRegression regress = new SimpleRegression(true);
    for (double[] d : points) {
        regress.addData(d[0], d[1]);
    }

    final double[] result = { regress.getSlope(), regress.getIntercept() };
    return result;
}
 
Example 15
Source File: TestRealRegrInterceptAggregation.java    From presto with Apache License 2.0 5 votes vote down vote up
@Override
protected Object getExpectedValue(int start, int length)
{
    if (length <= 1) {
        return null;
    }
    SimpleRegression regression = new SimpleRegression();
    for (int i = start; i < start + length; i++) {
        regression.addData(i + 2, i);
    }
    return (float) regression.getIntercept();
}
 
Example 16
Source File: Similarity.java    From mzmine2 with GNU General Public License v2.0 4 votes vote down vote up
public SimpleRegression getRegression(double[][] data) {
  SimpleRegression reg = new SimpleRegression();
  reg.addData(data);
  return reg;
}
 
Example 17
Source File: Similarity.java    From mzmine3 with GNU General Public License v2.0 4 votes vote down vote up
public SimpleRegression getRegression(double[][] data) {
  SimpleRegression reg = new SimpleRegression();
  reg.addData(data);
  return reg;
}
 
Example 18
Source File: Similarity.java    From mzmine3 with GNU General Public License v2.0 4 votes vote down vote up
public SimpleRegression getRegression(double[][] data) {
  SimpleRegression reg = new SimpleRegression();
  reg.addData(data);
  return reg;
}
 
Example 19
Source File: MainApp - Simple Regression.java    From Java-for-Data-Science with MIT License 4 votes vote down vote up
@Override
    public void start(Stage stage) {

//Belgium	1950	8639369
//Belgium	1960	9118700
//Belgium	1970	9637800
//Belgium	1980	9846800
//Belgium	1990	9969310
//Belgium	2000	10263618
        double[][] input = {
            {1950, 8639369},
            {1960, 9118700},
            {1970, 9637800},
            {1980, 9846800},
            {1990, 9969310},
            {2000, 10263618}};
        double[] predictionYears = {1950, 1960, 1970, 1980, 1990, 2000, 2010, 2020, 2030, 2040};

        NumberFormat yearFormat = NumberFormat.getNumberInstance();
        yearFormat.setMaximumFractionDigits(0);
        yearFormat.setGroupingUsed(false);
        NumberFormat populationFormat = NumberFormat.getNumberInstance();
        populationFormat.setMaximumFractionDigits(0);
        
        SimpleRegression regression = new SimpleRegression();
        regression.addData(input);
        projectedSeries.setName("Projected");
        for (int i = 0; i < predictionYears.length; i++) {
            out.println(yearFormat.format(predictionYears[i]) + "-"
                    + populationFormat.format(regression.predict(predictionYears[i])));
            addDataItem(projectedSeries, predictionYears[i],
                    regression.predict(predictionYears[i]));
        }

        displayAttribute("Slope",regression.getSlope());
        displayAttribute("Intercept", regression.getIntercept());
        displayAttribute("InterceptStdEr", regression.getInterceptStdErr());
        displayAttribute("MeanSquareError", regression.getMeanSquareError());
        displayAttribute("N", + regression.getN());
        displayAttribute("R", + regression.getR());
        displayAttribute("RSquare", regression.getRSquare());

        //Create index chart
        stage.setTitle("Simple Linear Regression");
        xAxis.setTickLabelFormatter(new StringConverter<Number>() {
            @Override
            public String toString(Number object) {
                return (object.intValue()) + "";
            }

            @Override
            public Number fromString(String string) {
                return 0;
            }
        });

        final LineChart<Number, Number> lineChart
                = new LineChart<>(xAxis, yAxis);
        lineChart.setTitle("Belgium Population");
        yAxis.setLabel("Population");

        originalSeries.setName("Actual");
        addDataItem(originalSeries, 1950, 8639369);
        addDataItem(originalSeries, 1960, 9118700);
        addDataItem(originalSeries, 1970, 9637800);
        addDataItem(originalSeries, 1980, 9846800);
        addDataItem(originalSeries, 1990, 9969310);
        addDataItem(originalSeries, 2000, 10263618);

        Scene scene = new Scene(lineChart, 800, 600);
        lineChart.getData().addAll(originalSeries, projectedSeries);
        stage.setScene(scene);
        stage.show();
    }
 
Example 20
Source File: ListGrid.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public Grid addRegressionColumn( int columnIndex, boolean addHeader )
{
    verifyGridState();

    SimpleRegression regression = new SimpleRegression();

    List<Object> column = getColumn( columnIndex );

    int index = 0;

    for ( Object value : column )
    {
        // 0 omitted from regression

        if ( value != null && !MathUtils.isEqual( Double.parseDouble( String.valueOf( value ) ), 0d ) )
        {
            regression.addData( index++, Double.parseDouble( String.valueOf( value ) ) );
        }
    }

    List<Object> regressionColumn = new ArrayList<>();

    for ( int i = 0; i < column.size(); i++ )
    {
        final double predicted = regression.predict( i );

        // Enough values must exist for regression

        if ( !Double.isNaN( predicted ) )
        {
            regressionColumn.add( Precision.round( predicted, 1 ) );
        }
        else
        {
            regressionColumn.add( null );
        }
    }

    addColumn( regressionColumn );

    if ( addHeader && columnIndex < headers.size() )
    {
        GridHeader header = headers.get( columnIndex );

        if ( header != null )
        {
            GridHeader regressionHeader = new GridHeader( header.getName() + REGRESSION_SUFFIX,
                header.getColumn() + REGRESSION_SUFFIX, header.getValueType(), header.getType(), header.isHidden(), header.isMeta() );

            addHeader( regressionHeader );
        }
    }

    return this;
}