Example usage for org.apache.commons.math.stat.regression SimpleRegression SimpleRegression

List of usage examples for org.apache.commons.math.stat.regression SimpleRegression SimpleRegression

Introduction

In this page you can find the example usage for org.apache.commons.math.stat.regression SimpleRegression SimpleRegression.

Prototype

public SimpleRegression() 

Source Link

Document

Create an empty SimpleRegression instance

Usage

From source file:com.discursive.jccook.math.SimpleRegressionExample.java

public static void main(String[] args) throws MathException {

    SimpleRegression sr = new SimpleRegression();

    // Add data points       
    sr.addData(0, 0);/*  w  ww  .  j  a va  2 s  .  co  m*/
    sr.addData(1, 1.2);
    sr.addData(2, 2.6);
    sr.addData(3, 3.2);
    sr.addData(4, 4);
    sr.addData(5, 5);

    NumberFormat format = NumberFormat.getInstance();

    // Print the value of y when line intersects the y axis
    System.out.println("Intercept: " + format.format(sr.getIntercept()));

    // Print the number of data points
    System.out.println("N: " + sr.getN());

    // Print the Slope and the Slop Confidence
    System.out.println("Slope: " + format.format(sr.getSlope()));
    System.out.println("Slope Confidence: " + format.format(sr.getSlopeConfidenceInterval()));

    // Print RSquare a measure of relatedness
    System.out.println("RSquare: " + format.format(sr.getRSquare()));

    sr.addData(400, 100);
    sr.addData(300, 105);
    sr.addData(350, 70);
    sr.addData(200, 50);
    sr.addData(150, 300);
    sr.addData(50, 500);

    System.out.println("Intercept: " + format.format(sr.getIntercept()));
    System.out.println("N: " + sr.getN());
    System.out.println("Slope: " + format.format(sr.getSlope()));
    System.out.println("Slope Confidence: " + format.format(sr.getSlopeConfidenceInterval()));
    System.out.println("RSquare: " + format.format(sr.getRSquare()));

}

From source file:graticules2wld.Main.java

/**
 * @param args// w  w  w  . jav a  2 s  .  c  o m
 * @throws Exception
 */
