Example usage for java.lang Double isFinite

List of usage examples for java.lang Double isFinite

Introduction

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

Prototype

public static boolean isFinite(double d) 

Source Link

Document

Returns true if the argument is a finite floating-point value; returns false otherwise (for NaN and infinity arguments).

Usage

From source file:de.bund.bfr.math.MathUtils.java

public static List<StartValues> createStartValuesList(List<ParamRange> ranges, int n,
        ToDoubleFunction<List<Double>> errorFunction, DoubleConsumer progessListener, ExecutionContext exec)
        throws CanceledExecutionException {
    List<StartValues> valuesList = new ArrayList<>();

    for (int i = 0; i < n; i++) {
        valuesList.add(new StartValues(Collections.nCopies(ranges.size(), i + 1.0), Double.POSITIVE_INFINITY));
    }/* w w  w  .  ja va 2  s  .c  om*/

    List<Integer> paramStepIndex = new ArrayList<>(Collections.nCopies(ranges.size(), 0));
    boolean done = false;
    int allStepSize = 1;
    int count = 0;

    for (ParamRange range : ranges) {
        allStepSize *= range.getStepCount();
    }

    while (!done) {
        List<Double> values = new ArrayList<>();

        for (int i = 0; i < ranges.size(); i++) {
            values.add(ranges.get(i).getMin() + paramStepIndex.get(i) * ranges.get(i).getStepSize());
        }

        double error = errorFunction.applyAsDouble(values);

        if (Double.isFinite(error) || error < valuesList.get(n - 1).getError()) {
            for (int i = 0; i < n; i++) {
                if (error < valuesList.get(i).getError()) {
                    valuesList.add(i, new StartValues(values, error));
                    valuesList.remove(n);
                    break;
                }
            }
        }

        for (int i = 0;; i++) {
            if (i >= ranges.size()) {
                done = true;
                break;
            }

            paramStepIndex.set(i, paramStepIndex.get(i) + 1);

            if (paramStepIndex.get(i) >= ranges.get(i).getStepCount()) {
                paramStepIndex.set(i, 0);
            } else {
                break;
            }
        }

        if (exec != null) {
            exec.checkCanceled();
        }

        progessListener.accept((double) ++count / (double) allStepSize);
    }

    return valuesList;
}

From source file:org.rhwlab.variationalbayesian.GaussianMixture.java

double lnSumP(double[] lnP) {

    // find the maximum
    double maxLnP = lnP[0];
    for (int k = 1; k < K; ++k) {
        if (lnP[k] > maxLnP) {
            maxLnP = lnP[k];/* w  ww .jav  a 2 s.c o m*/
        }
    }

    // subtract the maximum and exponentiate
    // sum is guaranted to be >= 1.0;
    double sum = 0.0;
    for (int k = 0; k < K; ++k) {
        sum = sum + Math.exp(lnP[k] - maxLnP);
    }
    if (!Double.isFinite(sum)) {
        return maxLnP;
    }
    return maxLnP + Math.log(sum);
}

From source file:de.bund.bfr.math.Evaluator.java

