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:org.broadinstitute.gatk.engine.recalibration.RecalDatum.java

public synchronized void setEstimatedQReported(final double estimatedQReported) {
    if (estimatedQReported < 0)
        throw new IllegalArgumentException("estimatedQReported < 0");
    if (Double.isInfinite(estimatedQReported))
        throw new IllegalArgumentException("estimatedQReported is infinite");
    if (Double.isNaN(estimatedQReported))
        throw new IllegalArgumentException("estimatedQReported is NaN");

    this.estimatedQReported = estimatedQReported;
    empiricalQuality = UNINITIALIZED;/*w w  w  .  j  a  v  a 2 s . c  om*/
}

From source file:org.caleydo.neo4j.plugins.kshortestpaths.KShortestPathsAlgo.java

public List<WeightedPath> run(Node sourceNode, Node targetNode, int k, IPathReadyListener onPathReady) {
    StopWatch w = new StopWatch();
    w.start();//  w w w . ja v a2 s. c  om

    // Calculate shortest path first
    List<WeightedPath> paths = new ArrayList<>(k);
    profile("start", w);
    WeightedPath shortestPath = shortestPathFinder.findSinglePath(sourceNode, targetNode);
    if (shortestPath == null)
        return paths;
    profile("initial disjkra", w);
    PriorityQueue<WeightedPath> pathCandidates = new PriorityQueue<WeightedPath>(20,
            new Comparator<WeightedPath>() {
                @Override
                public int compare(WeightedPath o1, WeightedPath o2) {
                    return Double.compare(o1.weight(), o2.weight());
                }
            });

    Set<Integer> pathCandidateHashes = new HashSet<>();

    if (onPathReady != null) {
        onPathReady.onPathReady(shortestPath);
    }
    paths.add(shortestPath);

    pathCandidateHashes.add(generatePathHash(shortestPath));

    for (int i = 1; i < k; i++) {

        WeightedPath prevPath = paths.get(i - 1);

        for (Node spurNode : prevPath.nodes()) {
            if (spurNode.getId() == prevPath.endNode().getId())
                break;

            WeightedPath rootPath = getSubPathTo(prevPath, spurNode);

            for (Path path : paths) {
                Iterator<Relationship> pathIterator = path.relationships().iterator();
                boolean containsRootPath = true;

                // Test if the existing shortest path starts with the root path
                for (Relationship relationship : rootPath.relationships()) {
                    if (!pathIterator.hasNext()) {
                        containsRootPath = false;
                        break;
                    }

                    Relationship pathRelationship = pathIterator.next();
                    if (relationship.getId() != pathRelationship.getId()) {
                        containsRootPath = false;
                        break;
                    }
                }

                // If so, set edge weight of following edge in that path to infinity
                if (containsRootPath) {
                    if (pathIterator.hasNext()) {
                        Relationship r = pathIterator.next();
                        costEvaluator.addInvalidRelationship(r);
                        //profile("invalid: "+r,w);
                    }
                }
            }

            // Simulate removal of root path nodes (except spur node) by setting all their edge weights to
            // infinity
            Set<Long> badIds = new HashSet<Long>();
            for (Node rootPathNode : rootPath.nodes()) {
                if (rootPathNode.getId() != spurNode.getId()) {
                    badIds.add(rootPathNode.getId());
                    //for (Relationship relationship : getRelationships(rootPathNode)) {
                    //   costEvaluator.addInvalidRelationship(relationship);
                    //}
                    //profile("invalids: "+rootPathNode.getRelationships(),w);
                }
            }
            expander.setExtraIgnoreNodes(badIds);

            profile("Find next path", w);
            WeightedPath spurPath = shortestPathFinder.findSinglePath(spurNode, targetNode);
            profile("Found next path", w);
            if (spurPath != null && !Double.isInfinite(spurPath.weight())) {
                WeightedPath pathCandidate = concatenate(rootPath, spurPath);
                Integer pathHash = generatePathHash(pathCandidate);
                if (!pathCandidateHashes.contains(pathHash)) {
                    pathCandidates.add(pathCandidate);
                    pathCandidateHashes.add(pathHash);
                }
            }

            // Restore edges
            costEvaluator.clearInvalidRelationships();
            expander.setExtraIgnoreNodes(null);

        }

        if (pathCandidates.isEmpty())
            break;

        WeightedPath nextBest = pathCandidates.poll();
        profile("flush path", w);
        if (onPathReady != null) {
            onPathReady.onPathReady(nextBest);
        }
        paths.add(nextBest);

    }
    profile("done", w);
    return paths;
}

