List of usage examples for java.lang Double isNaN
public static boolean isNaN(double v)
From source file:edu.cmu.tetrad.data.GeneralAndersonDarlingTest.java
private double[] leaveOutNaN(double[] data) { int numPresent = 0; for (int i = 0; i < data.length; i++) { if (!Double.isNaN(data[i])) { numPresent++;// w w w . j a v a 2s.co m } } if (numPresent == data.length) { double[] _data = new double[data.length]; System.arraycopy(data, 0, _data, 0, data.length); return _data; } else { List<Double> _leaveOutMissing = new ArrayList<Double>(); for (int i = 0; i < data.length; i++) { if (!Double.isNaN(data[i])) { _leaveOutMissing.add(data[i]); } } double[] _data = new double[_leaveOutMissing.size()]; for (int i = 0; i < _leaveOutMissing.size(); i++) _data[i] = _leaveOutMissing.get(i); return _data; } }
From source file:edu.jhuapl.bsp.detector.OpenMath.java
public static double mean(double[] in) { if (in != null && in.length > 0) { double sum = 0; for (int i = 0; i < in.length; i++) { sum += in[i];//from www . java2 s . com } double result = sum / in.length; if (Double.isNaN(result) || Double.isInfinite(result)) { return 0; } else { return result; } } return 0; }
From source file:gedi.util.math.stat.counting.RollingStatistics.java
/** * Always includes the first and last halfwindow and all windows that fit in between and are step entries apart from each other * It also takes care of ties in the covariate by always including adding all values for all ties within range * @param halfBinsize// w w w . j ava 2 s .c o m * @param step * @return */ public ExtendedIterator<RollingBin> iterateEquiSize(int halfBinsize, int step) { if (size() == 0) return EI.empty(); cov.parallelSort(val); if (size() < halfBinsize + 1) { NumericArraySlice slice = NumericArray.wrap(val.getRaw(), 0, val.size()); if (size() == 1) return EI.wrap(new RollingBin(cov.getDouble(0), slice)); return EI.wrap(new RollingBin(cov.getDouble(0), slice), new RollingBin(cov.getDouble(size() - 1), slice)); } if (size() < halfBinsize * 2 + 1) { return EI.wrap(new RollingBin(cov.getDouble(0), NumericArray.wrap(val.getRaw(), 0, halfBinsize + 1)), new RollingBin(cov.getDouble(size() - 1), NumericArray.wrap(val.getRaw(), size() - 1 - halfBinsize, size()))); } IntArrayList ties = new IntArrayList(); ties.add(0); for (int i = 1; i < size(); i++) if (cov.getDouble(i - 1) != cov.getDouble(i)) ties.add(i); ties.add(size()); ExtendedIterator<RollingBin> ei = new ExtendedIterator<RollingBin>() { private int i = halfBinsize - step; private RollingBin rb; private NumericArraySlice slice; private boolean dirty = false; private boolean lastDone = false; { int start = 0; int end = ties.binarySearch(halfBinsize + 1); if (end < 0) end = -end - 1; slice = NumericArray.wrap(val.getRaw(), ties.getInt(start), ties.getInt(end)); rb = new RollingBin(cov.getDouble(0), slice); } @Override public boolean hasNext() { computeIfNecessary(); return !Double.isNaN(rb.covariate); } @Override public RollingBin next() { computeIfNecessary(); dirty = true; return rb; } private void computeIfNecessary() { if (dirty && !Double.isNaN(rb.covariate)) { i += step; if (i < size() - halfBinsize) { int start = bin(i - halfBinsize, 0); int end = bin(i + halfBinsize, 1) + 1; slice.setSlice(ties.getInt(start), ties.getInt(end)); rb.covariate = cov.getDouble(i); } else if (!lastDone) { int start = ties.binarySearch(size() - 1 - halfBinsize); if (start < 0) start = -start - 2; int end = size(); slice.setSlice(ties.getInt(start), end); rb.covariate = cov.getDouble(size() - 1); lastDone = true; } else { rb.covariate = Double.NaN; } dirty = false; } } private int[][] fastBin = new int[2][]; private int bin(int s, int which) { if (fastBin[which] == null) { fastBin[which] = new int[2]; } else if (cov.getDouble(fastBin[which][0]) == cov.getDouble(s)) { return fastBin[which][1]; } fastBin[which][0] = s; fastBin[which][1] = ties.binarySearch(s); if (fastBin[which][1] < 0) fastBin[which][1] = -fastBin[which][1] - 2; return fastBin[which][1]; } }; int count = (int) Math.ceil((size() - halfBinsize * 2) / (double) step) + 2; if (progress != null) ei = ei.progress(progress, count, rb -> String.format("%.2f: [%.2f,%.2f]", rb.covariate, rb.values.getDouble(0), rb.values.getDouble(rb.getValues().length() - 1))); return ei; }
From source file:org.rdv.viz.chart.FastXYItemRenderer.java
@Override public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { boolean itemVisible = getItemVisible(series, item); // setup for collecting optional entity info... Shape entityArea = null;/*from w w w. j a v a 2 s . c o m*/ EntityCollection entities = null; if (info != null) { entities = info.getOwner().getEntityCollection(); } PlotOrientation orientation = plot.getOrientation(); Paint paint = getItemPaint(series, item); Stroke seriesStroke = getItemStroke(series, item); g2.setPaint(paint); g2.setStroke(seriesStroke); // get the data point... double x1 = dataset.getXValue(series, item); double y1 = dataset.getYValue(series, item); if (Double.isNaN(x1) || Double.isNaN(y1)) { itemVisible = false; } RectangleEdge xAxisLocation = plot.getDomainAxisEdge(); RectangleEdge yAxisLocation = plot.getRangeAxisEdge(); double transX1 = domainAxis.valueToJava2D(x1, dataArea, xAxisLocation); double transY1 = rangeAxis.valueToJava2D(y1, dataArea, yAxisLocation); if (getPlotLines()) { if (item == 0) { previousDrawnItem = 1; } if (getDrawSeriesLineAsPath()) { State s = (State) state; if (s.getSeriesIndex() != series) { // we are starting a new series path s.seriesPath.reset(); s.setLastPointGood(false); s.setSeriesIndex(series); } // update path to reflect latest point if (itemVisible && !Double.isNaN(transX1) && !Double.isNaN(transY1)) { float x = (float) transX1; float y = (float) transY1; if (orientation == PlotOrientation.HORIZONTAL) { x = (float) transY1; y = (float) transX1; } if (s.isLastPointGood()) { // TODO: check threshold s.seriesPath.lineTo(x, y); } else { s.seriesPath.moveTo(x, y); } s.setLastPointGood(true); } else { s.setLastPointGood(false); } if (item == dataset.getItemCount(series) - 1) { if (s.getSeriesIndex() == series) { // draw path g2.setStroke(lookupSeriesStroke(series)); g2.setPaint(lookupSeriesPaint(series)); g2.draw(s.seriesPath); } } } else if (item != 0 && itemVisible) { // get the previous data point... double x0 = dataset.getXValue(series, item - previousDrawnItem); double y0 = dataset.getYValue(series, item - previousDrawnItem); if (!Double.isNaN(x0) && !Double.isNaN(y0)) { boolean drawLine = true; if (getPlotDiscontinuous()) { // only draw a line if the gap between the current and // previous data point is within the threshold int numX = dataset.getItemCount(series); double minX = dataset.getXValue(series, 0); double maxX = dataset.getXValue(series, numX - 1); if (getGapThresholdType() == UnitType.ABSOLUTE) { drawLine = Math.abs(x1 - x0) <= getGapThreshold(); } else { drawLine = Math.abs(x1 - x0) <= ((maxX - minX) / numX * getGapThreshold()); } } if (drawLine) { double transX0 = domainAxis.valueToJava2D(x0, dataArea, xAxisLocation); double transY0 = rangeAxis.valueToJava2D(y0, dataArea, yAxisLocation); // only draw if we have good values if (Double.isNaN(transX0) || Double.isNaN(transY0) || Double.isNaN(transX1) || Double.isNaN(transY1)) { return; } // Only draw line if it is more than a pixel away from the // previous one if ((transX1 - transX0 > 2 || transX1 - transX0 < -2 || transY1 - transY0 > 2 || transY1 - transY0 < -2)) { previousDrawnItem = 1; if (orientation == PlotOrientation.HORIZONTAL) { state.workingLine.setLine(transY0, transX0, transY1, transX1); } else if (orientation == PlotOrientation.VERTICAL) { state.workingLine.setLine(transX0, transY0, transX1, transY1); } if (state.workingLine.intersects(dataArea)) { g2.draw(state.workingLine); } } else { // Increase counter for the previous drawn item. previousDrawnItem++; } } } } } // we needed to get this far even for invisible items, to ensure that // seriesPath updates happened, but now there is nothing more we need // to do for non-visible items... if (!itemVisible) { return; } // add a cursor to indicate the position of the last data item if (getCursorVisible() && item == dataset.getItemCount(series) - 1) { Line2D cursorX = new Line2D.Double(transX1 - DEFAULT_CURSOR_SIZE, transY1, transX1 + DEFAULT_CURSOR_SIZE, transY1); g2.draw(cursorX); Line2D cursorY = new Line2D.Double(transX1, transY1 - DEFAULT_CURSOR_SIZE, transX1, transY1 + DEFAULT_CURSOR_SIZE); g2.draw(cursorY); } if (getBaseShapesVisible()) { Shape shape = getItemShape(series, item); if (orientation == PlotOrientation.HORIZONTAL) { shape = ShapeUtilities.createTranslatedShape(shape, transY1, transX1); } else if (orientation == PlotOrientation.VERTICAL) { shape = ShapeUtilities.createTranslatedShape(shape, transX1, transY1); } if (shape.intersects(dataArea)) { if (getItemShapeFilled(series, item)) { g2.fill(shape); } else { g2.draw(shape); } } entityArea = shape; } if (getPlotImages()) { Image image = getImage(plot, series, item, transX1, transY1); if (image != null) { Point hotspot = getImageHotspot(plot, series, item, transX1, transY1, image); g2.drawImage(image, (int) (transX1 - hotspot.getX()), (int) (transY1 - hotspot.getY()), null); entityArea = new Rectangle2D.Double(transX1 - hotspot.getX(), transY1 - hotspot.getY(), image.getWidth(null), image.getHeight(null)); } } double xx = transX1; double yy = transY1; if (orientation == PlotOrientation.HORIZONTAL) { xx = transY1; yy = transX1; } // draw the item label if there is one... if (isItemLabelVisible(series, item)) { drawItemLabel(g2, orientation, dataset, series, item, xx, yy, (y1 < 0.0)); } int domainAxisIndex = plot.getDomainAxisIndex(domainAxis); int rangeAxisIndex = plot.getRangeAxisIndex(rangeAxis); updateCrosshairValues(crosshairState, x1, y1, domainAxisIndex, rangeAxisIndex, transX1, transY1, orientation); // add an entity for the item... if (entities != null && dataArea.contains(xx, yy)) { addEntity(entities, entityArea, dataset, series, item, xx, yy); } }
From source file:ffx.xray.SplineEnergy.java
/** * <p>//from www. j a va 2 s .c o m * target</p> * * @param x an array of double. * @param g an array of double. * @param gradient a boolean. * @param print a boolean. * @return a double. */ public double target(double x[], double g[], boolean gradient, boolean print) { double r = 0.0; double rf = 0.0; double rfree = 0.0; double rfreef = 0.0; double sum = 0.0; double sumfo = 0.0; // Zero out the gradient. if (gradient) { fill(g, 0.0); } for (HKL ih : reflectionlist.hkllist) { int i = ih.index(); if (Double.isNaN(fc[i][0]) || Double.isNaN(fo[i][0]) || fo[i][1] <= 0.0) { continue; } if (type == Type.FOTOESQ && fo[i][0] <= 0.0) { continue; } double eps = ih.epsilon(); double s = Crystal.invressq(crystal, ih); // spline setup double fh = spline.f(s, x); refinementdata.getFcTotIP(i, fct); double d2 = 0.0; double dr = 0.0; double w = 0.0; switch (type) { case Type.FOFC: w = 1.0; double f1 = refinementdata.getF(i); double f2 = fct.abs(); double d = f1 - fh * f2; d2 = d * d; dr = -2.0 * f2 * d; sumfo += f1 * f1; break; case Type.F1F2: w = 2.0 / ih.epsilonc(); double ieps = 1.0 / eps; f1 = pow(fct.abs(), 2.0) * ieps; f2 = pow(refinementdata.getF(i), 2) * ieps; d = fh * f1 - f2; d2 = d * d / f1; dr = 2.0 * d; sumfo = 1.0; break; case Type.FCTOESQ: w = 2.0 / ih.epsilonc(); f1 = pow(fct.abs() / sqrt(eps), 2); d = f1 * fh - 1.0; d2 = d * d / f1; dr = 2.0 * d; sumfo = 1.0; break; case Type.FOTOESQ: w = 2.0 / ih.epsilonc(); f1 = pow(refinementdata.getF(i) / sqrt(eps), 2); d = f1 * fh - 1.0; d2 = d * d / f1; dr = 2.0 * d; sumfo = 1.0; break; } sum += w * d2; double afo = abs(fo[i][0]); double afh = abs(fh * fct.abs()); if (refinementdata.isFreeR(i)) { rfree += abs(afo - afh); rfreef += afo; } else { r += abs(afo - afh); rf += afo; } if (gradient) { int i0 = spline.i0(); int i1 = spline.i1(); int i2 = spline.i2(); double g0 = spline.dfi0(); double g1 = spline.dfi1(); double g2 = spline.dfi2(); g[i0] += w * dr * g0; g[i1] += w * dr * g1; g[i2] += w * dr * g2; } } /** * Tim - should this only be done for Type.FOFC?? */ if (gradient) { double isumfo = 1.0 / sumfo; for (int i = 0; i < g.length; i++) { g[i] *= isumfo; } } if (print) { StringBuilder sb = new StringBuilder("\n"); sb.append(" Computed Potential Energy\n"); sb.append(String.format(" residual: %8.3f\n", sum / sumfo)); if (type == Type.FOFC || type == Type.F1F2) { sb.append( String.format(" R: %8.3f Rfree: %8.3f\n", (r / rf) * 100.0, (rfree / rfreef) * 100.0)); } sb.append("x: "); for (int i = 0; i < x.length; i++) { sb.append(String.format("%8g ", x[i])); } sb.append("\ng: "); for (int i = 0; i < g.length; i++) { sb.append(String.format("%8g ", g[i])); } sb.append("\n"); logger.info(sb.toString()); } totalEnergy = sum / sumfo; return sum / sumfo; }
From source file:com.hmsinc.epicenter.spatial.analysis.BayesianSpatialScanStatistic.java
/** Calculates the likelihood P(D|H1(S)) of an outbreak in this region and * stores it in the region object */ private void analyzeRegion(SpatialScanRegion region, SpatialScanGrid grid) { double C_in = region.getCount(); double B_in = region.getBaseline(); double C_out = grid.getC_all() - C_in; double B_out = (grid.getB_all() - B_in) + 1; // Variables to define the range of m to integrate over double mInitial = 1.0; double mFinal = 3.0; double mIncrement = 0.2; double ll = calculateLogLikelihood(grid, mInitial, mFinal, mIncrement, C_in, C_out, B_in, B_out); if (Double.isNaN(ll)) { throw new IllegalArgumentException("Log likelihood for region was NaN! " + region.toString()); }/*w w w.j a v a 2 s . com*/ region.setLikelihood(ll); }
From source file:lirmm.inria.fr.math.TestUtils.java
/** * Verifies that the relative error in actual vs. expected is less than or * equal to relativeError. If expected is infinite or NaN, actual must be * the same (NaN or infinity of the same sign). * * @param msg message to return with failure * @param expected expected value/*from w w w.ja v a 2s .c om*/ * @param actual observed value * @param relativeError maximum allowable relative error */ public static void assertRelativelyEquals(String msg, double expected, double actual, double relativeError) { if (Double.isNaN(expected)) { Assert.assertTrue(msg, Double.isNaN(actual)); } else if (Double.isNaN(actual)) { Assert.assertTrue(msg, Double.isNaN(expected)); } else if (Double.isInfinite(actual) || Double.isInfinite(expected)) { Assert.assertEquals(expected, actual, relativeError); } else if (expected == 0.0) { Assert.assertEquals(msg, actual, expected, relativeError); } else { double absError = FastMath.abs(expected) * relativeError; Assert.assertEquals(msg, expected, actual, absError); } }
From source file:com.ibm.bluej.commonutil.PrecisionRecallThreshold.java
public SummaryScores computeSummaryScores(double limitProb) { if (limitProb < 0.5) { throw new IllegalArgumentException("Probabilities cannot be limited to below 50%"); }// ww w .j a v a 2 s . c om SummaryScores sum = new SummaryScores(); Collections.shuffle(scoredPlusGold, RANDOMNESS); Collections.sort(scoredPlusGold, new FirstPairComparator(null)); Collections.reverse(scoredPlusGold); double tpRelative = 0; double fpRelative = 0; double cummulativeCorrect = 0; double auc = 0; double allPositive = 0; double averageScore = 0; for (Pair<Double, Boolean> p : scoredPlusGold) { if (p.second) allPositive += 1; averageScore += p.first; } averageScore /= scoredPlusGold.size(); sum.relativeThreshold = averageScore; double maxF = 0; double maxFThresh = 0; double logLike = 0; double maxAcc = 0; double maxAccThresh = 0; sum.relativePrecision = Double.NaN; for (int i = 0; i < scoredPlusGold.size(); ++i) { Pair<Double, Boolean> p = scoredPlusGold.get(i); if (p.second) { ++cummulativeCorrect; auc += cummulativeCorrect / ((i + 1) * allPositive); } double tp = cummulativeCorrect; double fp = (i + 1) - cummulativeCorrect; double fn = allPositive - cummulativeCorrect; double tn = (scoredPlusGold.size() - (i + 1)) - fn; double precision = (double) (tp) / (tp + fp); double recall = (double) (tp) / (tp + fn); double accuracy = (tp + tn) / scoredPlusGold.size(); double f1 = 2 * precision * recall / (precision + recall); if (p.second) { if (p.first > sum.relativeThreshold) tpRelative++; } else { if (p.first > sum.relativeThreshold) fpRelative++; } if (f1 > maxF) { maxF = f1; maxFThresh = p.first; } if (accuracy > maxAcc) { maxAcc = accuracy; maxAccThresh = p.first; } double prob = p.second ? p.first : 1 - p.first; if (prob < 0 || prob > 1) { logLike = Double.NaN; } if (prob > limitProb) { prob = limitProb; } if (prob < 1 - limitProb) { prob = 1 - limitProb; } logLike += Math.log(prob); } sum.maxFScore = maxF; sum.maxFScoreThreshold = maxFThresh; sum.auc = auc; sum.pearsonsR = pearsonsR(); sum.logLikelihood = logLike; sum.maxAccuracy = maxAcc; sum.maxAccuracyThreshold = maxAccThresh; sum.relativePrecision = tpRelative / (tpRelative + (fpRelative * (allPositive / (scoredPlusGold.size() - allPositive)))); if (Double.isNaN(sum.relativePrecision)) sum.relativePrecision = 0; sum.relativeRecall = tpRelative / allPositive; sum.relativeFScore = 2 * sum.relativePrecision * sum.relativeRecall / (sum.relativePrecision + sum.relativeRecall); if (Double.isNaN(sum.relativeFScore)) sum.relativeFScore = 0; return sum; }
From source file:com.joptimizer.optimizers.LPOptimizationRequest.java
public void setUb(DoubleMatrix1D ub) { for (int i = 0; i < ub.size(); i++) { double ubi = ub.getQuick(i); if (Double.isNaN(ubi) || Double.isInfinite(ubi)) { throw new IllegalArgumentException( "The upper bounds can not be set to Double.NaN or Double.INFINITY"); }/* ww w . j ava 2 s . c om*/ } this.ub = ub; }
From source file:com.sonicle.webtop.core.io.input.XlsPartsProcessorOLD.java
@Override public void processRecord(Record record) { cellValue = null;/*from w w w.j a v a2 s . c o m*/ switch (record.getSid()) { case BoundSheetRecord.sid: BoundSheetRecord bsr = (BoundSheetRecord) record; if (!sheetFound) { if (StringUtils.equals(bsr.getSheetname(), sheetName)) { sheetFound = true; columnNames = new LinkedHashMap<>(); columnIndexes = new HashMap<>(); } } else { close(); } break; case SSTRecord.sid: sstRecord = (SSTRecord) record; break; case BlankRecord.sid: BlankRecord br = (BlankRecord) record; row = br.getRow(); col = br.getColumn(); cellValue = ""; break; case BoolErrRecord.sid: BoolErrRecord ber = (BoolErrRecord) record; row = ber.getRow(); col = ber.getColumn(); cellValue = ""; break; case FormulaRecord.sid: FormulaRecord fr = (FormulaRecord) record; row = fr.getRow(); col = fr.getColumn(); if (Double.isNaN(fr.getValue())) { // Formula result is a string that is stored in the next record! findNextStringRecord = true; nextRow = fr.getRow(); nextCol = fr.getColumn(); cellValue = null; } else { cellValue = formatTrackingListener.formatNumberDateCell(fr); } break; case StringRecord.sid: if (findNextStringRecord) { // String for formula StringRecord sr = (StringRecord) record; cellValue = sr.getString(); row = nextRow; col = nextCol; // Resets markers... findNextStringRecord = false; nextRow = -1; nextCol = -1; } break; case LabelRecord.sid: LabelRecord lr = (LabelRecord) record; row = lr.getRow(); col = lr.getColumn(); cellValue = lr.getValue(); break; case LabelSSTRecord.sid: LabelSSTRecord lsstr = (LabelSSTRecord) record; row = lsstr.getRow(); col = lsstr.getColumn(); if (sstRecord == null) { cellValue = "#ERROR(undefined string)"; } else { cellValue = sstRecord.getString(lsstr.getSSTIndex()).toString(); } break; case NoteRecord.sid: NoteRecord nr = (NoteRecord) record; row = nr.getRow(); col = nr.getColumn(); // TODO: Find object to match nrec.getShapeId() cellValue = "#ERROR(TODO)"; break; case NumberRecord.sid: NumberRecord rn = (NumberRecord) record; row = rn.getRow(); col = rn.getColumn(); cellValue = formatTrackingListener.formatNumberDateCell(rn); break; case RKRecord.sid: RKRecord rkr = (RKRecord) record; row = rkr.getRow(); col = rkr.getColumn(); cellValue = "#ERROR(TODO)"; break; default: cellValue = null; } if (row == headersRow) { String cellReference = CellReference.convertNumToColString(col); String name = (headersRow == firstDataRow) ? cellReference : StringUtils.defaultIfBlank(cellValue, cellReference); columnNames.put(name.toLowerCase(), name); columnIndexes.put(name, col); } }