Example usage for java.lang Double isNaN

List of usage examples for java.lang Double isNaN

Introduction

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

Prototype

public static boolean isNaN(double v) 

Source Link

Document

Returns true if the specified number is a Not-a-Number (NaN) value, false otherwise.

Usage

From source file:be.ugent.maf.cellmissy.analysis.singlecell.processing.impl.interpolation.TrackLoessInterpolator.java

@Override
public InterpolatedTrack interpolateTrack(double[] time, double[] x, double[] y) {
    // create a new interpolator
    LoessInterpolator loessInterpolator = new LoessInterpolator();
    int interpolationPoints = PropertiesConfigurationHolder.getInstance().getInt("numberOfInterpolationPoints");

    // create arrays to hold the interpolant time, the interpolated X and the interpolated Y
    double[] interpolantTime = new double[interpolationPoints];
    double[] interpolatedX = new double[interpolationPoints];
    double[] interpolatedY = new double[interpolationPoints];
    // the step used for the interpolation in both direction
    double interpolationStep = (time[time.length - 1] - time[0]) / interpolationPoints;

    // check for monotonicity
    boolean monotonic = MathArrays.isMonotonic(time, MathArrays.OrderDirection.INCREASING, false);
    // in case time is not monotonic, sort in place time, x and y coordinates
    if (!monotonic) {
        MathArrays.sortInPlace(time, x, y);
    }//from  w ww .ja va  2 s  .c o m

    // call the interpolator, and actually do the interpolation
    try {
        PolynomialSplineFunction functionX = loessInterpolator.interpolate(time, x);
        PolynomialSplineFunction functionY = loessInterpolator.interpolate(time, y);

        // get the polynomial functions in both directions
        PolynomialFunction polynomialFunctionX = functionX.getPolynomials()[0];
        PolynomialFunction polynomialFunctionY = functionY.getPolynomials()[0];

        for (int i = 0; i < interpolationPoints; i++) {
            interpolantTime[i] = time[0] + (i * interpolationStep);
            interpolatedX[i] = functionX.value(interpolantTime[i]);
            interpolatedY[i] = functionY.value(interpolantTime[i]);
        }

        for (int k = 0; k < interpolationPoints; k++) {
            if (Double.isNaN(interpolatedX[k]) | Double.isNaN(interpolatedY[k])) {
                return null;
            }
        }
        return new InterpolatedTrack(interpolantTime, interpolatedX, interpolatedY, polynomialFunctionX,
                polynomialFunctionY);
    } catch (NumberIsTooSmallException e) {
        LOG.error(e.getMessage());
        return null;
    }
}

From source file:gedi.util.math.stat.testing.DirichletLikelihoodRatioTest.java

public static double effectSizeMultinomials(double pseudo, double[]... samples) {

    double[][] psamples = new double[samples.length][];
    assert samples.length > 1;
    BitVector nans = new BitVector(samples[0].length);
    for (int i = 0; i < samples.length; i++) {
        assert samples[i].length == samples[0].length;
        for (int j = 0; j < samples[i].length; j++)
            if (Double.isNaN(samples[i][j]))
                nans.putQuick(j, true);/*  w ww  .  j  a  v a 2 s. c  o  m*/
    }
    nans.not();

    double sum = 0;
    for (int i = 0; i < samples.length; i++) {
        psamples[i] = ArrayUtils.restrict(samples[i], nans);

        assert ArrayUtils.min(psamples[i]) >= 0;
        sum += ArrayUtils.sum(psamples[i]);
    }

    for (int i = 0; i < samples.length; i++) {
        ArrayUtils.add(psamples[i], pseudo * ArrayUtils.sum(psamples[i]) / sum);
    }

    int dim = psamples[0].length;
    int obj = psamples.length;
    if (dim < 2)
        return Double.NaN;
    if (obj != 2)
        throw new RuntimeException("Can only compute the effect size for a pair of samples!");

    double exp = (Math.log(ArrayUtils.sum(psamples[0])) - Math.log(ArrayUtils.sum(psamples[1]))) / Math.log(2);

    double re = 0;
    for (int i = 0; i < dim; i++) {
        re += Math.abs(exp - (Math.log(psamples[0][i]) - Math.log(psamples[1][i])) / Math.log(2));
    }

    return re;

}

From source file:com.feedzai.fos.api.CategoricalAttributeTest.java

@Test
public void testSetFaultyValue() throws Exception {
    assertTrue("Faulty categorical value must be replaced", Double.isNaN(field.parseOrMissing("non_existant")));
}

From source file:com.ning.metrics.collector.util.Stats.java

/**
 * @return max/*w w w  .  ja v a 2 s. c  o  m*/
 */
@Managed
@SuppressWarnings("unused")
public double getMillisMax() {
    double max = millisStats.getMax();
    return Double.isNaN(max) ? 0.0 : max;
}

From source file:at.alladin.rmbt.controlServer.ResultUpdateResource.java