public static void main(String[] args) throws Exception {

    /* parse the command line arguments */
    // create the command line parser
    CommandLineParser parser = new PosixParser();

    // create the Options
    Options options = new Options();
    options.addOption("x", "originx", true, "x component of projected coordinates of upper left pixel");
    options.addOption("y", "originy", true, "y component of projected coordinates of upper left pixel");
    options.addOption("u", "tometers", true, "multiplication factor to get source units into meters");
    options.addOption("h", "help", false, "prints this usage page");
    options.addOption("d", "debug", false, "prints debugging information to stdout");

    double originNorthing = 0;
    double originEasting = 0;

    String inputFileName = null;
    String outputFileName = null;

    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("help"))
            printUsage(0); // print usage then exit using a non error exit status

        if (line.hasOption("debug"))
            debug = true;

        // these arguments are required
        if (!line.hasOption("originy") || !line.hasOption("originx"))
            printUsage(1);

        originNorthing = Double.parseDouble(line.getOptionValue("originy"));
        originEasting = Double.parseDouble(line.getOptionValue("originx"));

        if (line.hasOption("tometers"))
            unitsToMeters = Double.parseDouble(line.getOptionValue("tometers"));

        // two args should be left. the input csv file name and the output wld file name.
        String[] iofiles = line.getArgs();
        if (iofiles.length < 2) {
            printUsage(1);
        }

        inputFileName = iofiles[0];
        outputFileName = iofiles[1];
    } catch (ParseException exp) {
        System.err.println("Unexpected exception:" + exp.getMessage());
        System.exit(1);
    }

    // try to open the input file for reading and the output file for writing
    File graticulesCsvFile;
    BufferedReader csvReader = null;

    File wldFile;
    BufferedWriter wldWriter = null;

    try {
        graticulesCsvFile = new File(inputFileName);
        csvReader = new BufferedReader(new FileReader(graticulesCsvFile));
    } catch (IOException exp) {
        System.err.println("Could not open input file for reading: " + inputFileName);
        System.exit(1);
    }

    try {
        wldFile = new File(outputFileName);
        wldWriter = new BufferedWriter(new FileWriter(wldFile));
    } catch (IOException exp) {
        System.err.println("Could not open output file for writing: " + outputFileName);
        System.exit(1);
    }

    // list of lon graticules and lat graticules
    ArrayList<Graticule> lonGrats = new ArrayList<Graticule>();
    ArrayList<Graticule> latGrats = new ArrayList<Graticule>();

    // read the source CSV and convert its information into the two ArrayList<Graticule> data structures
    readCSV(csvReader, lonGrats, latGrats);

    // we now need to start finding the world file paramaters
    DescriptiveStatistics stats = new DescriptiveStatistics();

    // find theta and phi
    for (Graticule g : latGrats) {
        stats.addValue(g.angle());
    }

    double theta = stats.getMean(); // we use the mean of the lat angles as theta
    if (debug)
        System.out.println("theta range = " + Math.toDegrees(stats.getMax() - stats.getMin()));
    stats.clear();

    for (Graticule g : lonGrats) {
        stats.addValue(g.angle());
    }

    double phi = stats.getMean(); // ... and the mean of the lon angles for phi
    if (debug)
        System.out.println("phi range = " + Math.toDegrees(stats.getMax() - stats.getMin()));
    stats.clear();

    // print these if in debug mode
    if (debug) {
        System.out.println("theta = " + Math.toDegrees(theta) + "deg");
        System.out.println("phi = " + Math.toDegrees(phi) + "deg");
    }

    // find x and y (distance beteen pixels in map units)
    Collections.sort(latGrats);
    Collections.sort(lonGrats);
    int prevMapValue = 0; //fixme: how to stop warning about not being initilised?
    Line2D prevGratPixelSys = new Line2D.Double();

    boolean first = true;
    for (Graticule g : latGrats) {
        if (!first) {
            int deltaMapValue = Math.abs(g.realValue() - prevMapValue);
            double deltaPixelValue = (g.l.ptLineDist(prevGratPixelSys.getP1())
                    + (g.l.ptLineDist(prevGratPixelSys.getP2()))) / 2;

            double delta = deltaMapValue / deltaPixelValue;
            stats.addValue(delta);
        } else {
            first = false;
            prevMapValue = g.realValue();
            prevGratPixelSys = (Line2D) g.l.clone();
        }
    }

    double y = stats.getMean();
    if (debug)
        System.out.println("y range = " + (stats.getMax() - stats.getMin()));
    stats.clear();

    first = true;
    for (Graticule g : lonGrats) {
        if (!first) {
            int deltaMapValue = g.realValue() - prevMapValue;
            double deltaPixelValue = (g.l.ptLineDist(prevGratPixelSys.getP1())
                    + (g.l.ptLineDist(prevGratPixelSys.getP2()))) / 2;

            double delta = deltaMapValue / deltaPixelValue;
            stats.addValue(delta);
        } else {
            first = false;
            prevMapValue = g.realValue();
            prevGratPixelSys = (Line2D) g.l.clone();
        }
    }

    double x = stats.getMean();
    if (debug)
        System.out.println("x range = " + (stats.getMax() - stats.getMin()));
    stats.clear();

    if (debug) {
        System.out.println("x = " + x);
        System.out.println("y = " + y);
    }

    SimpleRegression regression = new SimpleRegression();

    // C, F are translation terms: x, y map coordinates of the center of the upper-left pixel
    for (Graticule g : latGrats) {
        // find perp dist to pixel space 0,0
        Double perpPixelDist = g.l.ptLineDist(new Point2D.Double(0, 0));

        // find the map space distance from this graticule to the center of the 0,0 pixel
        Double perpMapDist = perpPixelDist * y; // perpMapDist / perpPixelDist = y

        regression.addData(perpMapDist, g.realValue());
    }

    double F = regression.getIntercept();
    regression.clear();

    for (Graticule g : lonGrats) {
        // find perp dist to pixel space 0,0
        Double perpPixelDist = g.l.ptLineDist(new Point2D.Double(0, 0));

        // find the map space distance from this graticule to the center of the 0,0 pixel
        Double perpMapDist = perpPixelDist * x; // perpMapDist / perpPixelDist = x

        regression.addData(perpMapDist, g.realValue());
    }

    double C = regression.getIntercept();
    regression.clear();

    if (debug) {
        System.out.println("Upper Left pixel has coordinates " + C + ", " + F);
    }

    // convert to meters
    C *= unitsToMeters;
    F *= unitsToMeters;

    // C,F store the projected (in map units) coordinates of the upper left pixel.
    // originNorthing,originEasting is the offset we need to apply to 0,0 to push the offsets into our global coordinate system 
    C = originEasting + C;
    F = originNorthing + F;

    // calculate the affine transformation matrix elements
    double D = -1 * x * unitsToMeters * Math.sin(theta);
    double A = x * unitsToMeters * Math.cos(theta);
    double B = y * unitsToMeters * Math.sin(phi); // if should be negative, it'll formed by negative sin
    double E = -1 * y * unitsToMeters * Math.cos(phi);

    /*
     * Line 1: A: pixel size in the x-direction in map units/pixel
     * Line 2: D: rotation about y-axis
     * Line 3: B: rotation about x-axis
     * Line 4: E: pixel size in the y-direction in map units, almost always negative[3]
     * Line 5: C: x-coordinate of the center of the upper left pixel
     * Line 6: F: y-coordinate of the center of the upper left pixel
     */
    if (debug) {
        System.out.println("A = " + A);
        System.out.println("D = " + D);
        System.out.println("B = " + B);
        System.out.println("E = " + E);
        System.out.println("C = " + C);
        System.out.println("F = " + F);

        // write the world file
        System.out.println();
        System.out.println("World File:");
        System.out.println(A);
        System.out.println(D);
        System.out.println(B);
        System.out.println(E);
        System.out.println(C);
        System.out.println(F);
    }

    // write to the .wld file
    wldWriter.write(A + "\n");
    wldWriter.write(D + "\n");
    wldWriter.write(B + "\n");
    wldWriter.write(E + "\n");
    wldWriter.write(C + "\n");
    wldWriter.write(F + "\n");

    wldWriter.close();
}

