Example usage for java.lang Double isInfinite

List of usage examples for java.lang Double isInfinite

Introduction

In this page you can find the example usage for java.lang Double isInfinite.

Prototype

public static boolean isInfinite(double v) 

Source Link

Document

Returns true if the specified number is infinitely large in magnitude, false otherwise.

Usage

From source file:Complex.java

/**
 * Returns a {@code Complex} whose value is {@code this * factor}, with {@code factor}
 * interpreted as a integer number.//from  ww w  . j  a  v  a  2s  .c  o m
 *
 * @param  factor value to be multiplied by this {@code Complex}.
 * @return {@code this * factor}.
 * @see #multiply(Complex)
 */
public Complex multiply(final int factor) {
    if (isNaN) {
        return NaN;
    }
    if (Double.isInfinite(real) || Double.isInfinite(imaginary)) {
        return INF;
    }
    return createComplex(real * factor, imaginary * factor);
}

From source file:org.onebusaway.nyc.vehicle_tracking.impl.particlefilter.ParticleFilter.java

/**
 * Finds the most likely/occurring trip & phase combination among the
 * particles, then chooses the particle with highest likelihood of that pair. <br>
 * /*from w ww . j a v  a2  s .c om*/
 * FIXME violates generic particle contract by assuming data is of type
 * VehicleState
 * 
 * @param particles
 */
private void computeBestState(Multiset<Particle> particles) {
    /**
     * We choose the "most likely" particle over the entire distribution w.r.t
     * the inferred trip.
     */
    final TObjectDoubleMap<String> tripPhaseToProb = new TObjectDoubleHashMap<String>();

    final HashMultimap<String, Particle> particlesIdMap = HashMultimap.create();
    final SortedSet<Particle> bestParticles = new TreeSet<Particle>();
    String bestId = null;

    if (!_maxLikelihoodParticle) {
        double highestTripProb = Double.MIN_VALUE;
        int index = 0;
        for (final Multiset.Entry<Particle> pEntry : particles.entrySet()) {
            final Particle p = pEntry.getElement();
            p.setIndex(index++);

            final double w = FastMath.exp(p.getLogWeight() + FastMath.log(pEntry.getCount()));

            if (Double.isInfinite(w))
                continue;

            final VehicleState vs = p.getData();
            final String tripId = vs.getBlockState() == null ? "NA"
                    : vs.getBlockState().getBlockLocation().getActiveTrip().getTrip().toString();
            final String phase = vs.getJourneyState().toString();
            final String id = tripId + "." + phase;

            final double newProb = tripPhaseToProb.adjustOrPutValue(id, w, w);

            particlesIdMap.put(id, p);

            /**
             * Check most likely new trip & phase pairs, then find the most likely
             * particle(s) within those.
             */
            if (bestId == null || newProb > highestTripProb) {
                bestId = id;
                highestTripProb = newProb;
            }
        }
        bestParticles.addAll(particlesIdMap.get(bestId));
    } else {
        bestParticles.addAll(particles);
    }

    /**
     * after we've found the best trip & phase pair, we choose the highest
     * likelihood particle among those.
     */
    final Particle bestParticle = bestParticles.first();

    _mostLikelyParticle = bestParticle.cloneParticle();

}

From source file:it.geosolutions.imageio.plugins.nitronitf.ImageIOUtils.java

public static double[] findMinAndMax(double[] buffer, int pixelStride, int numBands) {
    double min = Double.MAX_VALUE;
    double max = -Double.MAX_VALUE;
    for (int i = 0; i < buffer.length; i += numBands) {
        for (int j = 0; j < pixelStride; ++j) {
            double value = buffer[i + j];
            if (!Double.isInfinite(value)) {
                if (value < min)
                    min = value;//from w ww  .  j a  v  a2 s  .  com
                if (value > max)
                    max = value;
            }
        }
    }
    return new double[] { min, max };
}

From source file:org.opentripplanner.analyst.request.IsoChroneSPTRendererAccSampling.java

/**
 * Sample a SPT using a SPTWalker and an AccumulativeGridSampler.
 * /* ww  w. j  ava  2 s . c om*/
 * @param spt
 * @return
 */