private static double[] getErrors(double[] valuesX, Map<String, Double> parserConstants,
        Map<String, Map<String, Double>> covariances, double extraVariance, int degreesOfFreedom,
        ParameterFunction f) throws ParseException {
    List<String> paramList = new ArrayList<>(covariances.keySet());
    Map<String, double[]> derivValues = new LinkedHashMap<>();
    Map<String, ParseException> exceptions = new LinkedHashMap<>();

    paramList.parallelStream().forEach(param -> {
        Map<String, Double> constantsMinus = new LinkedHashMap<>(parserConstants);
        Map<String, Double> constantsPlus = new LinkedHashMap<>(parserConstants);
        double value = parserConstants.get(param);

        constantsMinus.put(param, value - MathUtils.DERIV_EPSILON);
        constantsPlus.put(param, value + MathUtils.DERIV_EPSILON);

        double[] deriv = new double[valuesX.length];

        try {//from ww w . j a v a 2s. c o  m
            double[] valuesMinus = f.getValuesY(constantsMinus);
            double[] valuesPlus = f.getValuesY(constantsPlus);

            for (int i = 0; i < valuesX.length; i++) {
                deriv[i] = (valuesPlus[i] - valuesMinus[i]) / (2 * MathUtils.DERIV_EPSILON);
            }

            derivValues.put(param, deriv);
        } catch (ParseException e) {
            exceptions.put(param, e);
        }
    });

    if (!exceptions.isEmpty()) {
        throw exceptions.values().stream().findAny().get();
    }

    double[] valuesY = new double[valuesX.length];
    double conf95 = MathUtils.get95PercentConfidence(degreesOfFreedom);

    Arrays.fill(valuesY, Double.NaN);

    loop: for (int index = 0; index < valuesX.length; index++) {
        double variance = 0.0;
        int n = paramList.size();

        for (int i = 0; i < n; i++) {
            String param = paramList.get(i);
            double value = derivValues.get(param)[index];

            variance += value * value * covariances.get(param).get(param);

            if (!Double.isFinite(variance)) {
                continue loop;
            }
        }

        for (int i = 0; i < n - 1; i++) {
            for (int j = i + 1; j < n; j++) {
                String param1 = paramList.get(i);
                String param2 = paramList.get(j);

                variance += 2.0 * derivValues.get(param1)[index] * derivValues.get(param2)[index]
                        * covariances.get(param1).get(param2);

                if (!Double.isFinite(variance)) {
                    continue loop;
                }
            }
        }

        valuesY[index] = Math.sqrt(variance + extraVariance) * conf95;
    }

    return valuesY;
}

From source file:org.rhwlab.variationalbayesian.GaussianMixture.java

public void lnPi() {
    double l = Math.log(X.getN());
    for (int k = 0; k < K; ++k) {
        double pi = 0.0;
        for (int n = 0; n < X.getN(); ++n) {
            double adj = X.get(n).adjustedIntensity;
            pi = pi + adj * r.getEntry(n, k);
        }/*from   w  ww. j a va2  s .  co m*/
        double lnp = Math.log(pi);
        if (Double.isFinite(lnp)) {
            lnPi[k] = Math.log(pi) - l;
        } else {
            lnPi[k] = -10000;
            //                inModel[k] = false;
        }

    }
    /*        
            double aHat = 0.0;
            for (int k=0 ; k<K ; ++k){
    if (inModel[k]){
        aHat = aHat + alpha[k];
    }
            }
            double psi = Gamma.digamma(aHat);
            for (int k=0 ; k<K ; ++k){
    if (inModel[k]){
        lnPi[k] = Gamma.digamma(alpha[k])-psi;
         if (!Double.isFinite(lnPi[k])){
            inModel[k] = false;
        } 
    }
            } 
    */
}

From source file:de.bund.bfr.math.MathUtils.java

public static FirstOrderDifferentialEquations createDiffEquations(Parser parser, List<ASTNode> functions,
        List<String> dependentVariables, String timeVariable,
        Map<String, UnivariateFunction> variableFunctions) {
    return new FirstOrderDifferentialEquations() {

        @Override/*  w  w w  . ja va 2s .c o m*/
        public int getDimension() {
            return functions.size();
        }

        @Override
        public void computeDerivatives(double t, double[] y, double[] yDot)
                throws MaxCountExceededException, DimensionMismatchException {
            parser.setVarValue(timeVariable, t);
            variableFunctions.forEach((var, function) -> parser.setVarValue(var, function.value(t)));

            for (int i = 0; i < functions.size(); i++) {
                parser.setVarValue(dependentVariables.get(i), y[i]);
            }

            for (int i = 0; i < functions.size(); i++) {
                try {
                    double value = parser.evaluate(functions.get(i));

                    yDot[i] = Double.isFinite(value) ? value : Double.NaN;
                } catch (ParseException e) {
                    e.printStackTrace();
                    yDot[i] = Double.NaN;
                }
            }
        }
    };
}

