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:com.bc.jexp.impl.DefaultNamespace.java

private void registerDefaultFunctions() {
    registerFunction(new AbstractFunction.D("sin", 1) {

        public double evalD(final EvalEnv env, final Term[] args) {
            return FastMath.sin(args[0].evalD(env));
        }//from w  w  w.ja  v a  2 s  . c om
    });
    registerFunction(new AbstractFunction.D("cos", 1) {

        public double evalD(final EvalEnv env, final Term[] args) {
            return FastMath.cos(args[0].evalD(env));
        }
    });
    registerFunction(new AbstractFunction.D("tan", 1) {

        public double evalD(final EvalEnv env, final Term[] args) {
            return FastMath.tan(args[0].evalD(env));
        }
    });
    registerFunction(new AbstractFunction.D("asin", 1) {

        public double evalD(final EvalEnv env, final Term[] args) {
            return FastMath.asin(args[0].evalD(env));
        }
    });
    registerFunction(new AbstractFunction.D("acos", 1) {

        public double evalD(final EvalEnv env, final Term[] args) {
            return FastMath.acos(args[0].evalD(env));
        }
    });
    registerFunction(new AbstractFunction.D("atan", 1) {

        public double evalD(final EvalEnv env, final Term[] args) {
            return FastMath.atan(args[0].evalD(env));
        }
    });
    registerFunction(new AbstractFunction.D("atan2", 2) {

        public double evalD(final EvalEnv env, final Term[] args) {
            return Math.atan2(args[0].evalD(env), args[1].evalD(env));
        }
    });
    registerFunction(new AbstractFunction.D("log", 1) {

        public double evalD(final EvalEnv env, final Term[] args) {
            return Math.log(args[0].evalD(env));
        }
    });

    registerFunction(new AbstractFunction.D("log10", 1) {
        public double evalD(EvalEnv env, Term[] args) throws EvalException {
            return Math.log10(args[0].evalD(env));
        }
    });

    registerFunction(new AbstractFunction.D("exp", 1) {

        public double evalD(final EvalEnv env, final Term[] args) {
            return FastMath.exp(args[0].evalD(env));
        }
    });

    registerFunction(new AbstractFunction.D("exp10", 1) {

        public double evalD(EvalEnv env, Term[] args) throws EvalException {
            return FastMath.pow(10.0, args[0].evalD(env));
        }
    });

    registerFunction(new AbstractFunction.D("sqr", 1) {

        public double evalD(final EvalEnv env, final Term[] args) {
            double v = args[0].evalD(env);
            return v * v;
        }
    });

    registerFunction(new AbstractFunction.D("sqrt", 1) {

        public double evalD(final EvalEnv env, final Term[] args) {
            return Math.sqrt(args[0].evalD(env));
        }
    });

    registerFunction(new AbstractFunction.D("pow", 2) {

        public double evalD(final EvalEnv env, final Term[] args) {
            return FastMath.pow(args[0].evalD(env), args[1].evalD(env));
        }
    });

    registerFunction(new AbstractFunction.I("min", 2) {

        public int evalI(final EvalEnv env, final Term[] args) {
            return Math.min(args[0].evalI(env), args[1].evalI(env));
        }
    });

    registerFunction(new AbstractFunction.D("min", 2) {

        public double evalD(final EvalEnv env, final Term[] args) {
            return Math.min(args[0].evalD(env), args[1].evalD(env));
        }
    });

    registerFunction(new AbstractFunction.I("max", 2) {

        public int evalI(final EvalEnv env, final Term[] args) {
            return Math.max(args[0].evalI(env), args[1].evalI(env));
        }
    });

    registerFunction(new AbstractFunction.D("max", 2) {

        public double evalD(final EvalEnv env, final Term[] args) {
            return Math.max(args[0].evalD(env), args[1].evalD(env));
        }
    });

    registerFunction(new AbstractFunction.D("floor", 1) {
        public double evalD(EvalEnv env, Term[] args) throws EvalException {
            return Math.floor(args[0].evalD(env));
        }
    });

    registerFunction(new AbstractFunction.D("round", 1) {
        public double evalD(EvalEnv env, Term[] args) throws EvalException {
            return Math.round(args[0].evalD(env));
        }
    });

    registerFunction(new AbstractFunction.D("ceil", 1) {
        public double evalD(EvalEnv env, Term[] args) throws EvalException {
            return Math.ceil(args[0].evalD(env));
        }
    });

    registerFunction(new AbstractFunction.D("rint", 1) {
        public double evalD(EvalEnv env, Term[] args) throws EvalException {
            return Math.rint(args[0].evalD(env));
        }
    });

    registerFunction(new AbstractFunction.I("sign", 1) {

        public int evalI(final EvalEnv env, final Term[] args) {
            return ExtMath.sign(args[0].evalI(env));
        }
    });

    registerFunction(new AbstractFunction.D("sign", 1) {

        public double evalD(final EvalEnv env, final Term[] args) {
            return ExtMath.sign(args[0].evalD(env));
        }
    });

    registerFunction(new AbstractFunction.I("abs", 1) {

        public int evalI(final EvalEnv env, final Term[] args) {
            return Math.abs(args[0].evalI(env));
        }
    });

    registerFunction(new AbstractFunction.D("abs", 1) {

        public double evalD(final EvalEnv env, final Term[] args) {
            return Math.abs(args[0].evalD(env));
        }
    });

    registerFunction(new AbstractFunction.D("deg", 1) {

        public double evalD(final EvalEnv env, final Term[] args) {
            return Math.toDegrees(args[0].evalD(env));
        }
    });

    registerFunction(new AbstractFunction.D("rad", 1) {

        public double evalD(final EvalEnv env, final Term[] args) {
            return Math.toRadians(args[0].evalD(env));
        }
    });

    registerFunction(new AbstractFunction.D("ampl", 2) {

        public double evalD(final EvalEnv env, final Term[] args) {
            final double a = args[0].evalD(env);
            final double b = args[1].evalD(env);
            return Math.sqrt(a * a + b * b);
        }
    });

    registerFunction(new AbstractFunction.D("phase", 2) {

        public double evalD(final EvalEnv env, final Term[] args) {
            final double a = args[0].evalD(env);
            final double b = args[1].evalD(env);
            return Math.atan2(b, a);
        }
    });

    registerFunction(new AbstractFunction.B("feq", 2) {
        public boolean evalB(EvalEnv env, Term[] args) throws EvalException {
            final double x1 = args[0].evalD(env);
            final double x2 = args[1].evalD(env);
            return ExtMath.feq(x1, x2, EPS);
        }
    });

    registerFunction(new AbstractFunction.B("feq", 3) {
        public boolean evalB(EvalEnv env, Term[] args) throws EvalException {
            final double x1 = args[0].evalD(env);
            final double x2 = args[1].evalD(env);
            final double eps = args[2].evalD(env);
            return ExtMath.feq(x1, x2, eps);
        }
    });

    registerFunction(new AbstractFunction.B("fneq", 2) {
        public boolean evalB(EvalEnv env, Term[] args) throws EvalException {
            final double x1 = args[0].evalD(env);
            final double x2 = args[1].evalD(env);
            return ExtMath.fneq(x1, x2, EPS);
        }
    });

    registerFunction(new AbstractFunction.B("fneq", 3) {
        public boolean evalB(EvalEnv env, Term[] args) throws EvalException {
            final double x1 = args[0].evalD(env);
            final double x2 = args[1].evalD(env);
            final double eps = args[2].evalD(env);
            return ExtMath.fneq(x1, x2, eps);
        }
    });

    registerFunction(new AbstractFunction.B("inf", 1) {
        public boolean evalB(EvalEnv env, Term[] args) throws EvalException {
            return Double.isInfinite(args[0].evalD(env));
        }
    });

    registerFunction(new AbstractFunction.B("nan", 1) {
        public boolean evalB(EvalEnv env, Term[] args) throws EvalException {
            return Double.isNaN(args[0].evalD(env));
        }
    });

    registerFunction(new AbstractFunction.D("distance", -1) {

        public double evalD(final EvalEnv env, final Term[] args) {
            double sqrSum = 0.0;
            final int n = args.length / 2;
            for (int i = 0; i < n; i++) {
                final double v = args[i + n].evalD(env) - args[i].evalD(env);
                sqrSum += v * v;
            }
            return Math.sqrt(sqrSum);
        }
    });

    registerFunction(new AbstractFunction.D("distance_deriv", -1) {

        public double evalD(final EvalEnv env, final Term[] args) {
            double sqrSum = 0.0;
            final int n = args.length / 2;
            for (int i = 0; i < n - 1; i++) {
                final double v1 = args[i + 1].evalD(env) - args[i].evalD(env);
                final double v2 = args[i + n + 1].evalD(env) - args[i + n].evalD(env);
                sqrSum += (v1 - v2) * (v1 - v2);
            }
            return Math.sqrt(sqrSum);
        }
    });

    registerFunction(new AbstractFunction.D("distance_integ", -1) {

        public double evalD(final EvalEnv env, final Term[] args) {
            double sqrSum = 0.0;
            double v1Sum = 0.0;
            double v2Sum = 0.0;
            final int n = args.length / 2;
            for (int i = 0; i < n; i++) {
                v1Sum += args[i].evalD(env);
                v2Sum += args[i + n].evalD(env);
                sqrSum += (v2Sum - v1Sum) * (v2Sum - v1Sum);
            }
            return Math.sqrt(sqrSum);
        }
    });

    registerFunction(new AbstractFunction.B("inrange", -1) {

        public boolean evalB(final EvalEnv env, final Term[] args) {
            final int n1 = args.length / 3;
            final int n2 = n1 + args.length / 3;
            for (int i = 0; i < n1; i++) {
                final double v = args[i].evalD(env);
                final double v1 = args[i + n1].evalD(env);
                final double v2 = args[i + n2].evalD(env);
                if (v < v1 || v > v2) {
                    return false;
                }
            }
            return true;
        }
    });

    registerFunction(new AbstractFunction.B("inrange_deriv", -1) {

        public boolean evalB(final EvalEnv env, final Term[] args) {
            final int n1 = args.length / 3;
            final int n2 = 2 * n1;
            for (int i = 0; i < n1 - 1; i++) {
                final double v = args[i + 1].evalD(env) - args[i].evalD(env);
                final double v1 = args[i + n1 + 1].evalD(env) - args[i + n1].evalD(env);
                final double v2 = args[i + n2 + 1].evalD(env) - args[i + n2].evalD(env);
                if (v < v1 || v > v2) {
                    return false;
                }
            }
            return true;
        }
    });

    registerFunction(new AbstractFunction.B("inrange_integ", -1) {

        public boolean evalB(final EvalEnv env, final Term[] args) {
            final int n1 = args.length / 3;
            final int n2 = 2 * n1;
            double vSum = 0.0;
            double v1Sum = 0.0;
            double v2Sum = 0.0;
            for (int i = 0; i < n1; i++) {
                vSum += args[i].evalD(env);
                v1Sum += args[i + n1].evalD(env);
                v2Sum += args[i + n2].evalD(env);
                if (vSum < v1Sum || vSum > v2Sum) {
                    return false;
                }
            }
            return true;
        }
    });

}

