List of usage examples for java.lang Double isInfinite
public static boolean isInfinite(double v)
From source file:com.anhth12.optimize.solvers.BackTrackLineSearch.java
public double optimize(INDArray line, int lineSearchIteration, double initialStep, INDArray x, INDArray g) throws InvalidStepException { INDArray oldParameters;/*from ww w.ja v a 2 s. co m*/ double slope, test, alamin, alam, alam2, tmplam; double rhs1, rhs2, a, b, disc, oldAlam; double f, fold, f2; oldParameters = x.dup(); alam2 = 0.0; f2 = fold = optimizer.score(); if (logger.isDebugEnabled()) { logger.trace("ENTERING BACKTRACK\n"); logger.trace("Entering BackTrackLinnSearch, value = " + fold + ",\ndirection.oneNorm:" + line.norm1(Integer.MAX_VALUE) + " direction.infNorm:" + FastMath.max(Float.NEGATIVE_INFINITY, Transforms.abs(line).max(Integer.MAX_VALUE).getDouble(0))); } BooleanIndexing.applyWhere(g, new Or(Conditions.isNan(), Conditions.isInfinite()), new Value(Nd4j.EPS_THRESHOLD)); LinAlgExceptions.assertValidNum(g); double sum = line.norm2(Integer.MAX_VALUE).getDouble(0); if (sum > stpmax) { logger.warn("attempted step too big. scaling: sum= " + sum + ", stpmax= " + stpmax); line.muli(stpmax / sum); } //dot product slope = Nd4j.getBlasWrapper().dot(g, line); logger.debug("slope = " + slope); if (slope < 0) throw new InvalidStepException("Slope = " + slope + " is negative"); if (slope == 0) throw new InvalidStepException("Slope = " + slope + " is zero"); // find maximum lambda // converge when (delta x) / x < REL_TOLX for all coordinates. // the largest step size that triggers this threshold is // precomputed and saved in alamin INDArray maxOldParams = Transforms.abs(oldParameters); BooleanIndexing.applyWhere(maxOldParams, new Condition() { @Override public Boolean apply(Number input) { return input.doubleValue() < 1.0; } @Override public Boolean apply(IComplexNumber input) { return false; } }, new Value(1.0)); INDArray testMatrix = Transforms.abs(line).divi(maxOldParams); test = testMatrix.max(Integer.MAX_VALUE).getDouble(0); //no longer needed testMatrix = null; alamin = relTolx / test; alam = 1.0f; oldAlam = 0.0f; int iteration; // look for step size in direction given by "line" for (iteration = 0; iteration < maxIterations; iteration++) { // x = oldParameters + alam*line // initially, alam = 1.0, i.e. take full Newton step logger.trace("BackTrack loop iteration " + iteration + " : alam=" + alam + " oldAlam=" + oldAlam); logger.trace("before step, x.1norm: " + x.norm1(Integer.MAX_VALUE) + "\nalam: " + alam + "\noldAlam: " + oldAlam); assert (alam != oldAlam) : "alam == oldAlam"; if (stepFunction == null) stepFunction = new DefaultStepFunction(); stepFunction.step(x, line, new Object[] { alam, oldAlam }); //step double norm1 = x.norm1(Integer.MAX_VALUE).getDouble(0); logger.debug("after step, x.1norm: " + norm1); // check for convergence //convergence on delta x if ((alam < alamin) || smallAbsDiff(oldParameters, x)) { function.setParams(oldParameters); f = function.score(); logger.trace("EXITING BACKTRACK: Jump too small (alamin = " + alamin + "). Exiting and using xold. Value = " + f); return 0.0f; } function.setParams(x); oldAlam = alam; f = function.score(); logger.debug("value = " + f); // sufficient function increase (Wolf condition) if (f >= fold + ALF * alam * slope) { logger.debug("EXITING BACKTRACK: value=" + f); if (f < fold) throw new IllegalStateException( "Function did not increase: f = " + f + " < " + fold + " = fold"); return alam; } // if value is infinite, i.e. we've // jumped to unstable territory, then scale down jump else if (Double.isInfinite(f) || Double.isInfinite(f2)) { logger.warn("Value is infinite after jump " + oldAlam + ". f=" + f + ", f2=" + f2 + ". Scaling back step size..."); tmplam = .2f * alam; if (alam < alamin) { //convergence on delta x function.setParams(oldParameters); f = function.score(); logger.warn("EXITING BACKTRACK: Jump too small. Exiting and using xold. Value=" + f); return 0.0f; } } else { // backtrack if (alam == 1.0) // first time through tmplam = -slope / (2.0f * (f - fold - slope)); else { rhs1 = f - fold - alam * slope; rhs2 = f2 - fold - alam2 * slope; if ((alam - alam2) == 0) throw new IllegalStateException("FAILURE: dividing by alam-alam2. alam=" + alam); a = (rhs1 / (FastMath.pow(alam, 2)) - rhs2 / (FastMath.pow(alam2, 2))) / (alam - alam2); b = (-alam2 * rhs1 / (alam * alam) + alam * rhs2 / (alam2 * alam2)) / (alam - alam2); if (a == 0.0) tmplam = -slope / (2.0f * b); else { disc = b * b - 3.0f * a * slope; if (disc < 0.0) { tmplam = .5f * alam; } else if (b <= 0.0) tmplam = (-b + FastMath.sqrt(disc)) / (3.0f * a); else tmplam = -slope / (b + FastMath.sqrt(disc)); } if (tmplam > .5f * alam) tmplam = .5f * alam; // lambda <= .5 lambda_1 } } alam2 = alam; f2 = f; logger.debug("tmplam:" + tmplam); alam = Math.max(tmplam, .1f * alam); // lambda >= .1*Lambda_1 } return 0.0f; }
From source file:r.base.Types.java
@Generic @Primitive("is.finite") public static boolean isFinite(@Recycle double value) { return !Double.isInfinite(value); }
From source file:org.tsho.dmc2.core.chart.TrajectoryMultiRenderer.java
private void computeRanges() { Stepper.Point2D point;/* ww w .ja v a 2s . c om*/ double xLower, xUpper; double yLower, yUpper; for (int i = 0; i < stepperList.length; i++) { stepperList[i].initialize(); } point = stepperList[0].getCurrentPoint2D(); xLower = point.getX(); xUpper = point.getX(); yLower = point.getY(); yUpper = point.getY(); for (index = 0; index < rangeIterations; index++) { for (int i = 0; i < stepperList.length; i++) { point = stepperList[i].getCurrentPoint2D(); if (xLower > point.getX()) { xLower = point.getX(); } else if (xUpper < point.getX()) { xUpper = point.getX(); } if (yLower > point.getY()) { yLower = point.getY(); } else if (yUpper < point.getY()) { yUpper = point.getY(); } stepperList[i].step(); if (stopped) { break; } } } if (Double.isInfinite(xLower) || Double.isInfinite(xUpper) || Double.isInfinite(yLower) || Double.isInfinite(yUpper) || Double.isNaN(xLower) || Double.isNaN(xUpper) || Double.isNaN(yLower) || Double.isNaN(yUpper)) { throw new ModelException("Exception during range calculations: (infinite or not-a-number value found)"); } if (!timePlot) { plot.setDataRanges(new Range(xLower, xUpper), new Range(yLower, yUpper)); } else { plot.setDataRanges(new Range(transients, transients + iterations), new Range(yLower, yUpper)); } computeRanges = false; }
From source file:org.tsho.dmc2.core.chart.TrajectoryRenderer.java
private void computeRanges() { Stepper.Point2D point;/*from w w w. ja v a 2s . com*/ double xLower, xUpper; double yLower, yUpper; stepper.initialize(); point = stepper.getCurrentPoint2D(); xLower = xUpper = point.getX(); yLower = yUpper = point.getY(); for (index = 0; index < rangeIterations; index++) { if (stopped) { state = STATE_STOPPED; break; } stepper.step(); point = stepper.getCurrentPoint2D(); if (xLower > point.getX()) { xLower = point.getX(); } else if (xUpper < point.getX()) { xUpper = point.getX(); } if (yLower > point.getY()) { yLower = point.getY(); } else if (yUpper < point.getY()) { yUpper = point.getY(); } } if (Double.isInfinite(xLower) || Double.isInfinite(xUpper) || Double.isInfinite(yLower) || Double.isInfinite(yUpper) || Double.isNaN(xLower) || Double.isNaN(xUpper) || Double.isNaN(yLower) || Double.isNaN(yUpper)) { throw new ModelException("Exception during range calculations: (infinite or not-a-number value found)"); } if (!timePlot) { plot.setDataRanges(new Range(xLower, xUpper), new Range(yLower, yUpper)); } else { plot.setDataRanges(new Range(transients, transients + iterations), new Range(yLower, yUpper)); } computeRanges = false; }
From source file:mase.mason.world.DistanceSensorArcs.java
@Override public double[] normaliseValues(double[] vals) { double[] norm = new double[vals.length]; double max = Double.isInfinite(range) ? fieldDiagonal : range; for (int i = 0; i < vals.length; i++) { if (binary) { norm[i] = Double.isInfinite(vals[i]) ? -1 : 1; } else {//from w ww . j a v a 2 s .com norm[i] = Double.isInfinite(vals[i]) ? 1 : vals[i] / max * 2 - 1; } } return norm; }
From source file:r.base.Types.java
@Generic @Primitive("is.infinite") public static boolean isInfinite(@Recycle double value) { return Double.isInfinite(value); }
From source file:org.jactr.core.module.declarative.four.learning.DefaultBaseLevelActivationEquation.java
/** * Description of the Method//from w ww. j a v a 2s . com * * @param model * Description of the Parameter * @param c * Description of the Parameter * @return Description of the Return Value */ public double computeBaseLevelActivation(IModel model, IChunk c) { IDeclarativeModule4 declarativeModule = getDeclarativeModule(); IDeclarativeLearningModule4 declarativeLearningModule = getDeclarativeLearningModule(); ISubsymbolicChunk ssc = c.getSubsymbolicChunk(); double baseLevelActivation = 0; double noiseActivation = 0; if (LOGGER.isDebugEnabled()) LOGGER.debug("Computing activation for " + c); if (declarativeLearningModule.isBaseLevelLearningEnabled()) { if (LOGGER.isDebugEnabled()) LOGGER.debug("base level learning is enabled, calculating"); double now = ACTRRuntime.getRuntime().getClock(model).getTime(); // compute base level activation double minusD = -1.0 * declarativeLearningModule.getBaseLevelLearning(); double defAct = getProceduralModule().getDefaultProductionFiringTime(); double base = 0.0; if (LOGGER.isDebugEnabled()) LOGGER.debug("defAct=" + defAct + " minusD=" + minusD); IReferences referenceList = ssc.getReferences(); int optimization = 0; if (referenceList instanceof IOptimizedReferences) optimization = ((IOptimizedReferences) referenceList).getOptimizationLevel(); // exact portion double[] times = referenceList.getRelativeTimes(now); if (LOGGER.isDebugEnabled()) LOGGER.debug("Snagged " + times.length + " delta access times for " + c); if (optimization != 0) { for (double element : times) { double tMinusD = Math.pow(Math.max(defAct, element), minusD); base += tMinusD; if (LOGGER.isDebugEnabled()) LOGGER.debug("tMinusD for " + element + " = " + tMinusD + " base = " + base); } if (times.length == 0) base = Math.pow(defAct, minusD); } baseLevelActivation = base; if (LOGGER.isDebugEnabled()) LOGGER.debug( "NoOpt-BaseLevelActivation " + baseLevelActivation + " with " + times.length + " accesses"); /* * optimized is : 1-d 1-d (n-m)(t0 - tn-m ) ---------------------- * (1-d)(t0 - tn-m) where m is the optimization level (# of reference * times stored) n is the number of references total t0 is the creation * time tn-m is the largest time differential in the references stored */ long nMinusM = referenceList.getNumberOfReferences() - times.length; double defActT0 = Math.max(defAct, (now - ssc.getCreationTime())); double defActTnm = Math.max(defAct, (times.length == 0 ? 0 : times[times.length - 1])); // t0 - tn-m to the 1-d double numerator = 0; double denom = 0; // it's zero.. if (optimization == 0) { numerator = Math.pow(defActT0, minusD); denom = 1; } else { numerator = Math.pow(defActT0, 1 + minusD) - Math.pow(defActTnm, 1 + minusD); denom = Math.max(defAct, defActT0 - defActTnm); } base = nMinusM * numerator / ((1 + minusD) * denom); if (LOGGER.isDebugEnabled()) { LOGGER.debug(nMinusM + "," + numerator + "," + denom + "," + times.length); LOGGER.debug("defActT0 = " + defActT0 + " defActTnm = " + defActTnm); LOGGER.debug("referenceCount = " + referenceList.getNumberOfReferences() + " Optimization = " + optimization + " times=" + times.length); LOGGER.debug("Opt-BaseLevelActivation " + base); } if (!Double.isNaN(base) && !Double.isInfinite(base)) baseLevelActivation += base; baseLevelActivation = Math.log(baseLevelActivation); baseLevelActivation += declarativeModule.getBaseLevelConstant(); if (LOGGER.isDebugEnabled()) LOGGER.debug("Adding constant " + _declarativeModule.getBaseLevelConstant() + " BaseLevelActivation " + baseLevelActivation); } else { baseLevelActivation = ssc.getBaseLevelActivation(); if (LOGGER.isDebugEnabled()) LOGGER.debug("forcing baselevel activation to " + baseLevelActivation); } IRandomModule randomModule = getRandomModule(); if (randomModule != null) noiseActivation = randomModule.logisticNoise(declarativeModule.getActivationNoise()); // System.err.println("IModel time is now "+now); if (LOGGER.isDebugEnabled()) LOGGER.debug(c + ".BaseLevelActivation = " + baseLevelActivation); return baseLevelActivation + noiseActivation; }
From source file:org.hyperic.hq.bizapp.server.session.DashboardPortletBossImpl.java
@Transactional(readOnly = true) public List<Map<String, Object>> getMeasurementData(AuthzSubject subj, Integer resId, Integer mtid, AppdefEntityTypeID ctype, long begin, long end) throws PermissionException { List<Map<String, Object>> result = new ArrayList<Map<String, Object>>(); DateFormat dateFmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.US); long intv = (end - begin) / 60; Map<String, Object> chartData = new HashMap<String, Object>(); Resource res = resourceManager.findResourceById(resId); if (res == null || res.isInAsyncDeleteState()) { return result; }/*from w w w.j a va 2s. c om*/ AppdefEntityID aeid = AppdefUtil.newAppdefEntityId(res); try { chartData.put("resourceName", res.getName()); AppdefEntityID[] aeids; if (aeid.isGroup()) { List<AppdefEntityID> members = GroupUtil.getCompatGroupMembers(subj, aeid, null, PageControl.PAGE_ALL); aeids = (AppdefEntityID[]) members.toArray(new AppdefEntityID[members.size()]); } else if (ctype != null) { aeids = measurementBoss.getAutoGroupMemberIDs(subj, new AppdefEntityID[] { aeid }, ctype); } else { aeids = new AppdefEntityID[] { aeid }; } List<Measurement> metrics = measurementManager.findMeasurements(subj, mtid, aeids); // Get measurement name if (!metrics.isEmpty()) { Measurement measurement = metrics.get(0); chartData.put("measurementName", measurement.getTemplate().getName()); chartData.put("measurementUnits", measurement.getTemplate().getUnits()); } List<HighLowMetricValue> data = dataManager.getHistoricalData(metrics, begin, end, intv, 0, true, PageControl.PAGE_ALL); Map<String, List<Double>> metricData = new LinkedHashMap<String, List<Double>>(); for (HighLowMetricValue pt : data) { List<Double> metricValues = new ArrayList<Double>(); double val = pt.getValue(); if (Double.isNaN(val) || Double.isInfinite(val)) { continue; } metricValues.add(val); Date date = new Date(pt.getTimestamp()); metricData.put(dateFmt.format(date), metricValues); } chartData.put("data", metricData); result.add(chartData); } catch (AppdefEntityNotFoundException e) { log.error("AppdefEntityNotFound: " + aeid); } catch (GroupNotCompatibleException e) { log.error("GroupNotCompatibleException: " + aeid); } return result; }
From source file:geogebra.common.kernel.cas.AlgoIntegralDefinite.java
@Override public final void compute() { if (!f.isDefined() || !ageo.isDefined() || !bgeo.isDefined()) { n.setUndefined();// www . j a v a 2 s. com return; } // check for equal bounds double lowerLimit = a.getDouble(); double upperLimit = b.getDouble(); if (Kernel.isEqual(lowerLimit, upperLimit)) { n.setValue(0); return; } // check if f(a) and f(b) are defined double fa = f.evaluate(lowerLimit); double fb = f.evaluate(upperLimit); if (Double.isNaN(fa) || Double.isInfinite(fa) || Double.isNaN(fb) || Double.isInfinite(fb)) { if (!this.evaluateNumerically && !evaluateOnly() && !f.isFreehandFunction()) { computeSpecial(); } else { n.setUndefined(); } return; } // return if it should not be evaluated (i.e. is shade-only) if (evaluateOnly()) { n.setValue(Double.NaN); return; } /* * Try to use symbolic integral * * We only do this for functions that do NOT include divisions by their * variable. Otherwise there might be problems like: Integral[ 1/x, -2, * -1 ] would be undefined (log(-1) - log(-2)) Integral[ 1/x^2, -1, 1 ] * would be defined (-2) */ if (symbIntegral != null && symbIntegral.isDefined() && !f.includesDivisionByVar() && !f.includesNonContinuousIntegral()) { double val = symbIntegral.evaluate(upperLimit) - symbIntegral.evaluate(lowerLimit); n.setValue(val); if (n.isDefined()) return; } else if (symbIntegral != null && symbIntegral.isDefined() && !this.evaluateNumerically) { computeSpecial(); return; } // numerical integration // max_error = ACCURACY; // current maximum error // maxstep = 0; if (f.isFreehandFunction()) { n.setValue(freehandIntegration(f, lowerLimit, upperLimit)); // AbstractApplication.debug(n.getValue()+" "+numericIntegration(f, // lowerLimit, upperLimit)); } else { // more accurate numeric-integration for polynomials Function inFun = f.getFunction(); // check if it's a polynomial PolyFunction polyIntegral = inFun.getNumericPolynomialIntegral(); // it it is... if (polyIntegral != null) { // ... we can calculate the integral more accurately n.setValue(polyIntegral.evaluate(upperLimit) - polyIntegral.evaluate(lowerLimit)); } else { n.setValue(numericIntegration(f, lowerLimit, upperLimit)); } } /* * Application.debug("***\nsteps: " + maxstep); * Application.debug("max_error: " + max_error); */ }
From source file:gov.nasa.ensemble.common.CommonUtils.java
/** * Check whether two doubles are equal concerning a delta. If either value is infinity then the delta value is ignored. * /*from ww w . ja v a 2s .co m*/ * @param d1 * @param d2 * @param delta * @return boolean */ public static final boolean equals(double d1, double d2, double delta) { // handle infinity specially since subtracting two infinite values gives NaN if (Double.isInfinite(d1) || Double.isInfinite(d2)) return d1 == d2; return Math.abs(d1 - d2) <= delta; }