private void sampleSPT(ShortestPathTree spt, ZSampleGrid<WTWD> sampleGrid, final double d0,
        final double gridSizeMeters, final double v0, final double maxWalkDistance, final double cosLat) {

    AccumulativeMetric<WTWD> accMetric = new AccumulativeMetric<WTWD>() {
        @Override
        public WTWD cumulateSample(Coordinate C0, Coordinate Cs, double z, WTWD zS) {
            double t = z;
            double d = distanceLibrary.fastDistance(C0, Cs, cosLat);
            // additionnal time
            double dt = d / v0;
            // t weight
            double w = 1 / ((d + d0) * (d + d0));
            if (zS == null) {
                zS = new WTWD();
                zS.d = Double.MAX_VALUE;
            }
            zS.w = zS.w + w;
            zS.tw = zS.tw + w * (t + dt);
            if (d < zS.d)
                zS.d = d;
            return zS;
        }

        @Override
        public WTWD closeSample(WTWD zUp, WTWD zDown, WTWD zRight, WTWD zLeft) {
            double dMin = Double.MAX_VALUE;
            for (WTWD z : new WTWD[] { zUp, zDown, zRight, zLeft }) {
                if (z == null)
                    continue;
                if (z.d < dMin)
                    dMin = z.d;
            }
            WTWD z = new WTWD();
            z.w = 1.0;
            z.tw = Double.POSITIVE_INFINITY;
            z.d = dMin + gridSizeMeters;
            return z;
        }
    };
    final AccumulativeGridSampler<WTWD> gridSampler = new AccumulativeGridSampler<WTWD>(sampleGrid, accMetric);

    SPTWalker johnny = new SPTWalker(spt);
    johnny.walk(new SPTVisitor() {
        @Override
        public final boolean accept(Edge e) {
            return e instanceof StreetEdge;
        }

        @Override
        public final void visit(Coordinate c, State s0, State s1, double d0, double d1) {
            double wd0 = s0.getWalkDistance() + d0;
            double wd1 = s0.getWalkDistance() + d1;
            double t0 = wd0 > maxWalkDistance ? Double.POSITIVE_INFINITY : s0.getActiveTime() + d0 / v0;
            double t1 = wd1 > maxWalkDistance ? Double.POSITIVE_INFINITY : s1.getActiveTime() + d1 / v0;
            if (!Double.isInfinite(t0) || !Double.isInfinite(t1))
                gridSampler.addSamplingPoint(c, t0 < t1 ? t0 : t1);
        }
    }, d0);
    gridSampler.close();
}

From source file:de.Keyle.MyPet.entity.MyPet.java

public void decreaseSaturation(double value) {
    if (!Double.isNaN(value) && !Double.isInfinite(value)) {
        saturation = Math.max(1, Math.min(100, saturation - value));
    } else {//w  w w .j a  va2  s.  c o m
        MyPetApi.getLogger()
                .warning("Saturation was decreased by an invalid number!\n" + Util.stackTraceToString());
    }
}

From source file:de.bund.bfr.knime.pmmlite.views.chart.ChartCreator.java