From source file:emlab.util.TrendEstimator.java

public static double[] estimateLinearTrend(double[][] input, double[] predictionYears) {
    ;// w  w w.j a v  a2  s.  c o  m
    //Get logarithm of second trend
    SimpleRegression sr = new SimpleRegression();
    sr.addData(input);
    double result[] = new double[predictionYears.length];
    for (int i = 0; i < result.length; i++) {
        result[i] = sr.predict(predictionYears[i]);
    }
    return result;

}

From source file:emlab.util.TrendEstimator.java

public static double[] estimateGeometricTrend(double[][] input, double[] predictionYears) {
    //Get logarithm of second trend
    for (int i = 0; i < input.length; i++) {
        input[i][1] = Math.log(input[i][1]);
    }/*from   w  w  w  .jav a2  s  .co m*/
    //input[1]=log;
    SimpleRegression sr = new SimpleRegression();
    sr.addData(input);
    double result[] = new double[predictionYears.length];
    for (int i = 0; i < result.length; i++) {
        result[i] = Math.exp(sr.predict(predictionYears[i]));
    }
    return result;

}

From source file:msc.fall2015.stock.kmeans.hbase.mapreduce.StockDataReaderMapper.java

public void map(ImmutableBytesWritable row, Result value, Context context)
        throws InterruptedException, IOException {
    SimpleRegression regression;//from w w  w  .  ja  va2 s  . co m
    for (Map.Entry<byte[], NavigableMap<byte[], NavigableMap<Long, byte[]>>> columnFamilyMap : value.getMap()
            .entrySet()) {
        regression = new SimpleRegression();
        int count = 1;
        for (Map.Entry<byte[], NavigableMap<Long, byte[]>> entryVersion : columnFamilyMap.getValue()
                .entrySet()) {
            for (Map.Entry<Long, byte[]> entry : entryVersion.getValue().entrySet()) {
                String rowKey = Bytes.toString(value.getRow());
                String column = Bytes.toString(entryVersion.getKey());
                byte[] val = entry.getValue();
                String valOfColumn = new String(val);
                System.out.println(
                        "RowKey : " + rowKey + " Column Key : " + column + " Column Val : " + valOfColumn);
                if (!valOfColumn.isEmpty()) {
                    String[] priceAndCap = valOfColumn.split("_");
                    if (priceAndCap.length > 1) {
                        String pr = priceAndCap[0];
                        if (pr != null && !pr.equals("null")) {
                            double price = Double.valueOf(pr);
                            if (price < 0) {
                                price = price - 2 * price;
                            }
                            System.out.println("Price : " + price + " count : " + count);
                            regression.addData(count, price);
                        }
                    }
                }
            }
            count++;
        }
        // displays intercept of regression line
        System.out.println("Intercept : " + regression.getIntercept());

        // displays slope of regression line
        System.out.println("Slope : " + regression.getSlope());

        // displays slope standard error
        System.out.println("Slope STD Error : " + regression.getSlopeStdErr());
    }
}