From source file:daylightchart.daylightchart.calculation.RiseSetUtility.java

@SuppressWarnings("boxing")
private static RawRiseSet calculateRiseSet(final Location location, final LocalDate date,
        final boolean useDaylightTime, final boolean inDaylightSavings, final TwilightType twilight) {
    if (location != null) {
        sunAlgorithm.setLocation(location.getDescription(),
                location.getPointLocation().getLatitude().getDegrees(),
                location.getPointLocation().getLongitude().getDegrees());
        sunAlgorithm/*from www.  ja  v a2 s.  c  om*/
                .setTimeZoneOffset(DefaultTimezones.getStandardTimeZoneOffsetHours(location.getTimeZoneId()));
    }
    sunAlgorithm.setDate(date.getYear(), date.getMonthValue(), date.getDayOfMonth());
    final double[] sunriseSunset = sunAlgorithm.calcRiseSet(twilight.getHorizon());

    if (useDaylightTime && inDaylightSavings) {
        if (!Double.isInfinite(sunriseSunset[0])) {
            sunriseSunset[0] = sunriseSunset[0] + 1;
        }
        if (!Double.isInfinite(sunriseSunset[1])) {
            sunriseSunset[1] = sunriseSunset[1] + 1;
        }
    }

    final RawRiseSet riseSet = new RawRiseSet(location, date, useDaylightTime && inDaylightSavings,
            sunriseSunset[0], sunriseSunset[1]);
    return riseSet;

}