From source file:mase.mason.world.DistanceSensorArcs.java

protected WorldObject[] getCandidates() {
    if (objects != null) {
        return objects;
    } else {/*from   w w  w. java  2  s  .c om*/
        Bag neighbours = (Double.isInfinite(range) || field.allObjects.size() < 30) ? field.allObjects
                : field.getNeighborsWithinDistance(ag.getLocation(), range + ag.getRadius(), false, true);
        WorldObject[] objs = new WorldObject[neighbours.size()];
        int index = 0;
        for (Object n : neighbours) {
            if (n != ag) {
                for (Class type : types) {
                    if (type.isInstance(n)) {
                        objs[index++] = (WorldObject) n;
                        break;
                    }
                }
            }
        }
        if (index < objs.length) {
            objs = Arrays.copyOf(objs, index);
        }
        return objs;
    }
}

From source file:org.renjin.primitives.MathGroup.java

@Deferrable
@Builtin//w  w  w . java2 s.  c om
@DataParallel(value = PreserveAttributeStyle.ALL, passNA = true)
public static double signif(double x, int digits) {
    if (Double.isInfinite(x) || Double.isNaN(x)) {
        return x;
    }
    if (digits <= 0) {
        digits = 1;
    }
    return new BigDecimal(x).round(new MathContext(digits, RoundingMode.HALF_UP)).doubleValue();
}

From source file:org.deeplearning4j.optimize.VectorizedBackTrackLineSearchMinimum.java

public double optimize(DoubleMatrix line, int lineSearchIteration, DoubleMatrix g, DoubleMatrix params) {
    DoubleMatrix x, oldParameters;/*from  www  .j a va2 s  .c o  m*/
    double slope, test, alamin, alam, alam2, tmplam;
    double rhs1, rhs2, a, b, disc, oldAlam;
    double f, fold, f2;
    oldParameters = params.dup();

    alam2 = tmplam = 0.0;
    f2 = fold = function.getValue();
    if (logger.isDebugEnabled()) {
        logger.trace("ENTERING BACKTRACK\n");
        logger.trace("Entering BackTrackLnSrch, value=" + fold + ",\ndirection.oneNorm:" + line.norm1()
                + "  direction.infNorm:"
                + FastMath.max(Double.NEGATIVE_INFINITY, MatrixFunctions.abs(line).max()));
    }

    assert (!MatrixUtil.isNaN(g));
    double sum = line.norm2();
    //        if(sum > stpmax) {
    //            logger.warn("attempted step too big. scaling: sum= " + sum +
    //                    ", stpmax= "+ stpmax);
    //            line.muli(stpmax / sum);
    //        }

    //dot product
    slope = SimpleBlas.dot(g, line);
    logger.debug("slope = " + slope);

    // 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
    DoubleMatrix maxOldParams = new DoubleMatrix(line.length);
    for (int i = 0; i < line.length; i++) {
        maxOldParams.put(i, Math.max(Math.abs(oldParameters.get(i)), 1.0));

    }

    DoubleMatrix testMatrix = MatrixFunctions.abs(line).div(maxOldParams);

    test = testMatrix.max();

    alamin = relTolx / test;

    alam = 1.0;
    oldAlam = 0.0;
    int iteration = 0;
    // look for step size in direction given by "line"
    for (iteration = 0; iteration < maxIterations; iteration++) {
        function.setCurrentIteration(lineSearchIteration);
        // 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: " + params.norm1() + "\nalam: " + alam + "\noldAlam: " + oldAlam);
        assert (alam != oldAlam) : "alam == oldAlam";

        params.addi(line.mul(alam - oldAlam)); // step

        logger.debug("after step, x.1norm: " + params.norm1());

        // check for convergence
        //convergence on delta x
        if ((alam < alamin) || smallAbsDiff(oldParameters, params)) {
            //            if ((alam < alamin)) {
            function.setParameters(oldParameters);
            f = function.getValue();
            logger.trace("EXITING BACKTRACK: Jump too small (alamin=" + alamin
                    + "). Exiting and using xold. Value=" + f);
            return 0.0;
        }

        function.setParameters(params);
        oldAlam = alam;
        f = function.getValue();

        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 = .2 * alam;
            if (alam < alamin) { //convergence on delta x
                function.setParameters(oldParameters);
                f = function.getValue();
                logger.warn("EXITING BACKTRACK: Jump too small. Exiting and using xold. Value=" + f);
                return 0.0;
            }
        } else { // backtrack
            if (alam == 1.0) // first time through
                tmplam = -slope / (2.0 * (f - fold - slope));
            else {
                rhs1 = f - fold - alam * slope;
                rhs2 = f2 - fold - alam2 * slope;
                assert ((alam - alam2) != 0) : "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.0 * b);
                else {
                    disc = b * b - 3.0 * a * slope;
                    if (disc < 0.0) {
                        tmplam = .5 * alam;
                    } else if (b <= 0.0)
                        tmplam = (-b + FastMath.sqrt(disc)) / (3.0 * a);
                    else
                        tmplam = -slope / (b + FastMath.sqrt(disc));
                }
                if (tmplam > .5 * alam)
                    tmplam = .5 * alam; // lambda <= .5 lambda_1
            }
        }

        alam2 = alam;
        f2 = f;
        logger.debug("tmplam:" + tmplam);
        alam = Math.max(tmplam, .1 * alam); // lambda >= .1*Lambda_1

    }

    if (iteration >= maxIterations)
        throw new IllegalStateException("Too many iterations.");
    return 0.0;
}