From source file:de.tudarmstadt.lt.ltbot.postprocessor.DecesiveValueProducerPerplexity.java

@Override
protected void innerProcess(CrawlURI uri) throws InterruptedException {
    _currently_processed_uris.add(uri);//from  w  ww  .ja v a 2s.  c  o  m

    if (_paused_due_to_error) {
        // reconnect
        if (!connectStringProviderService() || !testStringProviderService()) {
            LOG.severe("No service connected.");
            getCrawlController().requestCrawlPause(); // do not crawl any further
            _paused_due_to_error = true;
            _lmprvdr = null;
            _currently_processed_uris.remove(uri);
            return;
        }
    }

    double perplexity = getPerplexity(uri);
    String perplexity_as_str = String.format("%012g", perplexity);
    addExtraInfo(uri, getExtraInfoValueFieldName(), perplexity_as_str);

    synchronized (_lck) {
        if (!Double.isFinite(perplexity) || perplexity <= 1) {
            _num_inf_values.incrementAndGet();
        } else {
            double temp = (_perplexity_avg * _num_values) + perplexity;
            _perplexity_avg = temp / ++_num_values;
            if (_perplexity_min > perplexity)
                _perplexity_min = perplexity;
            if (_perplexity_max < perplexity)
                _perplexity_max = perplexity;
            _last100PerplexityVaulues.add(perplexity);
        }
        _currently_processed_uris.remove(uri);
        _last_processed_uri = uri;
        _last_assigned_perplexity = perplexity;
    }

}

From source file:com.yahoo.egads.models.tsmm.OlympicModel2.java

@Override
public void train(final DataSequence data) throws Exception {
    initializeIndices(data, modelStartEpoch);

    final long size = data.size();
    ZonedDateTime model_ts = Instant.ofEpochSecond(modelStartEpoch).atZone(zone);
    ZonedDateTime end_ts = model_ts.plus(windowSize, windowUnits);
    int prediction_index = 0;
    final List<WeightedValue> accumulator = Lists.newArrayList();

    // start the loop and break once we've filled the model.
    while (true) {
        accumulator.clear();/*from ww  w .  j a  v a2s  .  c  o m*/
        for (int i = 0; i < windowTimes.length; i++) {
            if (indices[i] < 0 || indices[i] >= size) {
                continue;
            }

            // advance
            windowTimes[i] = windowTimes[i].plus(interval, intervalUnits);
            long interval_end = windowTimes[i].toEpochSecond();
            final List<Double> doubles = Lists.newArrayList();
            long first_ts = -1;
            while (indices[i] < size && data.get(indices[i]).time < interval_end) {
                if (Double.isFinite(data.get(indices[i]).value)) {
                    doubles.add((double) data.get(indices[i]).value);
                }
                if (first_ts < 0) {
                    first_ts = data.get(indices[i]).time;
                }
                indices[i]++;
            }

            if (!doubles.isEmpty()) {
                // TODO - for DST if we jumped back then we may have a
                // period
                // with more than we expect. In that case, depending on the
                // aggregator, we may need to use only part of the data.
                // TODO - potentially other aggregations.
                double sum = 0;
                for (final Double v : doubles) {
                    sum += v;
                }
                accumulator.add(new WeightedValue((sum / doubles.size()), i + 1));
            }
        }

        if (drop_lowest > 0 || drop_highest > 0) {
            if (drop_highest > drop_lowest) {
                WeightedValue.drop(accumulator, drop_highest, true);
                WeightedValue.drop(accumulator, drop_lowest, false);
            } else {
                WeightedValue.drop(accumulator, drop_lowest, false);
                WeightedValue.drop(accumulator, drop_highest, true);
            }
        }

        model.add(new Pair<Long, Double>(model_ts.toEpochSecond(),
                WeightedValue.aggregate(accumulator, windowAggregator)));

        model_ts = model_ts.plus(interval, intervalUnits);
        if (model_ts.toEpochSecond() > end_ts.toEpochSecond()) {
            prediction_index++;
            if (prediction_index >= futureWindows) {
                break;
            }
            model_ts = Instant.ofEpochSecond(modelStartEpoch).atZone(zone);
            model_ts = model_ts.plus((windowDistanceInterval * prediction_index), windowDistanceIntervalUnits);
            end_ts = model_ts.plus(windowSize, windowUnits);
            for (int i = 0; i < windowTimes.length; i++) {
                windowTimes[i] = null;
                indices[i] = 0;
            }
            initializeIndices(data, model_ts.toEpochSecond());
        }
    }
}