From source file:jsat.distributions.empirical.MyKernelDensityEstimator.java

/**
 * Sets the bandwidth used for smoothing. Higher values make the pdf smoother, but can obscure features. Too small a bandwidth will causes spikes at only
 * the data points.//from ww w.j a  va  2  s  . c o  m
 * 
 * @param val
 *            new bandwidth
 */
public void setBandwith(double val) {
    if (val <= 0 || Double.isInfinite(val)) {
        throw new ArithmeticException("Bandwith parameter h must be greater than zero, not " + 0);
    }

    this.h = val;
}

From source file:com.rapidminer.gui.plotter.charts.MultipleScatterPlotter.java

private void prepareData() {
    idMap.clear();/*from   w w w  .j a  v  a  2 s.  c  om*/
    this.plotIndexToColumnIndexMap.clear();
    dataSet = new DefaultXYDataset();

    if (xAxis >= 0) {
        Map<String, List<double[]>> dataCollection = new LinkedHashMap<String, List<double[]>>();
        Map<String, List<String>> idCollection = new LinkedHashMap<String, List<String>>();

        synchronized (dataTable) {
            for (int column = 0; column < plotColumns.length; column++) {
                if (plotColumns[column]) {
                    plotIndexToColumnIndexMap.add(column);
                    String columnName = this.dataTable.getColumnName(column);
                    Iterator<DataTableRow> i = this.dataTable.iterator();
                    int index = 0;
                    while (i.hasNext()) {
                        DataTableRow row = i.next();

                        double xValue = row.getValue(xAxis);
                        double yValue = row.getValue(column);

                        if (!Double.isNaN(xValue) && !Double.isNaN(yValue)) {
                            addPoint(dataCollection, idCollection, row.getId(), xValue, yValue, columnName);
                        }
                        index++;
                    }
                }
            }
        }

        double minX = Double.POSITIVE_INFINITY;
        double maxX = Double.NEGATIVE_INFINITY;
        double minY = Double.POSITIVE_INFINITY;
        double maxY = Double.NEGATIVE_INFINITY;

        Iterator<Map.Entry<String, List<double[]>>> i = dataCollection.entrySet().iterator();
        while (i.hasNext()) {
            Map.Entry<String, List<double[]>> entry = i.next();
            List<double[]> dataList = entry.getValue();
            Iterator<double[]> j = dataList.iterator();
            while (j.hasNext()) {
                double[] current = j.next();
                minX = Math.min(minX, current[0]);
                maxX = Math.max(maxX, current[0]);
                minY = Math.min(minY, current[1]);
                maxY = Math.max(maxY, current[1]);
            }
        }

        Random jitterRandom = new Random(2001);
        double oldXRange = maxX - minX;
        double oldYRange = maxY - minY;

        if (Double.isInfinite(oldXRange) || Double.isNaN(oldXRange)) {
            oldXRange = 0;
        }
        if (Double.isInfinite(oldYRange) || Double.isNaN(oldYRange)) {
            oldYRange = 0;
        }

        i = dataCollection.entrySet().iterator();
        while (i.hasNext()) {
            Map.Entry<String, List<double[]>> entry = i.next();
            String seriesName = entry.getKey();
            List<double[]> dataList = entry.getValue();

            double[][] data = new double[2][dataList.size()];
            int listCounter = 0;
            Iterator<double[]> j = dataList.iterator();
            while (j.hasNext()) {
                double[] current = j.next();
                data[0][listCounter] = current[0];
                data[1][listCounter] = current[1];

                if (this.jitterAmount > 0) {
                    double pertX = oldXRange * (jitterAmount / 200.0d) * jitterRandom.nextGaussian();
                    double pertY = oldYRange * (jitterAmount / 200.0d) * jitterRandom.nextGaussian();
                    data[0][listCounter] += pertX;
                    data[1][listCounter] += pertY;
                }

                listCounter++;
            }
            ((DefaultXYDataset) dataSet).addSeries(seriesName, data);
        }

        int seriesCounter = 0;
        Iterator<List<String>> v = idCollection.values().iterator();
        while (v.hasNext()) {
            List<String> idList = v.next();
            int itemCounter = 0;
            Iterator<String> j = idList.iterator();
            while (j.hasNext()) {
                idMap.put(new SeriesAndItem(seriesCounter, itemCounter++), j.next());
            }
            seriesCounter++;
        }
    }
}

From source file:beast.evolution.tree.SimpleRandomTree.java