public JFreeChart getChart(List<String> idsToPaint) throws ParseException, UnitException {
    if (varX == null || varY == null || varX.getName() == null || varY.getName() == null) {
        return new JFreeChart(null, JFreeChart.DEFAULT_TITLE_FONT, new XYPlot(), showLegend);
    }//from w w  w .  j  a  va2  s .c o  m

    NumberAxis xAxis = new NumberAxis(varX.getDisplayString());
    NumberAxis yAxis = new NumberAxis(varY.getDisplayString());
    XYPlot plot = new XYPlot(null, xAxis, yAxis, null);
    double usedMinX = Double.POSITIVE_INFINITY;
    double usedMaxX = Double.NEGATIVE_INFINITY;
    int index = 0;
    List<Color> defaultColors = ChartUtils.createColorList(idsToPaint.size());
    List<NamedShape> defaultShapes = ChartUtils.createShapeList(idsToPaint.size());

    for (String id : idsToPaint) {
        Plotable plotable = plotables.get(id);

        if (plotable == null) {
            continue;
        }

        if (plotable.getType() == Plotable.Type.BOTH || plotable.getType() == Plotable.Type.BOTH_MANY
                || plotable.getType() == Plotable.Type.FUNCTION
                || plotable.getType() == Plotable.Type.FUNCTION_SAMPLE) {
            double minArg = varX.to(MathUtils.nullToNan(plotable.getMinValues().get(varX.getName())),
                    plotable.getUnits().get(varX.getName()));
            double maxArg = varX.to(MathUtils.nullToNan(plotable.getMaxValues().get(varX.getName())),
                    plotable.getUnits().get(varX.getName()));

            if (Double.isFinite(minArg)) {
                usedMinX = Math.min(usedMinX, minArg);
            }

            if (Double.isFinite(maxArg)) {
                usedMaxX = Math.max(usedMaxX, maxArg);
            }
        }

        if (plotable.getType() == Plotable.Type.BOTH || plotable.getType() == Plotable.Type.BOTH_MANY) {
            for (Map<String, Integer> choice : plotable.getAllChoices(varX.getName())) {
                double[][] points = plotable.getPoints(varX, varY, choice);

                if (points != null) {
                    for (int i = 0; i < points[0].length; i++) {
                        usedMinX = Math.min(usedMinX, points[0][i]);
                        usedMaxX = Math.max(usedMaxX, points[0][i]);
                    }
                }
            }
        }

        if (plotable.getType() == Plotable.Type.DATASET || plotable.getType() == Plotable.Type.DATASET_MANY) {
            double[][] points = plotable.getPoints(varX, varY);

            if (points != null) {
                for (int i = 0; i < points[0].length; i++) {
                    usedMinX = Math.min(usedMinX, points[0][i]);
                    usedMaxX = Math.max(usedMaxX, points[0][i]);
                }
            }
        }

        if (plotable.getType() == Plotable.Type.FUNCTION_SAMPLE) {
            for (Double x : plotable.getSamples()) {
                if (x != null && Double.isFinite(x)) {
                    usedMinX = Math.min(usedMinX, x);
                    usedMaxX = Math.max(usedMaxX, x);
                }
            }
        }
    }

    if (Double.isInfinite(usedMinX)) {
        usedMinX = 0.0;
    }

    if (Double.isInfinite(usedMaxX)) {
        usedMaxX = 100.0;
    }

    if (varX.getName().equals(PmmUtils.TIME) || varX.getName().equals(PmmUtils.CONCENTRATION)) {
        usedMinX = Math.min(usedMinX, 0.0);
        xAxis.setAutoRangeIncludesZero(true);
    } else {
        xAxis.setAutoRangeIncludesZero(false);
    }

    if (varY.getName().equals(PmmUtils.TIME) || varY.getName().equals(PmmUtils.CONCENTRATION)) {
        yAxis.setAutoRangeIncludesZero(true);
    } else {
        yAxis.setAutoRangeIncludesZero(false);
    }

    if (usedMinX == usedMaxX) {
        usedMinX -= 1.0;
        usedMaxX += 1.0;
    }

    if (useManualRange && minX < maxX && minY < maxY) {
        usedMinX = minX;
        usedMaxX = maxX;
        xAxis.setRange(new Range(minX, maxX));
        yAxis.setRange(new Range(minY, maxY));
    }

    for (String id : idsToPaint) {
        Plotable plotable = plotables.get(id);

        if (plotable == null) {
            continue;
        }

        plotable.setFunctionSteps(resolution);

        switch (plotable.getType()) {
        case DATASET:
            plotDataSet(plot, plotable, id, defaultColors.get(index), defaultShapes.get(index));
            break;
        case DATASET_MANY:
            plotDataSetStrict(plot, plotable, id);
            break;
        case FUNCTION:
            plotFunction(plot, plotable, id, defaultColors.get(index), defaultShapes.get(index), usedMinX,
                    usedMaxX);
            break;
        case FUNCTION_SAMPLE:
            plotFunctionSample(plot, plotable, id, defaultColors.get(index), defaultShapes.get(index), usedMinX,
                    usedMaxX);
            break;
        case BOTH:
            plotBoth(plot, plotable, id, defaultColors.get(index), defaultShapes.get(index), usedMinX,
                    usedMaxX);
            break;
        case BOTH_MANY:
            plotBothStrict(plot, plotable, id, usedMinX, usedMaxX);
            break;
        default:
            throw new RuntimeException("Unknown type of plotable: " + plotable.getType());
        }

        index++;
    }

    return new JFreeChart(null, JFreeChart.DEFAULT_TITLE_FONT, plot, showLegend);
}

From source file:edu.duke.cs.osprey.ematrix.epic.SeriesFitter.java