From source file:pt.ua.ieeta.nero.crf.CRFModel.java

public int train(final InstanceList train, final InstanceList unlabeled, final EvolvingSolution solution,
        final List<BIOFeature> features, final int iterations) {
    // Get evolving solution
    List<IOptimizationTarget> targets = solution.getFeatureList();
    double ge = ((GEWeightOptimizationTarget) targets.get(0)).getGEWeight();
    double gvp = ((GPVOptimizationTarget) targets.get(1)).getGPVWeight();
    int numFeatures = ((NrFeaturesOptimizationTarget) targets.get(2)).getNumFeatures();

    List<BIOFeature> featuresSubSet = features.subList(0, numFeatures);

    // Load constraints

    ArrayList constraintsList = new ArrayList();
    if (unlabeled != null && features != null) {
        HashMap<Integer, double[][]> constraints = loadGEConstraints(featuresSubSet, train);

        // Set OneLabelKL constraints OneLabelKLGEConstraints 
        OneLabelKLGEConstraints geConstraints = new OneLabelKLGEConstraints();
        for (int fi : constraints.keySet()) {
            double[][] dist = constraints.get(fi);

            boolean allSame = true;
            double sum = 0;

            double[] prob = new double[dist.length];
            for (int li = 0; li < dist.length; li++) {
                prob[li] = dist[li][0];/* w  ww. j  a  v  a 2 s  . c o m*/
                if (!Maths.almostEquals(dist[li][0], dist[li][1])) {
                    allSame = false;
                    break;
                } else if (Double.isInfinite(prob[li])) {
                    prob[li] = 0;
                }
                sum += prob[li];
            }

            if (!allSame) {
                throw new RuntimeException("A KL divergence penalty cannot be used with target ranges!");
            }
            if (!Maths.almostEquals(sum, 1)) {
                throw new RuntimeException("Targets must sum to 1 when using a KL divergence penalty!");
            }

            geConstraints.addConstraint(fi, prob, 1);
        }
        constraintsList.add(geConstraints);
    }

    // Set label map
    StateLabelMap map = new StateLabelMap(train.getTargetAlphabet(), true);

    CRF crf = getCRF();

    // Optimazable gradients
    /*
     * Optimizable.ByGradientValue[] opts; if (unlabeled != null && features
     * != null) { opts = new Optimizable.ByGradientValue[]{ new
     * CRFOptimizableByGE(crf, constraintsList, unlabeled, map, 8), new
     * CRFOptimizableByLabelLikelihood(crf, train),}; } else { opts = new
     * Optimizable.ByGradientValue[]{ //new CRFOptimizableByGE(crf,
     * constraintsList, unlabeled, map, numThreads, 1.0), new
     * CRFOptimizableByLabelLikelihood(crf, train) }; }
     */

    //        logger.info("TOTAL SIZE OF ALPHABET AFTER FEATURE SELECTION): {}", train.getDataAlphabet().size());

    // Train

    if (unlabeled != null && features != null) {
        //CRFTrainerByValueGradients crfTrainer = new CRFTrainerByValueGradients(crf, opts);
        //crfTrainer.train(train, iterations);

        MyCRFTrainerByLikelihoodAndGE2 crfTrainer = new MyCRFTrainerByLikelihoodAndGE2(crf, constraintsList,
                map);
        crfTrainer.setNumThreads(8);
        crfTrainer.setGEWeight(ge);
        crfTrainer.setGaussianPriorVariance(gvp);
        crfTrainer.setInitSupervised(true);
        crfTrainer.train(train, unlabeled, iterations);

        //this.supervisedCRF = crfTrainer.getSupervisedCRF();

        // Set CRF
        setCRF(crf);
        return crfTrainer.getIteration() - 1;

    } else {
        CRFTrainerByThreadedLabelLikelihood crfTrainer = new CRFTrainerByThreadedLabelLikelihood(crf, 8);
        crfTrainer.train(train, iterations);
        crfTrainer.shutdown();

        // Set CRF
        setCRF(crf);
        return crfTrainer.getIteration() - 1;
    }

}

