List of usage examples for org.apache.commons.math.stat.descriptive DescriptiveStatistics getPercentile
public double getPercentile(double p)
From source file:cal.binBased.BinMSnSpectrum.java
public double[] getBin_spectrum(int shift) { ArrayList<Double> bin_spec_al = new ArrayList<Double>(); double binSize = (fragment_tolerance * 2), upperLimit = max_value + 0.00001; for (double lowerLimit = min_value; lowerLimit < upperLimit; lowerLimit = lowerLimit + binSize) { double tmp_intensity_bin = 0; DescriptiveStatistics obj = new DescriptiveStatistics(); for (Peak p : peakList) { double mz = p.getMz() + shift; if (mz >= lowerLimit && mz < lowerLimit + binSize) { obj.addValue(p.intensity); }/*from w w w. ja v a 2 s . c o m*/ } if (obj.getN() > 0) { if (intensities_sum_or_mean_or_median == 0) { tmp_intensity_bin = obj.getSum(); } else if (intensities_sum_or_mean_or_median == 1) { tmp_intensity_bin = obj.getMean(); } else if (intensities_sum_or_mean_or_median == 2) { tmp_intensity_bin = obj.getPercentile(50); } } // put every bin_pectrum bin_spec_al.add(tmp_intensity_bin); } // convert an arraylist to double array // initiate size of array bin_size = bin_spec_al.size(); double[] bin_spectrum = new double[bin_spec_al.size()]; for (int i = 0; i < bin_spec_al.size(); i++) { bin_spectrum[i] = bin_spec_al.get(i); } return bin_spectrum; }
From source file:cal.binBased.BinMSnSpectrum.java
private ArrayList<double[]> prepareBinSpectra() { // first prepare bin-spectrum to be filled with zero int size = (2 * correctionFactor) + 1; ArrayList<double[]> shiftedSpectra = new ArrayList<double[]>(size); for (int i = 0; i < size; i++) { double[] shiftedSpectrum = new double[bin_size]; shiftedSpectra.add(shiftedSpectrum); }/*ww w . j av a 2 s. c o m*/ // now fill each bin spectrum with correct mz values. double binSize = (fragment_tolerance * 2), upperLimit = max_value + 0.00001; int current_index = 0; for (double lowerLimit = min_value + correctionFactor; lowerLimit < upperLimit - correctionFactor; lowerLimit = lowerLimit + binSize) { double tmp_intensity_bin = 0; DescriptiveStatistics obj = new DescriptiveStatistics(); for (Peak p : peakList) { double mz = p.getMz(); if (mz >= lowerLimit && mz < lowerLimit + binSize) { obj.addValue(p.intensity); } } if (obj.getN() > 0) { if (intensities_sum_or_mean_or_median == 0) { tmp_intensity_bin = obj.getSum(); } else if (intensities_sum_or_mean_or_median == 1) { tmp_intensity_bin = obj.getMean(); } else if (intensities_sum_or_mean_or_median == 2) { tmp_intensity_bin = obj.getPercentile(50); } } // put every bin_pectrum int filling_index = current_index; // check every bin spectrum for (double[] shifted : shiftedSpectra) { shifted[filling_index] = tmp_intensity_bin; filling_index++; } current_index++; } return shiftedSpectra; }
From source file:info.raack.appliancedetection.evaluation.model.EvaluationGroup.java
private void calculateEvaluationMetrics( Map<ApplianceEnergyConsumptionDetectionAlgorithm, List<Evaluation>> evaluationInfo) { for (ApplianceEnergyConsumptionDetectionAlgorithm algorithm : evaluationInfo.keySet()) { // do wattage stats DescriptiveStatistics stats = new DescriptiveStatistics(); List<Evaluation> evaluationList = evaluationInfo.get(algorithm); if (evaluationList.size() == 0) { throw new IllegalArgumentException( "No evaluations for " + algorithm + " in simulation group " + simulationGroup); }// w w w. j a v a2 s . com for (Evaluation evaluation : evaluationList) { // calculation produces watts stats.addValue((double) (evaluation.getOverallEnergyError()) * (3600.0 / (double) (evaluation.getSimulation().getDurationInSeconds()))); } errorMetrics.put(algorithm, new Double[] { stats.getMean(), stats.getPercentile(50), stats.getStandardDeviation() }); // stats = new DescriptiveStatistics(); evaluationList = evaluationInfo.get(algorithm); if (evaluationList.size() == 0) { throw new IllegalArgumentException( "No evaluations for " + algorithm + " in simulation group " + simulationGroup); } for (Evaluation evaluation : evaluationList) { // calculation produces watts stats.addValue((double) (evaluation.getOverallAccuracy())); } accuracyErrorMetrics.put(algorithm, new Double[] { stats.getMean(), stats.getPercentile(50), stats.getStandardDeviation() }); // stats = new DescriptiveStatistics(); evaluationList = evaluationInfo.get(algorithm); if (evaluationList.size() == 0) { throw new IllegalArgumentException( "No evaluations for " + algorithm + " in simulation group " + simulationGroup); } for (Evaluation evaluation : evaluationList) { // calculation produces watts stats.addValue((double) (evaluation.getStateTransitionAccuracy())); } stateTransitionAccuracyErrorMetrics.put(algorithm, new Double[] { stats.getMean(), stats.getPercentile(50), stats.getStandardDeviation() }); // stats = new DescriptiveStatistics(); evaluationList = evaluationInfo.get(algorithm); if (evaluationList.size() == 0) { throw new IllegalArgumentException( "No evaluations for " + algorithm + " in simulation group " + simulationGroup); } for (Evaluation evaluation : evaluationList) { // calculation produces watts stats.addValue((double) (evaluation.getStateTransitionRecall())); } stateTransitionRecallErrorMetrics.put(algorithm, new Double[] { stats.getMean(), stats.getPercentile(50), stats.getStandardDeviation() }); // stats = new DescriptiveStatistics(); evaluationList = evaluationInfo.get(algorithm); if (evaluationList.size() == 0) { throw new IllegalArgumentException( "No evaluations for " + algorithm + " in simulation group " + simulationGroup); } for (Evaluation evaluation : evaluationList) { // calculation produces watts stats.addValue((double) (evaluation.getStateTransitionPrecision())); } stateTransitionPrecisionErrorMetrics.put(algorithm, new Double[] { stats.getMean(), stats.getPercentile(50), stats.getStandardDeviation() }); } }
From source file:com.joliciel.jochre.graphics.SourceImageImpl.java
@Override public List<Rectangle> getWhiteAreas(List<Shape> shapes) { LOG.debug("#### getWhiteAreas ####"); // Delimit area to be examined based on shapes int top = Integer.MAX_VALUE, bottom = 0, left = Integer.MAX_VALUE, right = 0; for (Shape shape : shapes) { if (shape.getTop() < top) top = shape.getTop();/*from w w w . ja v a2 s.com*/ if (shape.getBottom() > bottom) bottom = shape.getBottom(); if (shape.getLeft() < left) left = shape.getLeft(); if (shape.getRight() > right) right = shape.getRight(); } // get average shape width & height DescriptiveStatistics shapeWidthStats = new DescriptiveStatistics(); DescriptiveStatistics shapeHeightStats = new DescriptiveStatistics(); for (Shape shape : shapes) { shapeWidthStats.addValue(shape.getWidth()); shapeHeightStats.addValue(shape.getHeight()); } double averageShapeWidth = shapeWidthStats.getPercentile(75); double averageShapeHeight = shapeHeightStats.getPercentile(75); LOG.debug("averageShapeWidth: " + averageShapeWidth); LOG.debug("averageShapeHeight: " + averageShapeHeight); List<Rectangle> whiteAreas = new ArrayList<Rectangle>(); // Horizontal white areas double minHorizontalWhiteAreaWidth = 40.0 * averageShapeWidth; double minHorizontalWhiteAreaHeight = 2.5 * averageShapeHeight; LOG.debug("minHorizontalWhiteAreaWidth: " + minHorizontalWhiteAreaWidth); LOG.debug("minHorizontalWhiteAreaHeight: " + minHorizontalWhiteAreaHeight); WhiteAreaFinder whiteAreaFinder = new WhiteAreaFinder(); List<Rectangle> blackAreas = new ArrayList<Rectangle>(); blackAreas.addAll(shapes); List<Rectangle> horizontalWhiteAreas = whiteAreaFinder.getWhiteAreas(blackAreas, left, top, right, bottom, minHorizontalWhiteAreaWidth, minHorizontalWhiteAreaHeight); // we add the horizontal white areas to the "black areas", since we don't want vertical // white areas detected at page top & page bottom, splitting a valid row blackAreas.addAll(horizontalWhiteAreas); whiteAreas.addAll(horizontalWhiteAreas); // Long vertical white areas double minVerticalWhiteAreaWidth = 2.5 * averageShapeWidth; double minVerticalWhiteAreaHeight = 10.0 * averageShapeHeight; LOG.debug("minVerticalWhiteAreaWidth: " + minVerticalWhiteAreaWidth); LOG.debug("minVerticalWhiteAreaHeight: " + minVerticalWhiteAreaHeight); List<Rectangle> verticalWhiteAreas = whiteAreaFinder.getWhiteAreas(blackAreas, left, top, right, bottom, minVerticalWhiteAreaWidth, minVerticalWhiteAreaHeight); whiteAreas.addAll(verticalWhiteAreas); // Square white areas double minSquareWhiteAreaWidth = 4.0 * averageShapeWidth; double minSquareWhiteAreaHeight = 4.0 * averageShapeHeight; LOG.debug("minSquareWhiteAreaWidth: " + minSquareWhiteAreaWidth); LOG.debug("minSquareWhiteAreaHeight: " + minSquareWhiteAreaHeight); List<Rectangle> squareWhiteAreas = whiteAreaFinder.getWhiteAreas(blackAreas, left, top, right, bottom, minSquareWhiteAreaWidth, minSquareWhiteAreaHeight); whiteAreas.addAll(squareWhiteAreas); blackAreas.addAll(squareWhiteAreas); blackAreas.addAll(this.getWhiteAreasAroundLargeShapes(shapes)); // Long narrow vertical white areas minVerticalWhiteAreaWidth = 1.0 * averageShapeWidth; minVerticalWhiteAreaHeight = 20.0 * averageShapeHeight; LOG.debug("minVerticalWhiteAreaWidth: " + minVerticalWhiteAreaWidth); LOG.debug("minVerticalWhiteAreaHeight: " + minVerticalWhiteAreaHeight); List<Rectangle> verticalWhiteAreas2 = whiteAreaFinder.getWhiteAreas(blackAreas, left, top, right, bottom, minVerticalWhiteAreaWidth, minVerticalWhiteAreaHeight); whiteAreas.addAll(verticalWhiteAreas2); return whiteAreas; }
From source file:com.joliciel.jochre.graphics.SourceImageImpl.java
void calculateShapeStatistics() { if (!shapeStatisticsCalculated) { DescriptiveStatistics shapeWidthStats = new DescriptiveStatistics(); DescriptiveStatistics shapeHeightStats = new DescriptiveStatistics(); for (RowOfShapes row : this.getRows()) { for (Shape shape : row.getShapes()) { shapeWidthStats.addValue(shape.getWidth()); shapeHeightStats.addValue(shape.getHeight()); }/* w w w. j a va2 s . c o m*/ } double minWidth = shapeWidthStats.getPercentile(50); double maxWidth = shapeWidthStats.getPercentile(80); double minHeight = shapeHeightStats.getPercentile(50); double maxHeight = shapeHeightStats.getPercentile(80); this.averageShapeWidth = shapeWidthStats.getPercentile(65); this.averageShapeHeight = shapeHeightStats.getPercentile(65); this.averageShapeWidthMargin = (maxWidth - minWidth) / 2.0; this.averageShapeHeightMargin = (maxHeight - minHeight) / 2.0; this.shapeStatisticsCalculated = true; } }
From source file:com.joliciel.jochre.graphics.RowOfShapesImpl.java
void calculateShapeStatistics() { if (!shapeStatisticsCalculated) { DescriptiveStatistics shapeWidthStats = new DescriptiveStatistics(); DescriptiveStatistics shapeHeightStats = new DescriptiveStatistics(); for (Shape shape : this.getShapes()) { shapeWidthStats.addValue(shape.getWidth()); shapeHeightStats.addValue(shape.getHeight()); }//from w ww.jav a 2 s. c om double minWidth = shapeWidthStats.getPercentile(33); double maxWidth = shapeWidthStats.getPercentile(66); double minHeight = shapeHeightStats.getPercentile(33); double maxHeight = shapeHeightStats.getPercentile(66); this.averageShapeWidth = shapeWidthStats.getPercentile(50); this.averageShapeHeight = shapeHeightStats.getPercentile(50); this.averageShapeWidthMargin = (maxWidth - minWidth) / 2.0; this.averageShapeHeightMargin = (maxHeight - minHeight) / 2.0; this.shapeStatisticsCalculated = true; } }
From source file:com.joliciel.jochre.graphics.RowOfShapesImpl.java
/** * The regression passes through the bottom of average shapes on this line. * It gives the line's slope, and a starting point for finding the baseline and meanline. *//*from w w w . j a v a2 s.c o m*/ public SimpleRegression getRegression() { if (this.regression == null) { // begin by calculating some sort of average line crossing the whole row, so that we can see if the row is // rising or falling to start with? // Calculate the line crossing the mid-point of all "average" shapes on this row // get the "smoothed" linear approximation of the mid-points regression = new SimpleRegression(); int numShapes = 0; int minShapes = 10; DescriptiveStatistics shapeWidthStats = new DescriptiveStatistics(); DescriptiveStatistics shapeHeightStats = new DescriptiveStatistics(); for (Shape shape : this.getShapes()) { shapeWidthStats.addValue(shape.getWidth()); shapeHeightStats.addValue(shape.getHeight()); } double minWidth = shapeWidthStats.getPercentile(25); double maxWidth = shapeWidthStats.getPercentile(75); double minHeight = shapeHeightStats.getPercentile(25); double maxHeight = shapeHeightStats.getPercentile(75); for (Shape shape : this.getShapes()) { // only add points whose shape is of "average" width and height (to leave out commas, etc.) if (shape.getWidth() >= minWidth && shape.getWidth() <= maxWidth && shape.getHeight() >= minHeight && shape.getHeight() <= maxHeight) { // using bottom only, since rows with different font sizes tend to align bottom regression.addData((((double) shape.getLeft() + (double) shape.getRight()) / 2.0), ((double) shape.getBottom())); numShapes++; } } // special case where row contains very few shapes (generally letter or number + period) boolean horizontalLine = false; if (numShapes < minShapes) { LOG.debug("Too few shapes: " + numShapes + ", assuming straight horizontal line"); horizontalLine = true; } else if ((this.getRight() - this.getLeft()) < (this.getContainer().getWidth() / 6.0)) { LOG.debug("Too narrow: " + (this.getRight() - this.getLeft()) + ", assuming straight horizontal line"); horizontalLine = true; } if (horizontalLine) { // assume a straight horizontal line Mean midPointMean = new Mean(); for (Shape shape : this.getShapes()) { // only add points whose shape is of "average" height (to leave out commas, etc.) if (shape.getWidth() >= minWidth && shape.getWidth() <= maxWidth && shape.getHeight() >= minHeight && shape.getHeight() <= maxHeight) { midPointMean.increment((double) shape.getBottom()); } } if (midPointMean.getN() == 0) { for (Shape shape : this.getShapes()) { midPointMean.increment((double) shape.getBottom()); } } double meanMidPoint = midPointMean.getResult(); regression = new SimpleRegression(); regression.addData(this.getLeft(), meanMidPoint); regression.addData(this.getRight(), meanMidPoint); } // displays intercept of regression line LOG.debug("intercept: " + regression.getIntercept()); // displays slope of regression line LOG.debug("slope: " + regression.getSlope()); // displays slope standard error LOG.debug("std err: " + regression.getSlopeStdErr()); LOG.debug("x = 0, y = " + regression.predict(0)); LOG.debug("x = " + this.getContainer().getWidth() + ", y = " + regression.predict(this.getContainer().getWidth())); } return regression; }
From source file:com.joliciel.jochre.graphics.RowOfShapesImpl.java
/** * Assign guidelines for a certain subset of shapes, and return the x-height. * @param startShape/*from w ww . j av a2 s. co m*/ * @param endShape * @return */ int assignGuideLines(List<GroupOfShapes> groupsToAssign) { LOG.debug("assignGuideLines internal"); double meanHorizontalSlope = this.getContainer().getMeanHorizontalSlope(); // the base-line and mean-line will be at a fixed distance away from the midpoint // the question is, which distance! // To find this out, we count number of black pixels on each row above this line // And then start analysing from the top and the bottom until the number drops off sharply // The notion of "groupsToAssign" is used to only assign guidelines // to a subset of the groups on the line // when the line contains two different font sizes List<Shape> shapes = new ArrayList<Shape>(); if (groupsToAssign != null) { for (GroupOfShapes group : groupsToAssign) { shapes.addAll(group.getShapes()); } } else { shapes = this.getShapes(); } int i = 0; DescriptiveStatistics shapeWidthStats = new DescriptiveStatistics(); DescriptiveStatistics shapeHeightStats = new DescriptiveStatistics(); for (Shape shape : this.getShapes()) { shapeWidthStats.addValue(shape.getWidth()); shapeHeightStats.addValue(shape.getHeight()); } double minWidth = shapeWidthStats.getPercentile(25); double maxWidth = shapeWidthStats.getPercentile(75); double minHeight = shapeHeightStats.getPercentile(45); double maxHeight = shapeHeightStats.getPercentile(75); double rowMidPointX = (double) (this.getLeft() + this.getRight()) / 2.0; // calculating the Y midpoint by the shapes in the row, instead of by the top & bottom of row Mean rowMidPointYMean = new Mean(); for (Shape shape : this.getShapes()) { // only add points whose shape is of "average" width and height (to leave out commas, etc.) if (shape.getWidth() >= minWidth && shape.getWidth() <= maxWidth && shape.getHeight() >= minHeight && shape.getHeight() <= maxHeight) { rowMidPointYMean.increment((double) (shape.getBottom() + shape.getTop()) / 2.0); } } double rowMidPointY = (double) (this.getTop() + this.getBottom()) / 2.0; if (rowMidPointYMean.getN() > 0) rowMidPointY = rowMidPointYMean.getResult(); LOG.debug("rowMidPointX: " + rowMidPointX); LOG.debug("rowMidPointY: " + rowMidPointY); // figure out where the top-most shape starts and the bottom-most shape ends, relative to the y midline int minTop = Integer.MAX_VALUE; int maxBottom = Integer.MIN_VALUE; List<Integer> rowYMidPoints = new ArrayList<Integer>(shapes.size()); for (Shape shape : shapes) { double shapeMidPointX = (double) (shape.getLeft() + shape.getRight()) / 2.0; int shapeMidPointY = (int) Math .round(rowMidPointY + (meanHorizontalSlope * (shapeMidPointX - rowMidPointX))); rowYMidPoints.add(shapeMidPointY); int relativeTop = shape.getTop() - shapeMidPointY; int relativeBottom = shape.getBottom() - shapeMidPointY; if (relativeTop < minTop) minTop = relativeTop; if (relativeBottom > maxBottom) maxBottom = relativeBottom; } if (minTop > 0) minTop = 0; if (maxBottom < 0) maxBottom = 0; int yIntervalTop = 0 - minTop; int yIntervalBottom = maxBottom; int yInterval = yIntervalTop + 1 + yIntervalBottom; LOG.debug("yIntervalTop: " + yIntervalTop); LOG.debug("yIntervalBottom: " + yIntervalBottom); LOG.debug("yInterval: " + yInterval); int[] pixelCounts = new int[yInterval]; // Get the pixel count for each row // examining one shape at a time to limit ourselves to the pixels that are // actually considered to be in this row int blackThreshold = this.getContainer().getSeparationThreshold(); int shapeIndex = 0; int shapeCount = 0; for (Shape shape : shapes) { if (shape.getHeight() >= minHeight) { LOG.trace(shape.toString()); shapeCount++; int shapeMidPointY = rowYMidPoints.get(shapeIndex); int zeroLine = shapeMidPointY - yIntervalTop; int topIndex = shape.getTop() - zeroLine; for (int x = 0; x < shape.getWidth(); x++) { for (int y = 0; y < shape.getHeight(); y++) { int yIndex = topIndex + y; if (yIndex >= 0 && yIndex < pixelCounts.length && shape.isPixelBlack(x, y, blackThreshold)) { pixelCounts[yIndex]++; } } } } shapeIndex++; } LOG.debug("Got pixels from " + shapeCount + " shapes."); boolean notEnoughShapes = shapeCount < 3; LOG.debug("notEnoughShapes? " + notEnoughShapes); // We start at the top // As soon as we reach a line with more pixels than the mean, we assume this is the mean-line Mean pixelCountMeanTop = new Mean(); StandardDeviation pixelCountStdDevTop = new StandardDeviation(); for (i = 0; i <= yIntervalTop; i++) { pixelCountMeanTop.increment(pixelCounts[i]); pixelCountStdDevTop.increment(pixelCounts[i]); } LOG.debug("Top: pixel count mean: " + pixelCountMeanTop.getResult() + ", std dev: " + pixelCountStdDevTop.getResult()); double threshold = pixelCountMeanTop.getResult() * 1.1; if (notEnoughShapes) { threshold = threshold / 2.0; } double lowerThreshold = threshold / 2.0; LOG.debug("Top threshold: " + threshold); LOG.debug("Top lowerThreshold: " + lowerThreshold); int meanLine = 0; boolean findMeanLine = true; for (i = 0; i <= yIntervalTop; i++) { int pixelCount = pixelCounts[i]; if (findMeanLine && pixelCount > threshold) { meanLine = i; findMeanLine = false; } else if (!findMeanLine && pixelCount < lowerThreshold) { findMeanLine = true; } } // We start at the bottom // As soon as we reach a line with more pixels than the mean, we assume this is the base-line Mean pixelCountMeanBottom = new Mean(); StandardDeviation pixelCountStdDevBottom = new StandardDeviation(); for (i = pixelCounts.length - 1; i >= yIntervalTop; i--) { pixelCountMeanBottom.increment(pixelCounts[i]); pixelCountStdDevBottom.increment(pixelCounts[i]); } LOG.debug("Bottom: pixel count mean: " + pixelCountMeanBottom.getResult() + ", std dev: " + pixelCountStdDevBottom.getResult()); threshold = pixelCountMeanBottom.getResult() * 1.1; if (notEnoughShapes) { threshold = threshold / 2.0; } lowerThreshold = threshold / 2.0; LOG.debug("Bottom threshold: " + threshold); LOG.debug("Bottom lowerThreshold: " + lowerThreshold); int baseLine = meanLine; boolean findBaseLine = true; for (i = pixelCounts.length - 1; i >= yIntervalTop; i--) { int pixelCount = pixelCounts[i]; if (findBaseLine && pixelCount > threshold) { baseLine = i; findBaseLine = false; } else if (!findBaseLine && pixelCount < lowerThreshold) { findBaseLine = true; } } for (i = 0; i < yInterval; i++) { int pixelCount = pixelCounts[i]; if (i == meanLine) LOG.trace("======= MEAN LINE " + i + " =========="); LOG.trace("pixel row " + i + ". pixel count " + pixelCount); if (i == baseLine) LOG.trace("======= BASE LINE " + i + " =========="); } // assign base lines and mean lines to each shape shapeIndex = 0; for (Shape shape : shapes) { int shapeMidPointY = rowYMidPoints.get(shapeIndex); int yMeanline = (shapeMidPointY - yIntervalTop) + meanLine; int yBaseline = (shapeMidPointY - yIntervalTop) + baseLine; LOG.trace(shape.toString() + ", meanLine: " + (yMeanline - shape.getTop()) + ", baseLine: " + (yBaseline - shape.getTop())); shape.setBaseLine(yBaseline - shape.getTop()); shape.setMeanLine(yMeanline - shape.getTop()); shapeIndex++; } // next shape int xHeight = baseLine - meanLine; return xHeight; }
From source file:com.joliciel.jochre.graphics.SourceImageImpl.java
public List<Rectangle> findColumnSeparators() { if (columnSeparators == null) { LOG.debug("############ findColumnSeparators ##############"); double slope = this.getMeanHorizontalSlope(); double imageMidPointX = (double) this.getWidth() / 2.0; int[] horizontalCounts = new int[this.getHeight()]; DescriptiveStatistics rowXHeightStats = new DescriptiveStatistics(); // first get the fill factor for each horizontal row in the image for (RowOfShapes row : this.getRows()) { rowXHeightStats.addValue(row.getXHeight()); for (Shape shape : row.getShapes()) { double shapeMidPointX = (double) (shape.getLeft() + shape.getRight()) / 2.0; int slopeAdjustedTop = (int) Math .round(shape.getTop() + (slope * (shapeMidPointX - imageMidPointX))); if (slopeAdjustedTop >= 0 && slopeAdjustedTop < this.getHeight()) { for (int i = 0; i < shape.getHeight(); i++) { if (slopeAdjustedTop + i < horizontalCounts.length) horizontalCounts[slopeAdjustedTop + i] += shape.getWidth(); }//from ww w . j ava 2 s. co m } } } DescriptiveStatistics horizontalStats = new DescriptiveStatistics(); DescriptiveStatistics horizontalStatsNonEmpty = new DescriptiveStatistics(); for (int i = 0; i < this.getHeight(); i++) { // LOG.trace("Row " + i + ": " + horizontalCounts[i]); horizontalStats.addValue(horizontalCounts[i]); if (horizontalCounts[i] > 0) horizontalStatsNonEmpty.addValue(horizontalCounts[i]); } LOG.debug("Mean horizontal count: " + horizontalStats.getMean()); LOG.debug("Median horizontal count: " + horizontalStats.getPercentile(50)); LOG.debug("25 percentile horizontal count: " + horizontalStats.getPercentile(25)); LOG.debug("Mean horizontal count (non empty): " + horizontalStatsNonEmpty.getMean()); LOG.debug("Median horizontal count (non empty): " + horizontalStatsNonEmpty.getPercentile(50)); LOG.debug("25 percentile horizontal count (non empty): " + horizontalStatsNonEmpty.getPercentile(25)); LOG.debug("10 percentile horizontal count (non empty): " + horizontalStatsNonEmpty.getPercentile(10)); double maxEmptyRowCount = horizontalStatsNonEmpty.getMean() / 8.0; LOG.debug("maxEmptyRowCount: " + maxEmptyRowCount); boolean inEmptyHorizontalRange = false; List<int[]> emptyHorizontalRanges = new ArrayList<int[]>(); int emptyHorizontalRangeStart = 0; for (int i = 0; i < this.getHeight(); i++) { if (!inEmptyHorizontalRange && horizontalCounts[i] <= maxEmptyRowCount) { inEmptyHorizontalRange = true; emptyHorizontalRangeStart = i; } else if (inEmptyHorizontalRange && horizontalCounts[i] > maxEmptyRowCount) { inEmptyHorizontalRange = false; emptyHorizontalRanges.add(new int[] { emptyHorizontalRangeStart, i }); } } if (inEmptyHorizontalRange) { emptyHorizontalRanges.add(new int[] { emptyHorizontalRangeStart, this.getHeight() - 1 }); } LOG.debug("rowXHeight mean: " + rowXHeightStats.getMean()); LOG.debug("rowXHeight median: " + rowXHeightStats.getPercentile(50)); double minHorizontalBreak = rowXHeightStats.getMean() * 2.0; LOG.debug("minHorizontalBreak: " + minHorizontalBreak); int smallBreakCount = 0; int mainTextTop = 0; int bigBreakCount = 0; for (int[] emptyHorizontalRange : emptyHorizontalRanges) { int height = emptyHorizontalRange[1] - emptyHorizontalRange[0]; LOG.trace("empty range: " + emptyHorizontalRange[0] + ", " + emptyHorizontalRange[1] + " = " + height); if (bigBreakCount < 2 && smallBreakCount < 2 && height > minHorizontalBreak) { mainTextTop = emptyHorizontalRange[1]; bigBreakCount++; } if (height <= minHorizontalBreak) smallBreakCount++; } LOG.debug("mainTextTop:" + mainTextTop); // lift mainTextTop upwards by max an x-height or till we reach a zero row int minTop = mainTextTop - (int) (rowXHeightStats.getMean() / 2.0); if (minTop < 0) minTop = 0; for (int i = mainTextTop; i > minTop; i--) { mainTextTop = i; if (horizontalCounts[i] == 0) { break; } } LOG.debug("mainTextTop (adjusted):" + mainTextTop); smallBreakCount = 0; bigBreakCount = 0; int mainTextBottom = this.getHeight(); for (int i = emptyHorizontalRanges.size() - 1; i >= 0; i--) { int[] emptyHorizontalRange = emptyHorizontalRanges.get(i); int height = emptyHorizontalRange[1] - emptyHorizontalRange[0]; LOG.trace("emptyHorizontalRange: " + emptyHorizontalRange[0] + ", height: " + height + ", bigBreakCount: " + bigBreakCount + ", smallBreakCount: " + smallBreakCount); if ((bigBreakCount + smallBreakCount) <= 2 && height > minHorizontalBreak) { mainTextBottom = emptyHorizontalRange[0]; LOG.trace("Set mainTextBottom to " + mainTextBottom); bigBreakCount++; } if (height <= minHorizontalBreak) smallBreakCount++; if ((bigBreakCount + smallBreakCount) > 2) break; } LOG.debug("mainTextBottom:" + mainTextBottom); // lower mainTextBottom downwards by max an x-height or till we reach a zero row int maxBottom = mainTextBottom + (int) (rowXHeightStats.getMean() / 2.0); if (maxBottom > this.getHeight()) maxBottom = this.getHeight(); for (int i = mainTextBottom; i < maxBottom; i++) { mainTextBottom = i; if (horizontalCounts[i] == 0) { break; } } LOG.debug("mainTextBottom (adjusted):" + mainTextBottom); int[] verticalCounts = new int[this.getWidth()]; // first get the fill factor for each horizontal row in the image for (RowOfShapes row : this.getRows()) { for (Shape shape : row.getShapes()) { int slopeAdjustedLeft = (int) Math.round(shape.getLeft() - row.getXAdjustment()); double shapeMidPointX = (double) (shape.getLeft() + shape.getRight()) / 2.0; int slopeAdjustedTop = (int) Math .round(shape.getTop() + (slope * (shapeMidPointX - imageMidPointX))); if (slopeAdjustedTop >= mainTextTop && slopeAdjustedTop <= mainTextBottom && slopeAdjustedLeft >= 0 && slopeAdjustedLeft < this.getWidth()) { for (int i = 0; i < shape.getWidth(); i++) { if (slopeAdjustedLeft + i < this.getWidth()) verticalCounts[slopeAdjustedLeft + i] += shape.getHeight(); } } } } DescriptiveStatistics verticalStats = new DescriptiveStatistics(); DescriptiveStatistics verticalStatsNonEmpty = new DescriptiveStatistics(); for (int i = 0; i < this.getWidth(); i++) { // LOG.trace("Column " + i + ": " + verticalCounts[i]); verticalStats.addValue(verticalCounts[i]); if (verticalCounts[i] > 0) verticalStatsNonEmpty.addValue(verticalCounts[i]); } LOG.debug("Mean vertical count: " + verticalStats.getMean()); LOG.debug("Median vertical count: " + verticalStats.getPercentile(50)); LOG.debug("25 percentile vertical count: " + verticalStats.getPercentile(25)); LOG.debug("Mean vertical count (non empty): " + verticalStatsNonEmpty.getMean()); LOG.debug("Median vertical count (non empty): " + verticalStatsNonEmpty.getPercentile(50)); LOG.debug("25 percentile vertical count (non empty): " + verticalStatsNonEmpty.getPercentile(25)); LOG.debug("10 percentile vertical count (non empty): " + verticalStatsNonEmpty.getPercentile(10)); LOG.debug("1 percentile vertical count (non empty): " + verticalStatsNonEmpty.getPercentile(1)); // double maxEmptyColumnCount = verticalStatsNonEmpty.getMean() / 8.0; double maxEmptyColumnCount = verticalStatsNonEmpty.getPercentile(1); LOG.debug("maxEmptyColumnCount: " + maxEmptyColumnCount); boolean inEmptyVerticalRange = false; List<int[]> emptyVerticalRanges = new ArrayList<int[]>(); int emptyVerticalRangeStart = 0; for (int i = 0; i < this.getWidth(); i++) { if (!inEmptyVerticalRange && verticalCounts[i] <= maxEmptyColumnCount) { inEmptyVerticalRange = true; emptyVerticalRangeStart = i; } else if (inEmptyVerticalRange && verticalCounts[i] > maxEmptyColumnCount) { inEmptyVerticalRange = false; emptyVerticalRanges.add(new int[] { emptyVerticalRangeStart, i }); } } if (inEmptyVerticalRange) { emptyVerticalRanges.add(new int[] { emptyVerticalRangeStart, this.getWidth() - 1 }); } LOG.debug("rowXHeight mean: " + rowXHeightStats.getMean()); LOG.debug("rowXHeight median: " + rowXHeightStats.getPercentile(50)); double minVerticalBreak = rowXHeightStats.getMean() * 1.0; LOG.debug("minVerticalBreak: " + minVerticalBreak); List<int[]> columnBreaks = new ArrayList<int[]>(); for (int[] emptyVerticalRange : emptyVerticalRanges) { int width = emptyVerticalRange[1] - emptyVerticalRange[0]; LOG.trace("empty range: " + emptyVerticalRange[0] + ", " + emptyVerticalRange[1] + " = " + width); if (width >= minVerticalBreak) { columnBreaks.add(emptyVerticalRange); LOG.trace("Found column break!"); } } columnSeparators = new ArrayList<Rectangle>(); for (int[] columnBreak : columnBreaks) { // reduce the column break to the thickest empty area if possible int[] bestColumnBreak = null; double originalCount = maxEmptyColumnCount; maxEmptyColumnCount = 0; while (bestColumnBreak == null && maxEmptyColumnCount <= originalCount) { inEmptyVerticalRange = false; emptyVerticalRanges = new ArrayList<int[]>(); emptyVerticalRangeStart = columnBreak[0]; for (int i = columnBreak[0]; i <= columnBreak[1]; i++) { if (!inEmptyVerticalRange && verticalCounts[i] <= maxEmptyColumnCount) { inEmptyVerticalRange = true; emptyVerticalRangeStart = i; } else if (inEmptyVerticalRange && verticalCounts[i] > maxEmptyColumnCount) { inEmptyVerticalRange = false; emptyVerticalRanges.add(new int[] { emptyVerticalRangeStart, i }); } } if (inEmptyVerticalRange) { emptyVerticalRanges.add(new int[] { emptyVerticalRangeStart, columnBreak[1] }); } for (int[] emptyVerticalRange : emptyVerticalRanges) { if (bestColumnBreak == null || (emptyVerticalRange[1] - emptyVerticalRange[0] > bestColumnBreak[1] - bestColumnBreak[0])) bestColumnBreak = emptyVerticalRange; } maxEmptyColumnCount += (originalCount / 8.0); } if (bestColumnBreak == null) bestColumnBreak = columnBreak; Rectangle whiteArea = new WhiteArea(bestColumnBreak[0], mainTextTop, bestColumnBreak[1], mainTextBottom); columnSeparators.add(whiteArea); LOG.debug("ColumnBreak: " + whiteArea); } // next column break } return columnSeparators; }
From source file:com.mozilla.socorro.hadoop.RawDumpSize.java
public int run(String[] args) throws Exception { if (args.length != 1) { return printUsage(); }//from w w w .j ava 2s . co m int rc = -1; Job job = initJob(args); job.waitForCompletion(true); if (job.isSuccessful()) { rc = 0; FileSystem hdfs = null; DescriptiveStatistics rawStats = new DescriptiveStatistics(); long rawTotal = 0L; DescriptiveStatistics processedStats = new DescriptiveStatistics(); long processedTotal = 0L; try { hdfs = FileSystem.get(job.getConfiguration()); Pattern tabPattern = Pattern.compile("\t"); for (FileStatus status : hdfs.listStatus(FileOutputFormat.getOutputPath(job))) { if (!status.isDir()) { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(hdfs.open(status.getPath()))); String line = null; while ((line = reader.readLine()) != null) { String[] splits = tabPattern.split(line); int byteSize = Integer.parseInt(splits[2]); if ("raw".equals(splits[1])) { rawStats.addValue(byteSize); rawTotal += byteSize; } else if ("processed".equals(splits[1])) { processedStats.addValue(byteSize); processedTotal += byteSize; } } } finally { if (reader != null) { reader.close(); } } } } } finally { if (hdfs != null) { hdfs.close(); } } System.out.println("===== " + job.getConfiguration().get(START_DATE) + " raw_data:dump ====="); System.out.println(String.format("Min: %.02f Max: %.02f Mean: %.02f", rawStats.getMin(), rawStats.getMax(), rawStats.getMean())); System.out.println(String.format("1st Quartile: %.02f 2nd Quartile: %.02f 3rd Quartile: %.02f", rawStats.getPercentile(25.0d), rawStats.getPercentile(50.0d), rawStats.getPercentile(75.0d))); System.out.println("Total Bytes: " + rawTotal); System.out.println("===== " + job.getConfiguration().get(START_DATE) + " processed_data:json ====="); System.out.println(String.format("Min: %.02f Max: %.02f Mean: %.02f", processedStats.getMin(), processedStats.getMax(), processedStats.getMean())); System.out.println(String.format("1st Quartile: %.02f 2nd Quartile: %.02f 3rd Quartile: %.02f", processedStats.getPercentile(25.0d), processedStats.getPercentile(50.0d), processedStats.getPercentile(75.0d))); System.out.println("Total Bytes: " + processedTotal); } return rc; }