static double[] fitSeries(DoubleMatrix1D[] samp, double trueVals[], double weights[], double lambda,
        boolean includeConst, int order, int PCOrder, boolean isPC[], boolean update, DoubleMatrix1D c,
        DoubleMatrix2D M) {//w ww .j a v a2  s. c  o  m
    //Default: quadratic with 0 constant term
    //includeConst adds the constant term and quartic adds 3rd-4th terms

    //If(update), then we are updating a previous fit with the same samp, trueVals
    //but different weights (and weights contains the difference in weights in this case)
    //c and M should be null unless we're updating or making a fit that we will update later

    long startTime = System.currentTimeMillis();

    int nd = samp[0].size();//number of degrees of freedom
    int numParams = getNumParams(nd, includeConst, order);

    if (PCOrder > order) {//add in parameters for PC orders
        int numPCs = countTrue(isPC);

        for (int n = order + 1; n <= PCOrder; n++)
            numParams += getNumParamsForOrder(numPCs, n);
    }

    int numSamples = samp.length;

    System.out.println("Fit has " + numSamples + " samples for " + numParams + " parameters");

    if (c == null)
        c = DoubleFactory1D.dense.make(numParams);
    if (M == null)
        M = DoubleFactory2D.dense.make(numParams, numParams);

    //scratch for terms of c, M
    DoubleMatrix1D cScratch = DoubleFactory1D.dense.make(numParams);
    DoubleMatrix2D MScratch = DoubleFactory2D.dense.make(numParams, numParams);

    if (!update) {
        for (int p = 0; p < numParams; p++)//deal with regularization
            M.set(p, p, lambda);
    }

    //long setupDoneTime = System.currentTimeMillis();
    //System.out.println("fitSeries setup time (ms): "+(setupDoneTime-startTime));

    for (int s = 0; s < numSamples; s++) {//summing each of these terms over the samples

        if ((!update) || (weights[s] != 0)) {
            //if updating, can ignore unchanged weights (weights[s]==0)

            double weight = 1;//weight for samples
            if (weights != null)
                weight = weights[s];

            //we want cScratch^T params = trueVals in the best-fit sense
            //Least-squares equations are then (sum_samples weight * MScratch) * params = sum_samples weight * c_scratch *trueVals
            //where MScratch is cScratch*cScratch^T
            calcSampParamCoeffs(cScratch, samp[s], nd, includeConst, order, PCOrder, isPC);

            Algebra.DEFAULT.multOuter(cScratch, cScratch, MScratch);
            MScratch.assign(Functions.mult(weight));
            M.assign(MScratch, Functions.plus);

            cScratch.assign(Functions.mult(trueVals[s] * weight));
            c.assign(cScratch, Functions.plus);
        }
    }

    DoubleMatrix2D C = DoubleFactory2D.dense.make(c.toArray(), numParams);//c as a column vector

    //long MCTime = System.currentTimeMillis();
    //System.out.println("fitSeries M, C calc time (ms): "+(MCTime-setupDoneTime));

    double[] v = null;//the best-fit parameters, as a column vector
    try {
        v = Algebra.DEFAULT.solve(M, C).viewColumn(0).toArray();
    } catch (IllegalArgumentException e) {//indices singular M
        //solve in a way robust to singularities
        //basically pseudoinverse(M)*C
        SingularValueDecomposition svd = new SingularValueDecomposition(M);
        //M = U*S*V', so M^-1 = V*invS*U'
        DoubleMatrix2D invS = svd.getS().copy();

        //this tolerance is from SingularValueDecomposition.java (used there to compute rank)
        //here we use the special case that M is square
        double eps = Math.pow(2.0, -52.0);
        double tol = invS.rows() * invS.get(0, 0) * eps;

        for (int i = 0; i < invS.rows(); i++) {
            double singVal = invS.get(i, i);
            if (singVal > tol)
                invS.set(i, i, 1. / singVal);
            else
                invS.set(i, i, 0);
        }

        DoubleMatrix2D ansCol = Algebra.DEFAULT.mult(Algebra.DEFAULT
                .mult(Algebra.DEFAULT.mult(svd.getV(), invS), Algebra.DEFAULT.transpose(svd.getU())), C);

        //DEBUG!!!!
        //DoubleMatrix2D checkC = Algebra.DEFAULT.mult(M, ansCol);

        v = ansCol.viewColumn(0).toArray();
    }

    //long vTime = System.currentTimeMillis();
    //System.out.println("fitSeries matrix solution time (ms): "+(vTime-MCTime));

    //Checking fit accuracy (done in fitSeriesIterative if updating)
    if (!update) {//Calculating the mean residual like this doesn't make sense for an update
        //since we don't have the actual weights
        double meanResidual = 0;
        double weightSum = 0;

        for (int s = 0; s < numSamples; s++) {
            double bv = evalSeries(v, samp[s], nd, includeConst, order, PCOrder, isPC);

            double weight = 1;//weight for samples
            if (weights != null)
                weight = weights[s];

            double residTerm = (trueVals[s] - bv) * (trueVals[s] - bv);

            if (Double.isInfinite(residTerm) || Double.isNaN(residTerm)) {
                System.err.println("ERROR: SeriesFitter.fitSeries gives infinite residual term: " + residTerm);

                System.out.print("Sample: ");
                for (int dof = 0; dof < nd; dof++)
                    System.err.print(samp[s].get(dof) + " ");
                System.out.println();

                System.err.println(" TRUEVAL=" + trueVals[s] + " BV=" + bv);
                System.err.println("params:");
                for (double param : v)
                    System.out.println(param);

                throw new RuntimeException("Infinite or nan residual");
            }

            //if want sample-by-sample output
            //System.out.println("TRAININGSET TRUE:"+trueVals[s]+" G2:"+bv);

            meanResidual += weight * residTerm;
            weightSum += weight;
        }

        meanResidual /= weightSum;
        System.out.println("TRAINING SET MEAN RESIDUAL:" + meanResidual);
    }

    long doneTime = System.currentTimeMillis();
    //System.out.println("fitSeries checking time (ms): "+(doneTime-vTime));
    System.out.println("fitSeries time (ms): " + (doneTime - startTime));

    return v;
}