From source file:org.apache.vxquery.runtime.functions.cast.CastToStringOperation.java

@Override
public void convertDouble(DoublePointable doublep, DataOutput dOut) throws SystemException, IOException {
    abvsInner.reset();/*from   www.  jav a 2 s.c om*/
    double value = doublep.getDouble();

    if (Double.isInfinite(value)) {
        if (value == Double.NEGATIVE_INFINITY) {
            FunctionHelper.writeCharSequence("-", dOutInner);
        }
        FunctionHelper.writeCharSequence("INF", dOutInner);
        sendStringDataOutput(dOut);
    } else if (Double.isNaN(value)) {
        FunctionHelper.writeCharSequence("NaN", dOutInner);
        sendStringDataOutput(dOut);
    } else if (value == -0.0 || value == 0.0) {
        long bits = Double.doubleToLongBits(value);
        boolean negative = ((bits >> 63) == 0) ? false : true;

        if (negative) {
            FunctionHelper.writeChar('-', dOutInner);
        }
        FunctionHelper.writeCharSequence("0", dOutInner);
        sendStringDataOutput(dOut);
    } else if (Math.abs(value) >= 0.000001 && Math.abs(value) <= 10000000) {
        //the jdk (toString function) does not output number in desired format when 
        //a number is between one and ten million, so we take care of this 
        //case separately here.
        CastToDecimalOperation castToDecimal = new CastToDecimalOperation();
        castToDecimal.convertDouble(doublep, dOutInner);
        XSDecimalPointable decp = (XSDecimalPointable) XSDecimalPointable.FACTORY.createPointable();
        decp.set(abvsInner.getByteArray(), abvsInner.getStartOffset() + 1,
                XSDecimalPointable.TYPE_TRAITS.getFixedLength());
        if (Math.abs(value) <= 1000000) {
            convertDecimal(decp, dOut);
        } else {
            decimalToScientificNotn(decp, dOut);
        }
    } else {
        dOut.write(returnTag);
        dOut.writeUTF(Double.toString(value));
    }
}

From source file:broadwick.stochastic.StochasticSimulator.java

/**
 * Perform an event by informing the subscribed observers and the amountManager.
 * @param event event to be performed./* ww w.j  a v a2  s .co  m*/
 * @param t        time at which the firing occurs.
 * @param n     the number of times mu is to be fired.
 */
protected final void doEvent(final SimulationEvent event, final double t, final int n) {
    log.trace("Performing event {}", event);
    for (Observer observer : observers) {
        observer.observeEvent(event, t, n);
    }
    // change the amount of the reactants
    if (!Double.isInfinite(t)) {
        amountManager.performEvent(event, n);
    }
}

From source file:cc.redberry.core.number.Numeric.java

/**
 * @return {@code Double.isInfinite(value)}
 * @see Double#isInfinite(double)//from w  w w  .j ava 2  s  .co m
 */