From source file:emlab.role.investment.DCFinvestInPowerGenerationTechnologies.java

SimpleRegression calculateRegressionBasedOnTimeStepsAndSubstance(long startTime, long endTime,
        Substance substance) {/*from  ww  w .j  a v  a 2 s .  c o m*/

    SimpleRegression sr = new SimpleRegression();

    Iterable<ClearingPoint> clearingPoints = reps.clearingPointRepository
            .findAllClearingPointsForSubstanceAndTimeRange(substance, startTime, endTime);

    for (ClearingPoint cp : clearingPoints) {
        sr.addData(cp.getTime(), cp.getPrice());
    }
    return sr;
}

From source file:emlab.util.GeometricTrendRegressionTest.java

@Test
public void testLinearTrendEstimation() {
    double[][] input = { { 0, 1 }, { 1, 1.1 }, { 2, 1.2 }, { 3, 1.3 }, { 4, 1.4 } };
    double[] predictionYears = { 5, 6, 7, 8 };
    double[] expectedResults = { 1.5, 1.6, 1.7, 1.8 };
    SimpleRegression sr = new SimpleRegression();
    sr.addData(input);// w w w .  j  a  v a2  s .c  o m
    for (int i = 0; i < predictionYears.length; i++) {
        assert (expectedResults[i] == sr.predict(predictionYears[i]));
    }
}

From source file:com.joliciel.jochre.boundaries.features.TwoPointSlopeDifferenceFeature.java