From source file:Complex.java

/**
 * Returns a {@code Complex} whose value is {@code this * factor}, with {@code factor}
 * interpreted as a real number./*  ww w  .j av a2s  .  c  o m*/
 *
 * @param  factor value to be multiplied by this {@code Complex}.
 * @return {@code this * factor}.
 * @see #multiply(Complex)
 */
public Complex multiply(double factor) {
    if (isNaN || Double.isNaN(factor)) {
        return NaN;
    }
    if (Double.isInfinite(real) || Double.isInfinite(imaginary) || Double.isInfinite(factor)) {
        // we don't use isInfinite() to avoid testing for NaN again
        return INF;
    }
    return createComplex(real * factor, imaginary * factor);
}

From source file:net.tsquery.DataEndpoint.java

private double getValue(DataPoint point) {
    double value;
    if (point.isInteger()) {
        value = (double) point.longValue();
    } else {/*  www  .jav  a  2  s. co m*/
        final double doubleValue = point.doubleValue();
        if (doubleValue != doubleValue || Double.isInfinite(doubleValue)) {
            throw new IllegalStateException("invalid datapoint found");
        }
        value = doubleValue;
    }

    return value;
}

From source file:org.jactr.core.module.procedural.six.learning.DefaultProceduralLearningModule6.java

public void reward(double initialReward) {
    IModel model = getModel();//from w ww.  j a  va2  s .c  om
    boolean log = LOGGER.isDebugEnabled() || Logger.hasLoggers(model);

    if (log) {
        String msg = "Rewarding " + _firedProductions.size() + " productions by " + initialReward;
        LOGGER.debug(msg);
        Logger.log(model, Logger.Stream.PROCEDURAL, msg);
    }

    double now = ACTRRuntime.getRuntime().getClock(model).getTime();
    IExpectedUtilityEquation equation = getExpectedUtilityEquation();

    for (Map.Entry<Double, IProduction> entry : _firedProductions.entrySet()) {
        double discountedReward = initialReward - (now - entry.getKey());
        IProduction p = entry.getValue();

        ISubsymbolicProduction6 ssp = (ISubsymbolicProduction6) p.getSubsymbolicProduction();

        double utility = equation.computeExpectedUtility(p, model, discountedReward);

        if (!(Double.isNaN(utility) || Double.isInfinite(utility)))
            ssp.setExpectedUtility(utility);

        if (log) {
            String msg = "Discounted reward for " + p + " to " + discountedReward + " for a learned utility of "
                    + utility;
            LOGGER.debug(msg);
            Logger.log(model, Logger.Stream.PROCEDURAL, msg);
        }
    }

    _firedProductions.clear();
}