@Override
public boolean isInfinite() {
    return Double.isInfinite(value);
}

From source file:org.easyrec.plugin.pearson.impl.PearsonServiceImpl.java

private void calculateWeights(final Integer tenantId, final Integer actionTypeId, final Integer itemTypeId,
        final List<User> users, final Map<Integer, Double> averageRatings) {
    final int userCount = users.size();

    final int perc25 = (int) (userCount * 0.25);
    final int perc50 = (int) (userCount * 0.5);
    final int perc75 = (int) (userCount * 0.75);

    for (int i = 0; i < userCount; i++) {
        final User activeUser = users.get(i);
        final double averageActive = averageRatings.get(activeUser.getUser());

        if (logger.isInfoEnabled()) {
            if (i == perc25)
                logger.info("Weight calculation at 25%");
            if (i == perc50)
                logger.info("Weight calculation at 50%");
            if (i == perc75)
                logger.info("Weight calculation at 75%");

            if (i % 10 == 0)
                logger.info(String.format("Weight calculation at user %d of %d", i, userCount));
        }//  w  w  w. j  ava2s  .c  om

        for (int j = i + 1; j < userCount; j++) {
            final User otherUser = users.get(j);
            final List<RatedTogether<Integer, Integer>> ratedTogether = latestActionDao
                    .getItemsRatedTogetherByUsers(tenantId, itemTypeId, activeUser.getUser(),
                            otherUser.getUser(), actionTypeId);

            // users don't have common rated items
            if (ratedTogether.size() == 0)
                continue;

            final double averageOther = averageRatings.get(otherUser.getUser());
            double frequency = 1.0;

            if (settings.isUseInverseUserFrequency()) {
                frequency = userCount / ratedTogether.size();
                frequency = Math.log10(frequency);

                if (frequency == 0.0)
                    continue;
            }

            double frequencySum = 0.0;
            double expectedBoth = 0.0;
            double expectedActive = 0.0;
            double expectedOther = 0.0;
            double expectedActiveSquare = 0.0;
            double expectedOtherSquare = 0.0;

            for (final RatedTogether<Integer, Integer> rating : ratedTogether) {
                final double ratingActive = rating.getRating1().getRatingValue();
                final double ratingOther = rating.getRating2().getRatingValue();

                frequencySum += frequency;
                expectedBoth += frequency * ratingActive * ratingOther;
                expectedActive += frequency * ratingActive;
                expectedOther += frequency * ratingOther;
                expectedActiveSquare += frequency * Math.pow(ratingActive, 2.0);
                expectedOtherSquare += frequency * Math.pow(ratingOther, 2.0);
            }

            // TODO replace EX^2 - (EX)^2 with E((X-EX)^2) for better stability
            final double varianceActive = frequencySum * expectedActiveSquare - Math.pow(expectedActive, 2.0);
            final double varianceOther = frequencySum * expectedOtherSquare - Math.pow(expectedOther, 2.0);

            double numerator1 = frequencySum * expectedBoth;
            double numerator2 = expectedActive * expectedOther;
            final double denominator = Math.sqrt(varianceActive * varianceOther);

            numerator1 /= denominator;
            numerator2 /= denominator;

            final double weight = numerator1 - numerator2;

            if (Double.isNaN(weight) || Double.isInfinite(weight)) {
                if (logger.isWarnEnabled())
                    logger.warn(String.format(
                            "Weight is %s for users %d and %d (vAct=%.2f, vOth=%.2f, Eact2=%.2f, Eoth2=%.2f, "
                                    + "Ebot=%.2f, Eact=%.2f, Eoth=%.2f, fre=%.2f fsum=%.2f, num1=%.2f, "
                                    + "numer2=%.2f, den=%.2f)",
                            Double.isNaN(weight) ? "NaN" : "Inf", i, j, varianceActive, varianceOther,
                            expectedActiveSquare, expectedOtherSquare, expectedBoth, expectedActive,
                            expectedOther, frequency, frequencySum, numerator1, numerator2, denominator));

                continue;
            }

            final Weight weightObj = new Weight(activeUser, otherUser, weight);

            weightDao.insertOrUpdateWeightSymmetric(weightObj);
        }
    }
}