@Override
public FeatureResult<Double> checkInternal(Split split, RuntimeEnvironment env) {
    FeatureResult<Double> result = null;
    FeatureResult<Integer> contourDistanceResult = contourDistanceFeature.check(split, env);
    if (contourDistanceResult != null) {
        int contourDistance = contourDistanceResult.getOutcome();

        int[][] verticalContour = split.getShape().getVerticalContour();
        int x = split.getPosition();
        Shape shape = split.getShape();
        int topStart = verticalContour[x][0];
        int bottomStart = verticalContour[x][1];

        SimpleRegression topRightRegression = new SimpleRegression();
        SimpleRegression bottomRightRegression = new SimpleRegression();
        SimpleRegression topLeftRegression = new SimpleRegression();
        SimpleRegression bottomLeftRegression = new SimpleRegression();

        topRightRegression.addData(x, topStart);
        topLeftRegression.addData(x, topStart);
        bottomRightRegression.addData(x, bottomStart);
        bottomLeftRegression.addData(x, bottomStart);

        int[] minTopRight = new int[] { x, topStart };
        int[] minTopLeft = new int[] { x, topStart };
        int[] maxTopRight = new int[] { x, topStart };
        int[] maxTopLeft = new int[] { x, topStart };
        int[] minBottomRight = new int[] { x, bottomStart };
        int[] minBottomLeft = new int[] { x, bottomStart };
        int[] maxBottomRight = new int[] { x, bottomStart };
        int[] maxBottomLeft = new int[] { x, bottomStart };
        for (int i = 1; i <= contourDistance; i++) {
            if (x + i < shape.getWidth()) {
                if (verticalContour[x + i][0] < minTopRight[1])
                    minTopRight = new int[] { x + i, verticalContour[x + i][0] };
                if (verticalContour[x + i][0] > maxTopRight[1])
                    maxTopRight = new int[] { x + i, verticalContour[x + i][0] };

                if (verticalContour[x + i][1] < minBottomRight[1])
                    minBottomRight = new int[] { x + i, verticalContour[x + i][1] };
                if (verticalContour[x + i][1] > maxBottomRight[1])
                    maxBottomRight = new int[] { x + i, verticalContour[x + i][1] };
            }//from ww w  .j  av a  2s . c  om
            if (x - i >= 0) {
                if (verticalContour[x - i][0] < minTopLeft[1])
                    minTopLeft = new int[] { x - i, verticalContour[x - i][0] };
                if (verticalContour[x - i][0] > maxTopLeft[1])
                    maxTopLeft = new int[] { x - i, verticalContour[x - i][0] };

                if (verticalContour[x - i][1] < minBottomLeft[1])
                    minBottomLeft = new int[] { x - i, verticalContour[x - i][1] };
                if (verticalContour[x - i][1] > maxBottomLeft[1])
                    maxBottomLeft = new int[] { x - i, verticalContour[x - i][1] };
            }
        }

        if (minTopRight[0] == x)
            topRightRegression.addData(maxTopRight[0], maxTopRight[1]);
        else
            topRightRegression.addData(minTopRight[0], minTopRight[1]);

        if (minTopLeft[0] == x)
            topLeftRegression.addData(maxTopLeft[0], maxTopLeft[1]);
        else
            topLeftRegression.addData(minTopLeft[0], minTopLeft[1]);

        if (maxBottomRight[0] == x)
            bottomRightRegression.addData(minBottomRight[0], minBottomRight[1]);
        else
            bottomRightRegression.addData(maxBottomRight[0], maxBottomRight[1]);

        if (maxBottomLeft[0] == x)
            bottomLeftRegression.addData(minBottomLeft[0], minBottomLeft[1]);
        else
            bottomLeftRegression.addData(maxBottomLeft[0], maxBottomLeft[1]);

        // get the slopes
        double topRightSlope = topRightRegression.getSlope();
        double bottomRightSlope = bottomRightRegression.getSlope();
        double topLeftSlope = topLeftRegression.getSlope();
        double bottomLeftSlope = bottomLeftRegression.getSlope();

        // convert slopes to angles
        double topRightAngle = Math.atan(topRightSlope);
        double bottomRightAngle = Math.atan(bottomRightSlope);
        double topLeftAngle = Math.atan(topLeftSlope);
        double bottomLeftAngle = Math.atan(bottomLeftSlope);

        // calculate the right & left-hand differences
        double rightDiff = Math.abs(topRightAngle - bottomRightAngle);
        double leftDiff = Math.abs(topLeftAngle - bottomLeftAngle);

        // normalise the differences from 0 to 1
        rightDiff = rightDiff / Math.PI;
        leftDiff = leftDiff / Math.PI;

        double product = rightDiff * leftDiff;

        if (LOG.isTraceEnabled()) {
            LOG.trace("topRightAngle: " + topRightAngle);
            LOG.trace("bottomRightAngle: " + bottomRightAngle);
            LOG.trace("topLeftAngle: " + topLeftAngle);
            LOG.trace("bottomLeftAngle: " + bottomLeftAngle);
            LOG.trace("rightDiff: " + rightDiff);
            LOG.trace("leftDiff: " + leftDiff);
            LOG.trace("product: " + product);
        }

        result = this.generateResult(product);
    }
    return result;
}

From source file:com.joliciel.jochre.boundaries.features.TrueContourSlopeDifferenceFeature.java

