List of usage examples for java.lang Double isInfinite
public static boolean isInfinite(double v)
From source file:org.broadinstitute.gatk.engine.recalibration.RecalDatumNode.java
/** * Calculate the phred-scaled p-value for a chi^2 test for independent among subnodes of this node. * * The chi^2 value indicates the degree of independence of the implied error rates among the * immediate subnodes//from www . ja v a 2 s .c om * * @return the phred-scaled p-value for chi2 penalty, or 0.0 if it cannot be calculated */ private double calcPenalty() { if (isLeaf() || freeToMerge()) return 0.0; else if (subnodes.size() == 1) // only one value, so its free to merge away return 0.0; else { final long[][] counts = new long[subnodes.size()][2]; int i = 0; for (final RecalDatumNode<T> subnode : subnodes) { // use the yates correction to help avoid all zeros => NaN counts[i][0] = Math.round(subnode.getRecalDatum().getNumMismatches()) + 1L; counts[i][1] = subnode.getRecalDatum().getNumObservations() + 2L; i++; } try { final double chi2PValue = new ChiSquareTestImpl().chiSquareTest(counts); final double penalty = -10.0 * Math.log10(Math.max(chi2PValue, SMALLEST_CHI2_PVALUE)); // make sure things are reasonable and fail early if not if (Double.isInfinite(penalty) || Double.isNaN(penalty)) throw new ReviewedGATKException("chi2 value is " + chi2PValue + " at " + getRecalDatum()); return penalty; } catch (MathException e) { throw new ReviewedGATKException("Failed in calculating chi2 value", e); } } }
From source file:jp.co.acroquest.jsonic.Formatter.java
public boolean format(final JSON json, final Context context, final Object src, final Object o, final OutputSource out) throws Exception { NumberFormat f = context.getNumberFormat(); if (f != null) { StringFormatter.serialize(context, f.format(o), out); } else {//from ww w . j a va 2 s . co m double d = ((Number) o).doubleValue(); if (Double.isNaN(d) || Double.isInfinite(d)) { if (context.getMode() != Mode.SCRIPT) { out.append('"'); out.append(o.toString()); out.append('"'); } else if (Double.isNaN(d)) { out.append("Number.NaN"); } else { out.append("Number."); out.append((d > 0) ? "POSITIVE" : "NEGATIVE"); out.append("_INFINITY"); } } else { out.append(o.toString()); } } return false; }
From source file:org.kalypso.model.wspm.tuhh.core.profile.LengthSectionCreator.java
protected static Double getMinValueFor(final IProfile profil, final int indexHeight, final String component, final double precision) { final Double[] values = ProfileUtil.getInterpolatedValues(profil, component); final IRecord[] points = profil.getPoints(); double minValue = Double.POSITIVE_INFINITY; for (int i = 0; i < values.length; i++) { final IRecord point = points[i]; final Double value = values[i]; final Object height = point.getValue(indexHeight); if (value != null && height instanceof Number) { final double doubleHeight = ((Number) height).doubleValue(); /* Only consider points that are NOT same as height */ if (Math.abs(value - doubleHeight) > precision) { minValue = Math.min(minValue, value); }// w w w. j av a 2s . co m } } if (Double.isInfinite(minValue)) return Double.NaN; return minValue; }
From source file:org.hyperic.hq.ui.action.resource.common.monitor.visibility.IndicatorChartsAction.java
/** * TODO: The logic here is similar to DataManagerEJBImpl.getAggData(). * Need to consolidate the code./*from www . j a va2 s .c o m*/ * */ private double[] getAggregateData(MeasurementTemplate template, List<HighLowMetricValue> metricData) { final boolean debug = log.isDebugEnabled(); if (metricData.size() == 0) { return null; } double high = Double.MIN_VALUE; double low = Double.MAX_VALUE; double total = 0; Double lastVal = null; int count = 0; long last = Long.MIN_VALUE; for (Iterator<HighLowMetricValue> it = metricData.iterator(); it.hasNext();) { final HighLowMetricValue mv = it.next(); final double currentLowValue = mv.getLowValue(); final double currentHighValue = mv.getHighValue(); final double currentValue = mv.getValue(); final int currentCount = mv.getCount(); final long currentTimestamp = mv.getTimestamp(); if (!Double.isNaN(currentLowValue) && !Double.isInfinite(currentLowValue)) { low = Math.min(mv.getLowValue(), low); } if (!Double.isNaN(currentHighValue) && !Double.isInfinite(currentHighValue)) { high = Math.max(mv.getHighValue(), high); } if (mv.getTimestamp() > last && !Double.isNaN(currentValue) && !Double.isInfinite(currentValue)) { lastVal = currentValue; } count += currentCount; if (!Double.isNaN(currentValue) && !Double.isInfinite(currentValue)) { total += currentValue * currentCount; } if (debug) { log.debug("Measurement=" + template.getName() + ", Current {Low=" + currentLowValue + ", High=" + currentHighValue + ", Value=" + currentValue + ", Count=" + currentCount + ", Timestamp=" + currentTimestamp + "}, Summary {Low=" + low + ", High=" + high + ", Total=" + total + ", Count=" + count + "}"); } } // This should only happen if every value in the array is NaN/Infinity... // ...if so, set low to zero if (low == Double.MAX_VALUE) { low = 0; } if (high == Double.MIN_VALUE) { high = 0; } // ...low should never be greater than high... assert (low <= high); double avg = 0.0d; // calculate average if count is more than 0... if (count > 0 && !(low == 0 && high == 0)) { avg = (double) total / count; } /* TODO Ensure this is true, have seen some odd cases where the data makes these assertion fail // ...low should never be greater than avg... assert(low <= avg); // ...avg should never be greater than high... assert(avg <= high); */ final double[] data = new double[MeasurementConstants.IND_LAST_TIME + 1]; data[MeasurementConstants.IND_MIN] = low; data[MeasurementConstants.IND_AVG] = avg; data[MeasurementConstants.IND_MAX] = high; data[MeasurementConstants.IND_CFG_COUNT] = count; if (lastVal != null) { data[MeasurementConstants.IND_LAST_TIME] = lastVal; } if (debug) { log.debug("Measurement=" + template.getName() + ", Last {Value=" + lastVal + "}, Summary {Avg=" + avg + ", Low=" + low + ", High=" + high + ", Total=" + total + ", Count=" + count + "}"); } return data; }
From source file:projects.upc.exec.HrDiagram.java
/** * Update the {@link HrDiagram#chartPanel}. *//* ww w . j av a2s .com*/ private void updateChart() { XYSeries series = new XYSeries("UPC HR diagram"); for (Entry<UpcStar, SsaCrossMatch> xm : starsToPlot.entrySet()) { UpcStar upcStar = xm.getKey(); SsaCrossMatch ssa = xm.getValue(); // Get the SSA colours of the UPC star double b = ssa.ssaB; double r2 = ssa.ssaR2; // double i = ssa.ssaI; // Use the parallax to correct the apparent magnitude to absolute magnitude. // Extract the parallax and error to use double p = (useHip && upcStar.isHipparcosStar()) ? upcStar.srcPi : upcStar.absPi; double sigma_p = (useHip && upcStar.isHipparcosStar()) ? upcStar.srcPiErr : upcStar.absPiErr; // Filter on the fractional parallax error double f = sigma_p / p; if (f > fMax) { continue; } // Correct to arcseconds p /= 1000; sigma_p /= 1000; // Get the distance double d = DistanceFromParallax.getDistance(p, sigma_p, method); // Filter & convert to absolute magnitude if (d > 0 && !Double.isInfinite(d)) { double B = MagnitudeUtils.getAbsoluteMagnitude(d, b); series.add(b - r2, B); } } XYSeriesCollection data = new XYSeriesCollection(); data.addSeries(series); // Set up the renderer XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(); renderer.setSeriesLinesVisible(0, false); renderer.setSeriesShapesVisible(0, true); renderer.setSeriesShape(0, new Ellipse2D.Double(-0.5, -0.5, 1, 1)); // Configure axes NumberAxis xAxis = new NumberAxis("B - R [mag]"); xAxis.setRange(-1.0, 3.5); NumberAxis yAxis = new NumberAxis("B [mag]"); yAxis.setInverted(true); yAxis.setRange(-5, 15); // Configure plot XYPlot xyplot = new XYPlot(data, xAxis, yAxis, renderer); xyplot.setBackgroundPaint(Color.white); JFreeChart chart = new JFreeChart("HR diagram of UPC stars with SSA cross-matches", xyplot); chart.removeLegend(); chart.setBackgroundPaint(Color.white); if (chartPanel == null) { // Branch is used on initialisation chartPanel = new ChartPanel(chart); } else { chartPanel.setChart(chart); } }
From source file:beast.structuredCoalescent.distribution.IndependentStructuredCoalescent.java
public double calculateLogP() { // newly calculate tree intervals treeIntervalsInput.get().calculateIntervals(); // correctly calculate the daughter nodes at coalescent intervals in the case of // bifurcation or in case two nodes are at the same height treeIntervalsInput.get().swap();//from w ww .j a va 2 s . com // Set up ArrayLists for the indices of active lineages and the lineage state probabilities activeLineages = new ArrayList<Integer>(); lineStateProbs = new ArrayList<Double>(); // Compute likelihood at each integration time and tree event starting at final sampling time and moving backwards logP = 0; // set the current time double currTime = 0.0; // total number of intervals final int intervalCount = treeIntervalsInput.get().getIntervalCount(); // interval time counter int t = 0; // initialize the number of lineages nr_lineages = 0; // Captures the probabilities of lineages being in a state double[] p; // Initialize the migration rates matrix double[][] migration_rates = new double[states][states]; int c = 0; for (int k = 0; k < states; k++) { for (int l = 0; l < states; l++) { if (k != l) { migration_rates[k][l] = migrationRatesInput.get().getArrayValue(c); c++; } else { // diagonal migration_rates[k][l] = 0.0; } } } // Initialize the coalescent rates double[] coalescent_rates = new double[states]; for (int k = 0; k < states; k++) { coalescent_rates[k] = coalescentRatesInput.get().getArrayValue(k) / 2;//(epiModelInput.get().getF(t,k,k) / (Y.get(k)*Y.get(k))); } // integrate until there are no more tree intervals do { double nextIntervalTime = treeIntervalsInput.get().getInterval(t); // Length of the current interval final double duration = nextIntervalTime;// - currTime; // if the current interval has a length greater than 0, integrate if (duration > 0) { if (dependentHistory) p = new double[lineStateProbs.size()]; // Captures the probabilities of lineages being in a state else p = new double[lineStateProbs.size() + 1]; // Captures the probabilities of lineages being in a state, last one keeps track of the probability // convert the array list to double[] for (int i = 0; i < lineStateProbs.size(); i++) p[i] = lineStateProbs.get(i); // not needed if (!dependentHistory) p[lineStateProbs.size()] = 1; double[] p_for_ode = new double[p.length]; double ts = 0.0; // If proportial time step is true, set the integration time for the given interval // inverse proportional to the number of lineages if (propTimeStep) ts = timeStep / lineStateProbs.size(); else ts = timeStep; // Never choose a longer time step than the integration window if (duration < (ts / 2)) ts = duration / 2; FirstOrderIntegrator integrator = new ClassicalRungeKuttaIntegrator(ts); // set the odes FirstOrderDifferentialEquations ode = new independent_ode_integrator(migration_rates, coalescent_rates, nr_lineages, states); // integrate integrator.integrate(ode, 0, p, duration, p_for_ode); // If the Dimension is larger than the maximum integer, at least one state prob is below 0 and the step is rejected if (ode.getDimension() == Integer.MAX_VALUE) { System.out.println(lineStateProbs.size()); System.out.println("lalalallal"); return Double.NEGATIVE_INFINITY; } for (int i = 0; i < lineStateProbs.size(); i++) lineStateProbs.set(i, p_for_ode[i]); } // update the time currTime = nextIntervalTime; // event is coalescent event if (treeIntervalsInput.get().getIntervalType(t) == IntervalType.COALESCENT) { logP += coalesce(t); nr_lineages--; } // event is sampling event if (treeIntervalsInput.get().getIntervalType(t) == IntervalType.SAMPLE) { addLineages(t); nr_lineages++; } // update the interval number t++; } while (t < intervalCount); //Compute likelihood of remaining tree intervals (coal events occuring before origin) if (Double.isInfinite(logP)) logP = Double.NEGATIVE_INFINITY; if (max_posterior < logP && logP < 0) { max_posterior = logP; max_mig = new double[states * (states - 1)]; max_coal = new double[states]; for (int i = 0; i < 1; i++) max_mig[i] = migrationRatesInput.get().getArrayValue(i); for (int i = 0; i < 1; i++) max_coal[i] = coalescentRatesInput.get().getArrayValue(i); } return logP; }
From source file:ponzu.impl.test.Verify.java
/** * Asserts that two doubles are not equal concerning a delta. If the expected value is infinity then the delta value * is ignored.//from w w w.ja va 2 s . com */ public static void assertNotEquals(String itemName, double notExpected, double actual, double delta) { // handle infinity specially since subtracting to infinite values gives NaN and the // the following test fails try { if (Double.isInfinite(notExpected) && notExpected == actual || Math.abs(notExpected - actual) <= delta) { Assert.fail(itemName + " should not be equal:<" + notExpected + '>'); } } catch (AssertionError e) { throwMangledException(e); } }
From source file:beast.structuredCoalescent.distribution.Masco.java
public double calculateLogP() { // newly calculate tree intervals treeIntervalsInput.get().calculateIntervals(); // correctly calculate the daughter nodes at coalescent intervals in the case of // bifurcation or in case two nodes are at the same height treeIntervalsInput.get().swap();//from w ww . j a v a 2s .co m // Set up ArrayLists for the indices of active lineages and the lineage state probabilities activeLineages = new ArrayList<Integer>(); lineStateProbs = new ArrayList<Double>(); // Compute likelihood at each integration time and tree event starting at final sampling time and moving backwards logP = 0; // set the current time double currTime = 0.0; // total number of intervals final int intervalCount = treeIntervalsInput.get().getIntervalCount(); // interval time counter int t = 0; // initialize the number of lineages nr_lineages = 0; // Captures the probabilities of lineages being in a state double[] p; // Initialize the migration rates matrix double[][] migration_rates = new double[states][states]; int c = 0; for (int k = 0; k < states; k++) { for (int l = 0; l < states; l++) { if (k != l) { migration_rates[k][l] = migrationRatesInput.get().getArrayValue(c); c++; } else { // diagonal migration_rates[k][l] = 0.0; } } } // Initialize the coalescent rates double[] coalescent_rates = new double[states]; for (int k = 0; k < states; k++) { coalescent_rates[k] = coalescentRatesInput.get().getArrayValue(k) / 2;//(epiModelInput.get().getF(t,k,k) / (Y.get(k)*Y.get(k))); } // integrate until there are no more tree intervals do { double nextIntervalTime = treeIntervalsInput.get().getInterval(t); // Length of the current interval final double duration = nextIntervalTime;// - currTime; // if the current interval has a length greater than 0, integrate if (duration > 0) { if (dependentHistory) p = new double[lineStateProbs.size()]; // Captures the probabilities of lineages being in a state else p = new double[lineStateProbs.size() + 1]; // Captures the probabilities of lineages being in a state, last one keeps track of the probability // convert the array list to double[] for (int i = 0; i < lineStateProbs.size(); i++) p[i] = lineStateProbs.get(i); // not needed if (!dependentHistory) p[lineStateProbs.size()] = 1; double[] p_for_ode = new double[p.length]; double ts = 0.0; // If proportial time step is true, set the integration time for the given interval // inverse proportional to the number of lineages if (propTimeStep) ts = timeStep / lineStateProbs.size(); else ts = timeStep; // Never choose a longer time step than the integration window if (duration < (ts / 2)) ts = duration / 2; FirstOrderIntegrator integrator = new ClassicalRungeKuttaIntegrator(ts); // set the odes FirstOrderDifferentialEquations ode = new ode_masco(migration_rates, coalescent_rates, nr_lineages, states); // integrate integrator.integrate(ode, 0, p, duration, p_for_ode); // If the Dimension is larger than the maximum integer, at least one state prob is below 0 and the step is rejected if (ode.getDimension() == Integer.MAX_VALUE) { System.out.println(lineStateProbs.size()); System.out.println("lalalallal"); return Double.NEGATIVE_INFINITY; } for (int i = 0; i < lineStateProbs.size(); i++) lineStateProbs.set(i, p_for_ode[i]); } // update the time currTime = nextIntervalTime; // event is coalescent event if (treeIntervalsInput.get().getIntervalType(t) == IntervalType.COALESCENT) { logP += coalesce(t); nr_lineages--; } // event is sampling event if (treeIntervalsInput.get().getIntervalType(t) == IntervalType.SAMPLE) { logP += normalizeLineages(); addLineages(t); nr_lineages++; } // update the interval number t++; } while (t < intervalCount); //Compute likelihood of remaining tree intervals (coal events occuring before origin) if (Double.isInfinite(logP)) logP = Double.NEGATIVE_INFINITY; if (max_posterior < logP && logP < 0) { max_posterior = logP; max_mig = new double[states * (states - 1)]; max_coal = new double[states]; for (int i = 0; i < 1; i++) max_mig[i] = migrationRatesInput.get().getArrayValue(i); for (int i = 0; i < 1; i++) max_coal[i] = coalescentRatesInput.get().getArrayValue(i); } // System.exit(0); return logP; }
From source file:com.opengamma.analytics.financial.model.volatility.BlackScholesFormulaRepository.java
/** * /* w ww . j a v a2s . c o m*/ * @param spot The spot value of the underlying * @param spotDelta The spot delta * @param timeToExpiry The time-to-expiry * @param lognormalVol The log-normal volatility * @param interestRate The interest rate * @param costOfCarry The cost-of-carry rate * @param isCall true for call * @return The strike * Note that the parameter range is more restricted for this method because the strike is undetermined for infinite/zero valued parameters */ public static double strikeForDelta(final double spot, final double spotDelta, final double timeToExpiry, final double lognormalVol, final double interestRate, final double costOfCarry, final boolean isCall) { ArgumentChecker.isTrue(spot > 0.0, "non-positive/NaN spot; have {}", spot); ArgumentChecker.isTrue(timeToExpiry > 0.0, "non-positive/NaN timeToExpiry; have {}", timeToExpiry); ArgumentChecker.isTrue(lognormalVol > 0.0, "non-positive/NaN lognormalVol; have {}", lognormalVol); ArgumentChecker.isFalse(Double.isNaN(interestRate), "interestRate is NaN"); ArgumentChecker.isFalse(Double.isNaN(costOfCarry), "costOfCarry is NaN"); ArgumentChecker.isFalse(Double.isInfinite(spot), "spot is infinite"); ArgumentChecker.isFalse(Double.isInfinite(spotDelta), "spotDelta is infinite"); ArgumentChecker.isFalse(Double.isInfinite(timeToExpiry), "timeToExpiry is infinite"); ArgumentChecker.isFalse(Double.isInfinite(lognormalVol), "lognormalVol is infinite"); ArgumentChecker.isFalse(Double.isInfinite(interestRate), "interestRate is infinite"); ArgumentChecker.isFalse(Double.isInfinite(costOfCarry), "costOfCarry is infinite"); final double rescaledDelta = spotDelta * Math.exp((-costOfCarry + interestRate) * timeToExpiry); Validate.isTrue( (isCall && rescaledDelta > 0. && rescaledDelta < 1.) || (!isCall && spotDelta < 0. && rescaledDelta > -1.), "delta/Math.exp((costOfCarry - interestRate) * timeToExpiry) out of range, ", rescaledDelta); final double sigmaRootT = lognormalVol * Math.sqrt(timeToExpiry); final double rescaledSpot = spot * Math.exp(costOfCarry * timeToExpiry); final int sign = isCall ? 1 : -1; final double d1 = sign * NORMAL.getInverseCDF(sign * rescaledDelta); return rescaledSpot * Math.exp(-d1 * sigmaRootT + 0.5 * sigmaRootT * sigmaRootT); }
From source file:de.mpicbg.knime.hcs.base.nodes.preproc.OutlierRemoval.java
private boolean isValidNumber(double nb) { return !(Double.isInfinite(nb) || Double.isNaN(nb)); }