public void doTheWork() {
    // find taxon sets we are dealing with
    taxonSets = new ArrayList<>();
    m_bounds = new ArrayList<>();
    distributions = new ArrayList<>();
    taxonSetIDs = new ArrayList<>();
    List<Boolean> onParent = new ArrayList<>();
    lastMonophyletic = 0;/*from   w w  w .  j  a v  a 2 s.  c om*/

    if (taxaInput.get() != null) {
        sTaxa.addAll(taxaInput.get().getTaxaNames());
    } else {
        sTaxa.addAll(m_taxonset.get().asStringList());
    }

    // pick up constraints from outputs, m_inititial input tree and output tree, if any
    List<MRCAPrior> calibrations = new ArrayList<MRCAPrior>();
    calibrations.addAll(calibrationsInput.get());

    // pick up constraints in m_initial tree
    for (final Object plugin : getOutputs()) {
        if (plugin instanceof MRCAPrior && !calibrations.contains(plugin)) {
            calibrations.add((MRCAPrior) plugin);
        }
    }

    if (m_initial.get() != null) {
        for (final Object plugin : m_initial.get().getOutputs()) {
            if (plugin instanceof MRCAPrior && !calibrations.contains(plugin)) {
                calibrations.add((MRCAPrior) plugin);
            }
        }
    }

    for (final MRCAPrior prior : calibrations) {
        final TaxonSet taxonSet = prior.taxonsetInput.get();
        if (taxonSet != null && !prior.onlyUseTipsInput.get()) {
            final Set<String> bTaxa = new LinkedHashSet<>();
            if (taxonSet.asStringList() == null) {
                taxonSet.initAndValidate();
            }
            for (final String sTaxonID : taxonSet.asStringList()) {

                if (!sTaxa.contains(sTaxonID)) {
                    throw new IllegalArgumentException(
                            "Taxon <" + sTaxonID + "> could not be found in list of taxa. Choose one of "
                                    + Arrays.toString(sTaxa.toArray(new String[sTaxa.size()])));
                }
                bTaxa.add(sTaxonID);
            }
            final ParametricDistribution distr = prior.distInput.get();
            final Bound bounds = new Bound();
            if (distr != null) {
                List<BEASTInterface> plugins = new ArrayList<>();
                distr.getPredecessors(plugins);
                for (int i = plugins.size() - 1; i >= 0; i--) {
                    plugins.get(i).initAndValidate();
                }
                try {
                    final double offset = distr.offsetInput.get();
                    bounds.lower = Math.max(distr.inverseCumulativeProbability(0.0) + offset, 0.0);
                    bounds.upper = distr.inverseCumulativeProbability(1.0) + offset;
                    assert bounds.lower <= bounds.upper;
                } catch (MathException e) {
                    Log.warning
                            .println("Could not set bounds in SimpleRandomTree::doTheWork : " + e.getMessage());
                }
            }

            if (prior.isMonophyleticInput.get() || bTaxa.size() == 1) {
                // add any monophyletic constraint
                boolean isDuplicate = false;
                for (int k = 0; k < lastMonophyletic; ++k) {
                    // assert prior.useOriginateInput.get().equals(onParent.get(k)) == (prior.useOriginateInput.get() == onParent.get(k));
                    if (bTaxa.size() == taxonSets.get(k).size() && bTaxa.equals(taxonSets.get(k))
                            && prior.useOriginateInput.get().equals(onParent.get(k))) {
                        if (distr != null) {
                            if (distributions.get(k) == null) {
                                distributions.set(k, distr);
                                m_bounds.set(k, bounds);
                                taxonSetIDs.set(k, prior.getID());
                            }
                        }
                        isDuplicate = true;
                    }
                }
                if (!isDuplicate) {
                    taxonSets.add(lastMonophyletic, bTaxa);
                    distributions.add(lastMonophyletic, distr);
                    onParent.add(lastMonophyletic, prior.useOriginateInput.get());
                    m_bounds.add(lastMonophyletic, bounds);
                    taxonSetIDs.add(lastMonophyletic, prior.getID());
                    lastMonophyletic++;
                }
            } else {
                // only calibrations with finite bounds are added
                if (!Double.isInfinite(bounds.lower) || !Double.isInfinite(bounds.upper)) {
                    taxonSets.add(bTaxa);
                    distributions.add(distr);
                    m_bounds.add(bounds);
                    taxonSetIDs.add(prior.getID());
                    onParent.add(prior.useOriginateInput.get());
                }
            }
        }
    }

    if (ICC) {
        for (int i = 0; i < lastMonophyletic; i++) {
            final Set<String> ti = taxonSets.get(i);
            for (int j = i + 1; j < lastMonophyletic; j++) {
                final Set<String> tj = taxonSets.get(j);
                boolean i_in_j = tj.containsAll(ti);
                boolean j_in_i = ti.containsAll(tj);
                if (i_in_j || j_in_i) {
                    boolean ok = true;
                    if (i_in_j && j_in_i) {
                        ok = (boolean) (onParent.get(i)) != (boolean) onParent.get(j);
                    }
                    assert ok : "" + i + ' ' + j + ' ' + ' ' + taxonSetIDs.get(i) + ' ' + taxonSetIDs.get(j);
                } else {
                    Set<String> tmp = new HashSet<>(tj);
                    tmp.retainAll(ti);
                    assert tmp.isEmpty();
                }
            }
        }
    }

    // assume all calibration constraints are Monophyletic
    // TODO: verify that this is a reasonable assumption
    lastMonophyletic = taxonSets.size();

    // sort constraints in increasing set inclusion order, i.e. such that if taxon set i is subset of taxon set j, then i < j
    for (int i = 0; i < lastMonophyletic; i++) {
        for (int j = i + 1; j < lastMonophyletic; j++) {

            final Set<String> taxai = taxonSets.get(i);
            final Set<String> taxaj = taxonSets.get(j);
            Set<String> intersection = new LinkedHashSet<>(taxai);
            intersection.retainAll(taxaj);

            if (intersection.size() > 0) {
                final boolean bIsSubset = taxai.containsAll(taxaj);
                final boolean bIsSubset2 = taxaj.containsAll(taxai);
                // sanity check: make sure either
                // o taxonset1 is subset of taxonset2 OR
                // o taxonset1 is superset of taxonset2 OR
                // o taxonset1 does not intersect taxonset2
                if (!(bIsSubset || bIsSubset2)) {
                    throw new IllegalArgumentException(
                            "333: Don't know how to generate a Random Tree for taxon sets that intersect, "
                                    + "but are not inclusive. Taxonset "
                                    + (taxonSetIDs.get(i) == null ? taxai : taxonSetIDs.get(i)) + " and "
                                    + (taxonSetIDs.get(j) == null ? taxaj : taxonSetIDs.get(j)));
                }
                // swap i & j if b1 subset of b2. If equal sub-sort on 'useOriginate'
                if (bIsSubset && (!bIsSubset2 || (onParent.get(i) && !onParent.get(j)))) {
                    swap(taxonSets, i, j);
                    swap(distributions, i, j);
                    swap(m_bounds, i, j);
                    swap(taxonSetIDs, i, j);
                    swap(onParent, i, j);
                }
            }
        }
    }

    if (ICC) {
        for (int i = 0; i < lastMonophyletic; i++) {
            final Set<String> ti = taxonSets.get(i);
            for (int j = i + 1; j < lastMonophyletic; j++) {
                final Set<String> tj = taxonSets.get(j);
                boolean ok = tj.containsAll(ti);
                if (ok) {
                    ok = !tj.equals(ti) || (!onParent.get(i) && onParent.get(j));
                    assert ok : "" + i + ' ' + j + ' ' + tj.equals(ti) + ' ' + taxonSetIDs.get(i) + ' '
                            + taxonSetIDs.get(j);
                } else {
                    Set<String> tmp = new HashSet<>(tj);
                    tmp.retainAll(ti);
                    assert tmp.isEmpty();
                }
            }
        }
    }

    for (int i = 0; i < lastMonophyletic; i++) {
        if (onParent.get(i)) {
            // make sure it is after constraint on node itself, if such exists
            assert (!(i + 1 < lastMonophyletic && taxonSets.get(i).equals(taxonSets.get(i + 1))
                    && onParent.get(i) && !onParent.get(i + 1)));
            // find something to attach to ....
            // find enclosing clade, if any. pick a non-intersecting clade in the enclosed without an onParent constraint, or one whose
            // onParent constraint is overlapping.
            final Set<String> iTaxa = taxonSets.get(i);
            int j = i + 1;
            Set<String> enclosingTaxa = sTaxa;
            {
                String someTaxon = iTaxa.iterator().next();
                for (/**/; j < lastMonophyletic; j++) {
                    if (taxonSets.get(j).contains(someTaxon)) {
                        enclosingTaxa = taxonSets.get(j);
                        break;
                    }
                }
            }
            final int enclosingIndex = (j == lastMonophyletic) ? j : j;
            Set<String> candidates = new HashSet<>(enclosingTaxa);
            candidates.removeAll(iTaxa);
            Set<Integer> candidateClades = new HashSet<>(5);
            List<String> canTaxa = new ArrayList<>();
            for (String c : candidates) {
                for (int k = enclosingIndex - 1; k >= 0; --k) {
                    if (taxonSets.get(k).contains(c)) {
                        if (!candidateClades.contains(k)) {
                            if (onParent.get(k)) {
                                if (!intersecting(m_bounds.get(k), m_bounds.get(i))) {
                                    break;
                                }
                            } else {
                                if (!(m_bounds.get(k).lower <= m_bounds.get(i).lower)) {
                                    break;
                                }
                            }
                            candidateClades.add(k);
                        }
                        break;
                    }
                    if (k == 0) {
                        canTaxa.add(c);
                    }
                }
            }

            final int sz1 = canTaxa.size();
            final int sz2 = candidateClades.size();

            if (sz1 + sz2 == 0 && i + 1 == enclosingIndex) {
                final Bound ebound = m_bounds.get(enclosingIndex);
                ebound.restrict(m_bounds.get(i));
            } else {
                assert sz1 + sz2 > 0;
                // prefer taxa over clades (less chance of clades useOriginate clashing)
                final int k = Randomizer.nextInt(sz1 > 0 ? sz1 : sz2);
                Set<String> connectTo;
                int insertPoint;
                if (k < sz1) {
                    // from taxa
                    connectTo = new HashSet<>(1);
                    connectTo.add(canTaxa.get(k));
                    insertPoint = i + 1;
                } else {
                    // from clade
                    final Iterator<Integer> it = candidateClades.iterator();
                    for (j = 0; j < k - sz1 - 1; ++j) {
                        it.next();
                    }
                    insertPoint = it.next();
                    connectTo = new HashSet<>(taxonSets.get(insertPoint));
                    insertPoint = Math.max(insertPoint, i) + 1;
                }

                final HashSet<String> cc = new HashSet<String>(connectTo);

                connectTo.addAll(taxonSets.get(i));
                if (!connectTo.equals(enclosingTaxa) || enclosingTaxa == sTaxa) { // equal when clade already exists

                    taxonSets.add(insertPoint, connectTo);
                    distributions.add(insertPoint, distributions.get(i));
                    onParent.add(insertPoint, false);
                    m_bounds.add(insertPoint, m_bounds.get(i));
                    final String tid = taxonSetIDs.get(i);
                    taxonSetIDs.add(insertPoint, tid);
                    lastMonophyletic += 1;
                } else {
                    // we lose distribution i :(
                    final Bound ebound = m_bounds.get(enclosingIndex);
                    ebound.restrict(m_bounds.get(i));
                }
            }
            if (true) {
                taxonSets.set(i, new HashSet<>());
                distributions.set(i, null);
                m_bounds.set(i, new Bound());
                final String tid = taxonSetIDs.get(i);
                if (tid != null) {
                    taxonSetIDs.set(i, "was-" + tid);
                }
            }
        }
    }

    {
        int icur = 0;
        for (int i = 0; i < lastMonophyletic; ++i, ++icur) {
            final Set<String> ti = taxonSets.get(i);
            if (ti.isEmpty()) {
                icur -= 1;
            } else {
                if (icur < i) {
                    taxonSets.set(icur, taxonSets.get(i));
                    distributions.set(icur, distributions.get(i));
                    m_bounds.set(icur, m_bounds.get(i));
                    taxonSetIDs.set(icur, taxonSetIDs.get(i));
                    onParent.set(icur, onParent.get(i));
                }
            }
        }
        taxonSets.subList(icur, lastMonophyletic).clear();
        distributions.subList(icur, lastMonophyletic).clear();
        m_bounds.subList(icur, lastMonophyletic).clear();
        taxonSetIDs.subList(icur, lastMonophyletic).clear();
        onParent.subList(icur, lastMonophyletic).clear();

        lastMonophyletic = icur;
    }

    if (ICC) {
        for (int i = 0; i < lastMonophyletic; i++) {
            final Set<String> ti = taxonSets.get(i);
            for (int j = i + 1; j < lastMonophyletic; j++) {
                final Set<String> tj = taxonSets.get(j);
                boolean ok = tj.containsAll(ti);
                if (ok) {
                    ok = !tj.equals(ti) || (!onParent.get(i) && onParent.get(j));
                    assert ok : "" + i + ' ' + j + ' ' + taxonSetIDs.get(i) + ' ' + taxonSetIDs.get(j);
                } else {
                    Set<String> tmp = new HashSet<>(tj);
                    tmp.retainAll(ti);
                    assert tmp.isEmpty();
                }
            }
        }
    }

    // map parent child relationships between mono clades. nParent[i] is the immediate parent clade of i, if any. An immediate parent is the
    // smallest superset of i, children[i] is a list of all clades which have i as a parent.
    // The last one, standing for the virtual "root" of all monophyletic clades is not associated with any actual clade
    final int[] nParent = new int[lastMonophyletic];
    children = new List[lastMonophyletic + 1];
    for (int i = 0; i < lastMonophyletic + 1; i++) {
        children[i] = new ArrayList<>();
    }
    for (int i = 0; i < lastMonophyletic; i++) {
        int j = i + 1;
        while (j < lastMonophyletic && !taxonSets.get(j).containsAll(taxonSets.get(i))) {
            j++;
        }
        nParent[i] = j;
        children[j].add(i);
    }

    // make sure upper bounds of a child does not exceed the upper bound of its parent
    for (int i = lastMonophyletic - 1; i >= 0; --i) {
        if (nParent[i] < lastMonophyletic) {
            if (m_bounds.get(i).upper > m_bounds.get(nParent[i]).upper) {
                m_bounds.get(i).upper = m_bounds.get(nParent[i]).upper - 1e-100;
                assert m_bounds.get(i).lower <= m_bounds.get(i).upper : i;
            }
        }
    }

    nodeCount = 2 * sTaxa.size() - 1;
    boundPerNode = new Bound[nodeCount];
    distPerNode = new ParametricDistribution[nodeCount];

    buildTree(sTaxa);
    assert nextNodeNr == nodeCount : "" + nextNodeNr + ' ' + nodeCount;

    double bm = branchMeanInput.get();

    if (bm < 0) {
        double maxMean = 0;

        for (ParametricDistribution distr : distPerNode) {
            if (distr != null) {
                double m = distr.getMean();
                if (maxMean < m)
                    maxMean = m;
            }
        }
        if (maxMean > 0) {
            double s = 0;
            for (int i = 2; i <= nodeCount; ++i) {
                s += 1.0 / i;
            }
            bm = s / maxMean;
        }
    }

    double rate = 1 / (bm < 0 ? 1 : bm);
    boolean succ = false;
    int ntries = 6;
    final double epsi = 0.01 / rate;
    double clamp = 1 - clampInput.get();
    while (!succ && ntries > 0) {
        try {
            succ = setHeights(rate, false, epsi, clamp);
        } catch (ConstraintViolatedException e) {
            throw new RuntimeException("Constraint failed: " + e.getMessage());
        }
        --ntries;
        rate *= 2;
        clamp /= 2;
    }
    if (!succ) {
        try {
            succ = setHeights(rate, true, 0, 0);
        } catch (ConstraintViolatedException e) {
            throw new RuntimeException("Constraint failed: " + e.getMessage());
        }
    }
    assert succ;

    internalNodeCount = sTaxa.size() - 1;
    leafNodeCount = sTaxa.size();

    HashMap<String, Integer> taxonToNR = null;
    // preserve node numbers where possible
    if (m_initial.get() != null) {
        taxonToNR = new HashMap<>();
        for (Node n : m_initial.get().getExternalNodes()) {
            taxonToNR.put(n.getID(), n.getNr());
        }
    }
    // re-assign node numbers
    setNodesNrs(root, 0, new int[1], taxonToNR);

    initArrays();
}