@Override
public FeatureResult<Double> checkInternal(Split split, RuntimeEnvironment env) {
    FeatureResult<Double> result = null;
    FeatureResult<Integer> contourDistanceResult = contourDistanceFeature.check(split, env);
    if (contourDistanceResult != null) {
        int contourDistance = contourDistanceResult.getOutcome();

        int[][] verticalContour = split.getShape().getVerticalContour();
        int startX = split.getPosition();
        Shape shape = split.getShape();
        int topStart = verticalContour[startX][0];
        int bottomStart = verticalContour[startX][1];

        SimpleRegression topRightRegression = new SimpleRegression();
        SimpleRegression bottomRightRegression = new SimpleRegression();
        SimpleRegression topLeftRegression = new SimpleRegression();
        SimpleRegression bottomLeftRegression = new SimpleRegression();

        topRightRegression.addData(startX, topStart);
        topLeftRegression.addData(startX, topStart);
        bottomRightRegression.addData(startX, bottomStart);
        bottomLeftRegression.addData(startX, bottomStart);

        int lastTopRight = topStart;
        int lastTopLeft = topStart;
        int lastBottomRight = bottomStart;
        int lastBottomLeft = bottomStart;
        for (int i = 1; i <= contourDistance; i++) {
            int x = startX + i;
            if (x < shape.getWidth()) {
                if (shape.isPixelBlack(x, lastTopRight)) {
                    for (int y = lastTopRight - 1; y >= -1; y--) {
                        if (y < 0 || !shape.isPixelBlack(x, y)) {
                            lastTopRight = y + 1;
                            topRightRegression.addData(x, lastTopRight);
                            break;
                        }//ww  w .  j  a  v  a2s.  co  m
                    }
                } else {
                    for (int y = lastTopRight + 1; y <= shape.getHeight(); y++) {
                        if (y == shape.getHeight() || shape.isPixelBlack(x, y)) {
                            lastTopRight = y;
                            topRightRegression.addData(x, lastTopRight);
                            break;
                        }
                    }
                }
                if (shape.isPixelBlack(x, lastBottomRight)) {
                    for (int y = lastBottomRight + 1; y <= shape.getHeight(); y++) {
                        if (y == shape.getHeight() || !shape.isPixelBlack(x, y)) {
                            lastBottomRight = y - 1;
                            bottomRightRegression.addData(x, lastBottomRight);
                            break;
                        }
                    }
                } else {
                    for (int y = lastBottomRight - 1; y >= -1; y--) {
                        if (y < 0 || shape.isPixelBlack(x, y)) {
                            lastBottomRight = y;
                            bottomRightRegression.addData(x, lastBottomRight);
                            break;
                        }
                    }
                }
            }

            x = startX - i;
            if (x >= 0) {
                if (shape.isPixelBlack(x, lastTopLeft)) {
                    for (int y = lastTopLeft - 1; y >= -1; y--) {
                        if (y < 0 || !shape.isPixelBlack(x, y)) {
                            lastTopLeft = y + 1;
                            topLeftRegression.addData(x, lastTopLeft);
                            break;
                        }
                    }
                } else {
                    for (int y = lastTopLeft + 1; y <= shape.getHeight(); y++) {
                        if (y == shape.getHeight() || shape.isPixelBlack(x, y)) {
                            lastTopLeft = y;
                            topLeftRegression.addData(x, lastTopLeft);
                            break;
                        }
                    }
                }
                if (shape.isPixelBlack(x, lastBottomLeft)) {
                    for (int y = lastBottomLeft + 1; y <= shape.getHeight(); y++) {
                        if (y == shape.getHeight() || !shape.isPixelBlack(x, y)) {
                            lastBottomLeft = y - 1;
                            bottomLeftRegression.addData(x, lastBottomLeft);
                            break;
                        }
                    }
                } else {
                    for (int y = lastBottomLeft - 1; y >= -1; y--) {
                        if (y < 0 || shape.isPixelBlack(x, y)) {
                            lastBottomLeft = y;
                            bottomLeftRegression.addData(x, lastBottomLeft);
                            break;
                        }
                    }
                }
            }
        }

        // get the slopes
        double topRightSlope = topRightRegression.getSlope();
        double bottomRightSlope = bottomRightRegression.getSlope();
        double topLeftSlope = topLeftRegression.getSlope();
        double bottomLeftSlope = bottomLeftRegression.getSlope();

        // convert slopes to angles
        double topRightAngle = Math.atan(topRightSlope);
        double bottomRightAngle = Math.atan(bottomRightSlope);
        double topLeftAngle = Math.atan(topLeftSlope);
        double bottomLeftAngle = Math.atan(bottomLeftSlope);

        // calculate the right & left-hand differences
        double rightDiff = Math.abs(topRightAngle - bottomRightAngle);
        double leftDiff = Math.abs(topLeftAngle - bottomLeftAngle);

        // normalise the differences from 0 to 1
        rightDiff = rightDiff / Math.PI;
        leftDiff = leftDiff / Math.PI;

        double product = rightDiff * leftDiff;

        if (LOG.isTraceEnabled()) {
            LOG.trace("topRightAngle: " + topRightAngle);
            LOG.trace("bottomRightAngle: " + bottomRightAngle);
            LOG.trace("topLeftAngle: " + topLeftAngle);
            LOG.trace("bottomLeftAngle: " + bottomLeftAngle);
            LOG.trace("rightDiff: " + rightDiff);
            LOG.trace("leftDiff: " + leftDiff);
            LOG.trace("product: " + product);
        }

        result = this.generateResult(product);
    }
    return result;
}