From source file:org.rhwlab.variationalbayesian.SuperVoxelGaussianMixture.java

static double[] normalizeLogP(double[] lnP) {
    double[] p = new double[lnP.length];

    // find the maximum
    double maxLnP = lnP[0];
    for (int i = 1; i < p.length; ++i) {
        if (lnP[i] > maxLnP) {
            maxLnP = lnP[i];//from   w w w.  jav  a 2  s .c  o m
        }
    }

    // subtract the maximum and exponentiate
    // sum is guaranted to be >= 1.0;
    double sum = 0.0;
    for (int i = 0; i < p.length; ++i) {
        p[i] = Math.exp(lnP[i] - maxLnP);
        if (!Double.isFinite(p[i])) {
            p[i] = 0.0;
        }
        sum = sum + p[i];
    }

    // normalize sum to 1
    for (int i = 0; i < p.length; ++i) {
        p[i] = p[i] / sum;
    }
    return p;
}

From source file:nl.rivm.cib.episim.model.disease.infection.MSEIRSTest.java

public static Observable<Entry<Double, long[]>> stochasticGillespie(final SIRConfig config,
        final double maxDt) {
    return Observable.create(sub -> {
        final double gamma = 1. / config.recovery();
        final double beta = gamma * config.reproduction();
        final long[] y = config.population();
        final double[] T = config.t();
        final double dt = Double.isFinite(maxDt) && maxDt > 0 ? maxDt : T[1];

        final Long seed = config.seed();
        final RandomGenerator rng = new MersenneTwister(seed == null ? System.currentTimeMillis() : seed);

        for (double t = T[0]; t < T[1];) {
            publishCopy(sub, t, y);//from ww  w .  j av  a  2  s  .c o m

            // SIR terms (flow rates)
            final double n = y[0] + y[1] + y[2], flow_si = beta * y[0] * y[1] / n, flow_ir = gamma * y[1],
                    flow_sum = flow_si + flow_ir;

            final double t2 = t + new ExponentialDistribution(rng, 1d / flow_sum).sample();

            // publish intermediate values
            for (double t1 = Math.min(t2, t + dt), tMax = Math.min(T[1], t2); t1 < tMax; t1 += dt)
                publishCopy(sub, t1, y);

            // advance time to next event
            t = t2;

            // determine event (s->i, i->r, ...)
            if (rng.nextDouble() < flow_si / flow_sum) {
                y[0]--; // from S
                y[1]++; // to I
            } else {
                y[1]--; // from I
                y[2]++; // to R
                if (y[0] != 0 && y[1] == 0) {
                    y[0]--; // from S
                    y[1]++; // to I
                }
            }
        }
        sub.onComplete();
    });
}

From source file:com.ivli.roim.controls.ChartControl.java