@Post("json")
public String request(final String entity) {
    addAllowOrigin();/*from   w  w  w.j a  va2  s .  c om*/

    JSONObject request = null;

    final ErrorList errorList = new ErrorList();
    final JSONObject answer = new JSONObject();

    final String ip = getIP();

    System.out.println(MessageFormat.format(labels.getString("NEW_RESULT_UPDATE"), ip));

    if (entity != null && !entity.isEmpty()) {
        try {
            request = new JSONObject(entity);
            final UUID clientUUID = UUID.fromString(request.getString("uuid"));
            final UUID testUUID = UUID.fromString(request.getString("test_uuid"));
            final int zipCode = request.optInt("zip_code", 0);
            final double geoLat = request.optDouble("geo_lat", Double.NaN);
            final double geoLong = request.optDouble("geo_long", Double.NaN);
            final float geoAccuracy = (float) request.optDouble("accuracy", 0);
            final String provider = request.optString("provider").toLowerCase();

            final Client client = new Client(conn);
            final long clientId = client.getClientByUuid(clientUUID);
            if (clientId < 0)
                throw new IllegalArgumentException("error while loading client");

            final Test test = new Test(conn);
            if (test.getTestByUuid(testUUID) < 0)
                throw new IllegalArgumentException("error while loading test");

            if (test.getField("client_id").longValue() != clientId)
                throw new IllegalArgumentException("client UUID does not match test");

            if (zipCode > 0) {
                ((IntField) test.getField("zip_code")).setValue(zipCode);
            }
            if (!Double.isNaN(geoLat) && !Double.isNaN(geoLong)
                    && (provider.equals(GEO_PROVIDER_GEOCODER) || provider.equals(GEO_PROVIDER_MANUAL))) {
                final GeoLocation geoloc = new GeoLocation(conn);
                geoloc.setTest_id(test.getUid());

                final Timestamp tstamp = java.sql.Timestamp
                        .valueOf(new Timestamp((new Date().getTime())).toString());
                geoloc.setTime(tstamp, TimeZone.getDefault().toString());
                geoloc.setAccuracy(geoAccuracy);
                geoloc.setGeo_lat(geoLat);
                geoloc.setGeo_long(geoLong);
                geoloc.setProvider(provider);
                geoloc.storeLocation();

                ((DoubleField) test.getField("geo_lat")).setValue(geoLat);
                ((DoubleField) test.getField("geo_long")).setValue(geoLong);
                ((DoubleField) test.getField("geo_accuracy")).setValue(geoAccuracy);
                test.getField("geo_provider").setString(provider);
            }

            test.storeTestResults(true);

            if (test.hasError())
                errorList.addError(test.getError());
        } catch (final JSONException e) {
            errorList.addError("ERROR_REQUEST_JSON");
            System.out.println("Error parsing JSDON Data " + e.toString());
        } catch (final IllegalArgumentException e) {
            errorList.addError("ERROR_REQUEST_JSON");
            System.out.println("Error parsing JSDON Data " + e.toString());
        }
    }

    return answer.toString();
}

From source file:org.jfree.data.statistics.BoxAndWhiskerCalculator.java

/**
 * Calculates the statistics required for a {@link BoxAndWhiskerItem}
 * from a list of <code>Number</code> objects.  Any items in the list
 * that are <code>null</code>, not an instance of <code>Number</code>, or
 * equivalent to <code>Double.NaN</code>, will be ignored.
 *
 * @param values  a list of numbers (a <code>null</code> list is not
 *                permitted)./*  www  .  j  a  v  a 2 s .c o m*/
 * @param stripNullAndNaNItems  a flag that controls the handling of null
 *     and NaN items.
 *
 * @return A box-and-whisker item.
 *
 * @since 1.0.3
 */