From source file:com.joliciel.jochre.boundaries.features.SlopeDifferenceFeature.java

@Override
public FeatureResult<Double> checkInternal(Split split, RuntimeEnvironment env) {
    FeatureResult<Double> result = null;
    FeatureResult<Integer> contourDistanceResult = contourDistanceFeature.check(split, env);
    if (contourDistanceResult != null) {
        int contourDistance = contourDistanceResult.getOutcome();

        int[][] verticalContour = split.getShape().getVerticalContour();
        int x = split.getPosition();
        Shape shape = split.getShape();
        int topStart = verticalContour[x][0];
        int bottomStart = verticalContour[x][1];

        SimpleRegression topRightRegression = new SimpleRegression();
        SimpleRegression bottomRightRegression = new SimpleRegression();
        SimpleRegression topLeftRegression = new SimpleRegression();
        SimpleRegression bottomLeftRegression = new SimpleRegression();

        topRightRegression.addData(x, topStart);
        topLeftRegression.addData(x, topStart);
        bottomRightRegression.addData(x, bottomStart);
        bottomLeftRegression.addData(x, bottomStart);

        for (int i = 1; i <= contourDistance; i++) {
            if (x + i < shape.getWidth()) {
                topRightRegression.addData(x + i, verticalContour[x + i][0]);
                bottomRightRegression.addData(x + i, verticalContour[x + i][1]);
            }/*w w  w .j  av a2 s .  c  o m*/
            if (x - i >= 0) {
                topLeftRegression.addData(x - i, verticalContour[x - i][0]);
                bottomLeftRegression.addData(x - i, verticalContour[x - i][1]);
            }
        }

        // get the slopes
        double topRightSlope = topRightRegression.getSlope();
        double bottomRightSlope = bottomRightRegression.getSlope();
        double topLeftSlope = topLeftRegression.getSlope();
        double bottomLeftSlope = bottomLeftRegression.getSlope();

        // convert slopes to angles
        double topRightAngle = Math.atan(topRightSlope);
        double bottomRightAngle = Math.atan(bottomRightSlope);
        double topLeftAngle = Math.atan(topLeftSlope);
        double bottomLeftAngle = Math.atan(bottomLeftSlope);

        // calculate the right & left-hand differences
        double rightDiff = Math.abs(topRightAngle - bottomRightAngle);
        double leftDiff = Math.abs(topLeftAngle - bottomLeftAngle);

        // normalise the differences from 0 to 1
        rightDiff = rightDiff / Math.PI;
        leftDiff = leftDiff / Math.PI;

        double product = rightDiff * leftDiff;

        if (LOG.isTraceEnabled()) {
            LOG.trace("topRightAngle: " + topRightAngle);
            LOG.trace("bottomRightAngle: " + bottomRightAngle);
            LOG.trace("topLeftAngle: " + topLeftAngle);
            LOG.trace("bottomLeftAngle: " + bottomLeftAngle);
            LOG.trace("rightDiff: " + rightDiff);
            LOG.trace("leftDiff: " + leftDiff);
            LOG.trace("product: " + product);
        }

        result = this.generateResult(product);
    }
    return result;
}