From source file:com.clust4j.kernel.KernelTestCases.java

@Test
public void testOther() {
    /*//from  ww w  .j av a2s .c o  m
     * hilbert space will equal 2*115 - 129 - 174 = -73
     */
    double[] a = new double[] { 10, 2, 3, 4 }; // ip = 129
    double[] b = new double[] { 5, 6, 7, 8 }; // ip = 174
    assertTrue(Kernel.toHilbertPSpace(a, b) == -73);
    Kernel c, d, e;

    /*
     * Ensure the sigma param is working for Cauchy
     */
    c = new CauchyKernel();
    d = new CauchyKernel(5.0);
    assertFalse(c.getSimilarity(a, b) == d.getSimilarity(a, b));

    /*
     * Assert circular kernel 0
     */
    c = new CircularKernel(-200.0);
    assertTrue(c.getSimilarity(a, b) == 0.0); // greater than sigma

    /*
     * Ensure alpha, beta are used in GeneralizedMinKernel
     */
    c = new GeneralizedMinKernel(-2.0, -3.0);
    d = new GeneralizedMinKernel();
    assertFalse(c.getSimilarity(a, b) == d.getSimilarity(a, b));

    /*
     * test constant on inverse multi
     */
    c = new InverseMultiquadricKernel();
    d = new InverseMultiquadricKernel(5.0);
    assertFalse(c.getSimilarity(a, b) == d.getSimilarity(a, b));

    /*
     * Test laplacian cases
     */
    c = new LaplacianKernel(2.0);
    d = new LaplacianKernel(2.0, 2.0);
    e = new LaplacianKernel(2.0, 2.0, 2.0);
    assertFalse(c.getSimilarity(a, b) == d.getSimilarity(a, b));
    assertFalse(c.getSimilarity(a, b) == e.getSimilarity(a, b));
    assertFalse(e.getSimilarity(a, b) == d.getSimilarity(a, b));

    /*
     * Test log cases
     */
    c = new LogKernel();
    d = new LogKernel(1000);
    double f = c.getSimilarity(a, b), g = d.getSimilarity(a, b);
    assertTrue((Double.isInfinite(f) && Double.isInfinite(g)) || (f != g));

    /*
     * Test polynomial cases
     */
    c = new PolynomialKernel();
    d = new PolynomialKernel(5.0, 2.0);
    assertFalse(c.getSimilarity(a, b) == d.getSimilarity(a, b));

    /*
     * Test spherical cases
     */
    c = new SphericalKernel(-200.0);
    assertTrue(c.getSimilarity(a, b) == 0.0); // greater than sigma
    d = new SphericalKernel(1000.0);
    assertFalse(c.getSimilarity(a, b) == d.getSimilarity(a, b));
}