@Override
public void actionPerformed(ActionEvent e) {
    super.actionPerformed(e);
    final XYPlot plot = getChart().getXYPlot();

    switch (MENUS.translate(e.getActionCommand())) {
    case ADD:/* w w  w .jav a  2s  .c  o m*/
        if (null != iSeries && iSeries instanceof XYSeries) {
            addMarker(new DomainMarker(iDataItem.getXValue(), iSeries));
        }
        break;
    case EXPORT_CSV:
        if (null != iSeries && iSeries instanceof XYSeries) {
            FileOpenDialog dlg = new FileOpenDialog(
                    java.util.ResourceBundle.getBundle("com/ivli/roim/Bundle").getString("CHOICE_FILE_TO_OPEN"),
                    "csv", //NOI18N 
                    "CSV file", //NOI18N 
                    false);

            if (dlg.doModal()) {
                try (Writer pwr = new PrintWriter(dlg.getFileName())) { //NOI18N                              
                    for (int i = 0; i < iSeries.getItemCount(); ++i) {
                        XYDataItem xy = iSeries.getDataItem(i);
                        pwr.append(String.format("%f\t%f\n", xy.getXValue(), xy.getYValue())); //NOI18N                        
                    }
                    pwr.flush();
                    pwr.close();
                } catch (IOException ex) {
                    LOG.throwing(ex);
                }
            }
        }
        break;
    case MOVE_TO_MAX:
        iMarker.setValue(XYSeriesUtilities.getDomainValueOfMaximum(((DomainMarker) iMarker).getSeries()));
        break;//((DomainMarker)iMarker).moveToMaximum(DomainMarker.MOVETO.GLOBAL)); break;                           
    case MOVE_TO_MIN:
        iMarker.setValue(XYSeriesUtilities.getDomainValueOfMinimum(((DomainMarker) iMarker).getSeries()));
        break;
    case MOVE_TO_MEDIAN: {
        iMarker.setValue(XYSeriesUtilities.getDomainValueOfMaximum(((DomainMarker) iMarker).getSeries()));
        double medY = (iSeries.getMaxY() - iSeries.getMinY()) / 2.;
        double val = XYSeriesUtilities.getNearestX(iSeries, medY);

        if (Double.isFinite(val))
            iMarker.setValue(val);
    }
        ;
        break;
    case DELETE:
        removeMarker((DomainMarker) iMarker);
        break;
    case DELETE_ALL:
        plot.getDomainMarkers(Layer.FOREGROUND).clear();
        iInterpolations.stream().forEach((i) -> {
            i.close();
        });
        iInterpolations.clear();
        break;
    case FIT_LEFT:
    case FIT_RIGHT: {
        final FITDIR dir = (MENUS.FIT_LEFT == MENUS.translate(e.getActionCommand()) ? FITDIR.FIT_LEFT
                : FITDIR.FIT_RIGHT);

        List<DomainMarker> list = (new ArrayList<DomainMarker>(plot.getDomainMarkers(Layer.FOREGROUND)))
                .stream().filter((DomainMarker m) -> {
                    return ((DomainMarker) iMarker).getSeries() == m.getSeries();
                }).sorted((DomainMarker aLhs, DomainMarker aRhs) -> {
                    return (int) (aLhs.getValue() - aRhs.getValue());
                }).collect(Collectors.toList());

        LOG.debug("-->Found " + list.size() + " markers");

        switch (list.size()) {
        case 0:
            break;
        case 1:
            iInterpolations.add(new Interpolation((DomainMarker) iMarker, dir));
            break;
        case 2: //fallthrough as default
        default: {
            DomainMarker left = null, right = null;
            int ndx = list.indexOf(iMarker);
            if (dir == FITDIR.FIT_LEFT) {
                if (ndx >= 1) {
                    right = (DomainMarker) iMarker;
                    left = list.get(--ndx);
                    iInterpolations.add(new Interpolation(left, right));
                } else {
                    iInterpolations.add(new Interpolation((DomainMarker) iMarker, dir));
                }

            } else if (dir == FITDIR.FIT_RIGHT) {
                if (ndx < list.size() - 1) {
                    right = list.get(++ndx);
                    left = (DomainMarker) iMarker;
                    iInterpolations.add(new Interpolation(left, right));
                } else {
                    iInterpolations.add(new Interpolation((DomainMarker) iMarker, dir));
                }
            }
        }
            break;
        }
    }
        break;
    default:
        break;
    }

    dropSelection();
}