public static BoxAndWhiskerItem calculateBoxAndWhiskerStatistics(List values, boolean stripNullAndNaNItems) {

    ParamChecks.nullNotPermitted(values, "values");

    List vlist;
    if (stripNullAndNaNItems) {
        vlist = new ArrayList(values.size());
        Iterator iterator = values.listIterator();
        while (iterator.hasNext()) {
            Object obj = iterator.next();
            if (obj instanceof Number) {
                Number n = (Number) obj;
                double v = n.doubleValue();
                if (!Double.isNaN(v)) {
                    vlist.add(n);
                }
            }
        }
    } else {
        vlist = values;
    }
    Collections.sort(vlist);

    double mean = Statistics.calculateMean(vlist, false);
    double median = Statistics.calculateMedian(vlist, false);
    double q1 = calculateQ1(vlist);
    double q3 = calculateQ3(vlist);

    double interQuartileRange = q3 - q1;

    double upperOutlierThreshold = q3 + (interQuartileRange * 1.5);
    double lowerOutlierThreshold = q1 - (interQuartileRange * 1.5);

    double upperFaroutThreshold = q3 + (interQuartileRange * 2.0);
    double lowerFaroutThreshold = q1 - (interQuartileRange * 2.0);

    double minRegularValue = Double.POSITIVE_INFINITY;
    double maxRegularValue = Double.NEGATIVE_INFINITY;
    double minOutlier = Double.POSITIVE_INFINITY;
    double maxOutlier = Double.NEGATIVE_INFINITY;
    List outliers = new ArrayList();

    Iterator iterator = vlist.iterator();
    while (iterator.hasNext()) {
        Number number = (Number) iterator.next();
        double value = number.doubleValue();
        if (value > upperOutlierThreshold) {
            outliers.add(number);
            if (value > maxOutlier && value <= upperFaroutThreshold) {
                maxOutlier = value;
            }
        } else if (value < lowerOutlierThreshold) {
            outliers.add(number);
            if (value < minOutlier && value >= lowerFaroutThreshold) {
                minOutlier = value;
            }
        } else {
            minRegularValue = Math.min(minRegularValue, value);
            maxRegularValue = Math.max(maxRegularValue, value);
        }
        minOutlier = Math.min(minOutlier, minRegularValue);
        maxOutlier = Math.max(maxOutlier, maxRegularValue);
    }

    return new BoxAndWhiskerItem(new Double(mean), new Double(median), new Double(q1), new Double(q3),
            new Double(minRegularValue), new Double(maxRegularValue), new Double(minOutlier),
            new Double(maxOutlier), outliers);

}

From source file:com.clust4j.algo.preprocess.impute.MedianImputation.java

@Override
public double[][] transform(final double[][] dat) {
    checkMat(dat);/*  ww w .  j  ava 2  s.c om*/

    final LogTimer timer = new LogTimer();
    final double[][] copy = MatUtils.copy(dat);
    final int m = dat.length, n = dat[0].length;
    info("(" + getName() + ") performing median imputation on " + m + " x " + n + " dataset");

    // Operates in 2M * N
    for (int col = 0; col < n; col++) {
        final double median = VecUtils.nanMedian(MatUtils.getColumn(copy, col));

        int count = 0;
        for (int row = 0; row < m; row++) {
            if (Double.isNaN(copy[row][col])) {
                copy[row][col] = median;
                count++;
            }
        }

        info("(" + getName() + ") " + count + " NaN" + (count != 1 ? "s" : "") + " identified in column " + col
                + " (column median=" + median + ")");
    }

    sayBye(timer);
    return copy;
}

From source file:net.librec.similarity.AbstractRecommenderSimilarity.java

/**
 * Build social similarity matrix with trainMatrix in dataModel.
 *
 * @param dataModel/*from w  w w .j  av  a 2s . c  o m*/
 *            the input data model
 */
@Override
public void buildSimilarityMatrix(DataModel dataModel) {
    conf = dataModel.getContext().getConf();
    String similarityKey = conf.get("rec.recommender.similarity.key", "user");
    if (StringUtils.isNotBlank(similarityKey)) {
        if (StringUtils.equals(similarityKey, "social")) {
            buildSocialSimilarityMatrix(dataModel);
        } else {
            // calculate the similarity between users, or the similarity between
            // items.
            boolean isUser = StringUtils.equals(similarityKey, "user") ? true : false;
            SparseMatrix trainMatrix = dataModel.getDataSplitter().getTrainData();
            int numUsers = trainMatrix.numRows();
            int numItems = trainMatrix.numColumns();
            int count = isUser ? numUsers : numItems;

            similarityMatrix = new SymmMatrix(count);

            for (int i = 0; i < count; i++) {
                SparseVector thisVector = isUser ? trainMatrix.row(i) : trainMatrix.column(i);
                if (thisVector.getCount() == 0) {
                    continue;
                }
                // user/item itself exclusive
                for (int j = i + 1; j < count; j++) {
                    SparseVector thatVector = isUser ? trainMatrix.row(j) : trainMatrix.column(j);
                    if (thatVector.getCount() == 0) {
                        continue;
                    }

                    double sim = getCorrelation(thisVector, thatVector);
                    if (!Double.isNaN(sim)) {
                        similarityMatrix.set(i, j, sim);
                    }
                }
            }
        }
    }

}

From source file:com.clust4j.metrics.pairwise.TestDistanceEnums.java

@Test
public void testNaN() {
    final double[] a = new double[] { 0d, 0d, 0d };
    final double[] b = new double[] { 3d, 4d, Double.NaN };
    assertTrue(Double.isNaN(Distance.MANHATTAN.getDistance(a, b)));
    assertTrue(Double.isNaN(Distance.EUCLIDEAN.getDistance(a, b)));
}

From source file:at.jku.traces.json.UserTrace.java

@Override
public double length() {
    if (Double.isNaN(len)) {
        len = 0;/* ww w  .j a va 2s .  c  o  m*/
        for (int i = 0; i < trace.length - 1; i++) {
            len += MapUtils.getDistance(trace[i].getLatitude(), trace[i].getLongitude(),
                    trace[i + 1].getLatitude(), trace[i + 1].getLongitude());
        }
    }
    return 0;
}