From source file:com.gs.collections.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 .j a  v a2s. c  o  m
 *
 * @deprecated in 3.0. Use {@link Assert#assertNotEquals(String, double, double, double)} in JUnit 4.11 instead.
 */
@Deprecated
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 {
        //noinspection FloatingPointEquality
        if (Double.isInfinite(notExpected) && notExpected == actual
                || Math.abs(notExpected - actual) <= delta) {
            Assert.fail(itemName + " should not be equal:<" + notExpected + '>');
        }
    } catch (AssertionError e) {
        Verify.throwMangledException(e);
    }
}

From source file:com.github.rinde.rinsim.scenario.measure.Metrics.java

/**
 * Computes a histogram for the inputs. The result is a multiset with an entry
 * for each bin in ascending order, the count of each entry indicates the size
 * of the bin. A bin is indicated by its leftmost value, for example if the
 * <code>binSize</code> is <code>2</code> and the result contains
 * <code>4</code> with count <code>3</code> this means that there are
 * <code>3</code> values in range <code>2 &le; x &lt; 4</code>.
 * @param input The values to compute the histogram of.
 * @param binSize The size of the bins.//from  ww  w. j  av a2 s . co  m
 * @return An {@link ImmutableSortedMultiset} representing the histogram.
 */
public static ImmutableSortedMultiset<Double> computeHistogram(Iterable<Double> input, double binSize) {
    final ImmutableSortedMultiset.Builder<Double> builder = ImmutableSortedMultiset.naturalOrder();
    for (final double d : input) {
        checkArgument(!Double.isInfinite(d) && !Double.isNaN(d), "Only finite numbers are accepted, found %s.",
                d);
        builder.add(Math.floor(d / binSize) * binSize);
    }
    return builder.build();
}

From source file:de.bund.bfr.knime.pmm.common.chart.ChartCreator.java

public JFreeChart getChart(List<String> idsToPaint) {
    if (paramX == null || paramY == null) {
        return new JFreeChart(null, JFreeChart.DEFAULT_TITLE_FONT, new XYPlot(), showLegend);
    }//from  w w w .j  a v  a2  s  .c  o  m

    NumberAxis xAxis = new NumberAxis(AttributeUtilities.getNameWithUnit(paramX, unitX, transformX));
    NumberAxis yAxis = new NumberAxis(AttributeUtilities.getNameWithUnit(paramY, unitY, transformY));
    XYPlot plot = new XYPlot(null, xAxis, yAxis, null);
    double usedMinX = Double.POSITIVE_INFINITY;
    double usedMaxX = Double.NEGATIVE_INFINITY;
    int index = 0;
    ColorAndShapeCreator colorAndShapeCreator = new ColorAndShapeCreator(idsToPaint.size());

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

        try {
            if (plotable != null) {
                if (plotable.getType() == Plotable.BOTH || plotable.getType() == Plotable.BOTH_STRICT) {
                    Double minArg = Plotable.transform(
                            plotable.convertToUnit(paramX, plotable.getMinArguments().get(paramX), unitX),
                            transformX);
                    Double maxArg = Plotable.transform(
                            plotable.convertToUnit(paramX, plotable.getMaxArguments().get(paramX), unitX),
                            transformX);

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

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

                    for (Map<String, Integer> choice : plotable.getAllChoices()) {
                        double[][] points = plotable.getPoints(paramX, paramY, unitX, unitY, transformX,
                                transformY, choice);

                        if (points != null) {
                            for (int i = 0; i < points[0].length; i++) {
                                if (isValid(points[0][i])) {
                                    usedMinX = Math.min(usedMinX, points[0][i]);
                                    usedMaxX = Math.max(usedMaxX, points[0][i]);
                                }
                            }
                        }
                    }
                } else if (plotable.getType() == Plotable.DATASET
                        || plotable.getType() == Plotable.DATASET_STRICT) {
                    double[][] points = plotable.getPoints(paramX, paramY, unitX, unitY, transformX,
                            transformY);

                    if (points != null) {
                        for (int i = 0; i < points[0].length; i++) {
                            if (isValid(points[0][i])) {
                                usedMinX = Math.min(usedMinX, points[0][i]);
                                usedMaxX = Math.max(usedMaxX, points[0][i]);
                            }
                        }
                    }
                } else if (plotable.getType() == Plotable.FUNCTION) {
                    Double minArg = Plotable.transform(
                            plotable.convertToUnit(paramX, plotable.getMinArguments().get(paramX), unitX),
                            transformX);
                    Double maxArg = Plotable.transform(
                            plotable.convertToUnit(paramX, plotable.getMaxArguments().get(paramX), unitX),
                            transformX);

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

                    if (isValid(maxArg)) {
                        usedMaxX = Math.max(usedMaxX, maxArg);
                    }
                } else if (plotable.getType() == Plotable.FUNCTION_SAMPLE) {
                    Double minArg = Plotable.transform(
                            plotable.convertToUnit(paramX, plotable.getMinArguments().get(paramX), unitX),
                            transformX);
                    Double maxArg = Plotable.transform(
                            plotable.convertToUnit(paramX, plotable.getMaxArguments().get(paramX), unitX),
                            transformX);

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

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

                    for (Double x : plotable.getSamples()) {
                        Double xx = Plotable.transform(plotable.convertToUnit(paramX, x, unitX), transformX);

                        if (isValid(xx)) {
                            usedMinX = Math.min(usedMinX, xx);
                            usedMaxX = Math.max(usedMaxX, xx);
                        }
                    }
                }
            }
        } catch (ConvertException e) {
        }
    }

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

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

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

    if (paramY.equals(AttributeUtilities.TIME) || paramY.equals(AttributeUtilities.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));
    }

    Set<ConvertException> convertExceptions = new LinkedHashSet<>();

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

        if (plotable != null && plotable.getType() == Plotable.DATASET) {
            try {
                plotDataSet(plot, plotable, id, colorAndShapeCreator.getColorList().get(index),
                        colorAndShapeCreator.getShapeList().get(index));
                index++;
            } catch (ConvertException e) {
                convertExceptions.add(e);
            }
        }
    }

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

        if (plotable != null && plotable.getType() == Plotable.DATASET_STRICT) {
            try {
                plotDataSetStrict(plot, plotable, id);
                index++;
            } catch (ConvertException e) {
                convertExceptions.add(e);
            }
        }
    }

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

        if (plotable != null && plotable.getType() == Plotable.FUNCTION) {
            try {
                plotFunction(plot, plotable, id, colorAndShapeCreator.getColorList().get(index),
                        colorAndShapeCreator.getShapeList().get(index), usedMinX, usedMaxX);
                index++;
            } catch (ConvertException e) {
                convertExceptions.add(e);
            }
        }
    }

    warnings = new ArrayList<>();

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

        if (plotable != null && plotable.getType() == Plotable.FUNCTION_SAMPLE) {
            try {
                plotFunctionSample(plot, plotable, id, colorAndShapeCreator.getColorList().get(index),
                        colorAndShapeCreator.getShapeList().get(index), usedMinX, usedMaxX, warnings);
                index++;
            } catch (ConvertException e) {
                convertExceptions.add(e);
            }
        }
    }

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

        if (plotable != null && plotable.getType() == Plotable.BOTH) {
            try {
                plotBoth(plot, plotable, id, colorAndShapeCreator.getColorList().get(index),
                        colorAndShapeCreator.getShapeList().get(index), usedMinX, usedMaxX);
                index++;
            } catch (ConvertException e) {
                convertExceptions.add(e);
            }
        }
    }

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

        if (plotable != null && plotable.getType() == Plotable.BOTH_STRICT) {
            try {
                plotBothStrict(plot, plotable, id, usedMinX, usedMaxX);
                index++;
            } catch (ConvertException e) {
                convertExceptions.add(e);
            }
        }
    }

    if (!convertExceptions.isEmpty()) {
        String warning = "Some datasets/functions cannot be converted to the desired unit\n";

        warning += "Uncovertable units: ";

        for (ConvertException e : convertExceptions) {
            warning += e.getFromUnit() + "->" + e.getToUnit() + ", ";
        }

        warning = warning.substring(0, warning.length() - 2);

        JOptionPane.showMessageDialog(this, warning, "Warning", JOptionPane.WARNING_MESSAGE);
    }

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

From source file:edu.duke.cs.osprey.voxq.QuadraticQFunction.java

private boolean erfcInvNumericsOK(double x, double refRange) {
    //some points near edges of bell curve make erfc inversion innaccurate.  Detect this.
    //refRange used to determine tolerance
    x = Math.abs(x);// w w w  .  java 2 s .  c  o  m
    double invResult = myErfcInv(Erf.erfc(x));
    if (Double.isInfinite(invResult))//definitely going to be a problem
        return false;
    else if (Math.abs(x - invResult) > 0.01 * refRange)
        return false;

    return true;
}