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:delfos.group.results.groupevaluationmeasures.MAE_byMemberStdDev.java

@Override
public GroupEvaluationMeasureResult getMeasureResult(GroupRecommenderSystemResult groupRecommenderSystemResult,
        DatasetLoader<? extends Rating> originalDatasetLoader, RelevanceCriteria relevanceCriteria,
        DatasetLoader<? extends Rating> trainingDatasetLoader,
        DatasetLoader<? extends Rating> testDatasetLoader) {

    TreeMap<Integer, MeanIterative> maeAllMembers = new TreeMap<>();

    for (GroupOfUsers groupOfUsers : groupRecommenderSystemResult.getGroupsOfUsers()) {
        Collection<Recommendation> groupRecommendations = groupRecommenderSystemResult
                .getGroupOutput(groupOfUsers).getRecommendations().getRecommendations();

        if (groupRecommendations.isEmpty()) {
            continue;
        }//from  www  .j av a 2 s .c  o m
        MeanIterative maeGroup = new MeanIterative();
        Map<Integer, MeanIterative> maeMembers = new TreeMap<>();
        for (User member : groupOfUsers.getMembers()) {
            maeMembers.put(member.getId(), new MeanIterative());
        }

        Map<Integer, Map<Integer, ? extends Rating>> groupTrueRatings = new TreeMap<>();

        groupOfUsers.getIdMembers().stream().forEach((idUser) -> {
            try {
                groupTrueRatings.put(idUser, testDatasetLoader.getRatingsDataset().getUserRatingsRated(idUser));
            } catch (UserNotFound ex) {
                ERROR_CODES.USER_NOT_FOUND.exit(ex);
            }
        });

        for (Recommendation recommendation : groupRecommendations) {
            if (Double.isNaN(recommendation.getPreference().doubleValue())) {
                continue;
            }
            int idItem = recommendation.getItem().getId();
            for (int idUser : groupOfUsers.getIdMembers()) {
                if (groupTrueRatings.get(idUser).containsKey(idItem)) {
                    double trueRating = groupTrueRatings.get(idUser).get(idItem).getRatingValue().doubleValue();
                    double predicted = recommendation.getPreference().doubleValue();
                    double absoluteError = Math.abs(predicted - trueRating);

                    maeGroup.addValue(absoluteError);
                    maeMembers.get(idUser).addValue(absoluteError);
                }
            }
        }

        maeAllMembers.putAll(maeMembers);

    }

    double[] maeByMember = maeAllMembers.values().parallelStream()
            .mapToDouble(meanMember -> meanMember.getMean()).filter(value -> !Double.isNaN(value)).toArray();

    double maeByMemberStdDev = new StandardDeviation().evaluate(maeByMember);

    if (maeByMember.length == 0) {
        return new GroupEvaluationMeasureResult(this, Double.NaN);
    } else {
        return new GroupEvaluationMeasureResult(this, maeByMemberStdDev);
    }
}

From source file:org.pentaho.platform.uifoundation.chart.BubbleRenderer.java

/**
 * Draws the visual representation of a single data item.
 * /*from w  w  w . j  a  va  2  s  . c o m*/
 * @param g2
 *          the graphics device.
 * @param state
 *          the renderer state.
 * @param dataArea
 *          the area within which the data is being drawn.
 * @param info
 *          collects information about the drawing.
 * @param plot
 *          the plot (can be used to obtain standard color information etc).
 * @param domainAxis
 *          the domain (horizontal) axis.
 * @param rangeAxis
 *          the range (vertical) axis.
 * @param dataset
 *          the dataset (an {@link XYZDataset} is expected).
 * @param series
 *          the series index (zero-based).
 * @param item
 *          the item index (zero-based).
 * @param crosshairState
 *          crosshair information for the plot (<code>null</code> permitted).
 * @param pass
 *          the pass index.
 */
@Override
public void drawItem(final Graphics2D g2, final XYItemRendererState state, final Rectangle2D dataArea,
        final PlotRenderingInfo info, final XYPlot plot, final ValueAxis domainAxis, final ValueAxis rangeAxis,
        final XYDataset dataset, final int series, final int item, final CrosshairState crosshairState,
        final int pass) {

    PlotOrientation orientation = plot.getOrientation();

    // get the data point...
    double x = dataset.getXValue(series, item);
    double y = dataset.getYValue(series, item);
    double z = Double.NaN;
    if (dataset instanceof XYZDataset) {
        XYZDataset xyzData = (XYZDataset) dataset;
        z = xyzData.getZValue(series, item);
    }
    if (!Double.isNaN(z)) {
        RectangleEdge domainAxisLocation = plot.getDomainAxisEdge();
        RectangleEdge rangeAxisLocation = plot.getRangeAxisEdge();
        double transX = domainAxis.valueToJava2D(x, dataArea, domainAxisLocation);
        double transY = rangeAxis.valueToJava2D(y, dataArea, rangeAxisLocation);

        double circleSize;

        circleSize = maxSize * (z / maxZ);

        circleSize = Math.abs(circleSize);

        Ellipse2D circle = null;
        if (orientation == PlotOrientation.VERTICAL) {
            circle = new Ellipse2D.Double(transX - circleSize / 2.0, transY - circleSize / 2.0, circleSize,
                    circleSize);
        } else if (orientation == PlotOrientation.HORIZONTAL) {
            circle = new Ellipse2D.Double(transY - circleSize / 2.0, transX - circleSize / 2.0, circleSize,
                    circleSize);
        }
        g2.setPaint(getItemPaint(series, item));
        g2.fill(circle);
        g2.setStroke(getItemOutlineStroke(series, item));
        g2.setPaint(getItemOutlinePaint(series, item));
        g2.draw(circle);

        if (isItemLabelVisible(series, item)) {
            if (orientation == PlotOrientation.VERTICAL) {
                drawItemLabel(g2, orientation, dataset, series, item, transX, transY, false);
            } else if (orientation == PlotOrientation.HORIZONTAL) {
                drawItemLabel(g2, orientation, dataset, series, item, transY, transX, false);
            }
        }

        // setup for collecting optional entity info...
        EntityCollection entities = null;
        if (info != null) {
            entities = info.getOwner().getEntityCollection();
        }

        // add an entity for the item...
        if (entities != null) {
            String tip = null;
            XYToolTipGenerator generator = getToolTipGenerator(series, item);
            if (generator != null) {
                tip = generator.generateToolTip(dataset, series, item);
            }
            String url = null;
            if (getURLGenerator() != null) {
                url = getURLGenerator().generateURL(dataset, series, item);
            }
            XYItemEntity entity = new XYItemEntity(circle, dataset, series, item, tip, url);
            entities.add(entity);
        }

        int domainAxisIndex = plot.getDomainAxisIndex(domainAxis);
        int rangeAxisIndex = plot.getRangeAxisIndex(rangeAxis);
        updateCrosshairValues(crosshairState, x, y, domainAxisIndex, rangeAxisIndex, transX, transY,
                orientation);
    }

}

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

@Test
public void testSetMissingValue() throws Exception {
    assertTrue("Missing value must be handled as missing",
            Double.isNaN(field.parseOrMissing(Attribute.MISSING_VALUE_STR)));
}

From source file:ChartUsingJava.XYSmoothLineAndShapeRenderer.java

/**
 * Draws the item (first pass). This method draws the lines
 * connecting the items.//from  w ww  .j a  v a  2 s .co  m
 *
 * @param g2  the graphics device.
 * @param state  the renderer state.
 * @param dataArea  the area within which the data is being drawn.
 * @param plot  the plot (can be used to obtain standard color
 *              information etc).
 * @param domainAxis  the domain axis.
 * @param rangeAxis  the range axis.
 * @param dataset  the dataset.
 * @param pass  the pass.
 * @param series  the series index (zero-based).
 * @param item  the item index (zero-based).
 */
protected void drawPrimaryLine(XYItemRendererState state, Graphics2D g2, XYPlot plot, XYDataset dataset,
        int pass, int series, int item, ValueAxis domainAxis, ValueAxis rangeAxis, Rectangle2D dataArea) {

    if (item == 0) {
        return;
    }

    // get the data point...
    double x1 = dataset.getXValue(series, item);
    double y1 = dataset.getYValue(series, item);
    if (Double.isNaN(y1) || Double.isNaN(x1)) {
        return;
    }

    double x0 = dataset.getXValue(series, item - 1);
    double y0 = dataset.getYValue(series, item - 1);
    if (Double.isNaN(y0) || Double.isNaN(x0)) {
        return;
    }

    RectangleEdge xAxisLocation = plot.getDomainAxisEdge();
    RectangleEdge yAxisLocation = plot.getRangeAxisEdge();

    double transX0 = domainAxis.valueToJava2D(x0, dataArea, xAxisLocation);
    double transY0 = rangeAxis.valueToJava2D(y0, dataArea, yAxisLocation);

    double transX1 = domainAxis.valueToJava2D(x1, dataArea, xAxisLocation);
    double transY1 = rangeAxis.valueToJava2D(y1, dataArea, yAxisLocation);

    // only draw if we have good values
    if (Double.isNaN(transX0) || Double.isNaN(transY0) || Double.isNaN(transX1) || Double.isNaN(transY1)) {
        return;
    }

    Point2D.Double point0 = new Point2D.Double();
    Point2D.Double point1 = new Point2D.Double();
    Point2D.Double point2 = new Point2D.Double();
    Point2D.Double point3 = new Point2D.Double();

    if (item == 1) {
        point0 = null;
    } else {
        point0.x = domainAxis.valueToJava2D(dataset.getXValue(series, item - 2), dataArea, xAxisLocation);
        point0.y = rangeAxis.valueToJava2D(dataset.getYValue(series, item - 2), dataArea, yAxisLocation);
    }

    point1.x = transX0;
    point1.y = transY0;

    point2.x = transX1;
    point2.y = transY1;

    if ((item + 1) == dataset.getItemCount(series)) {
        point3 = null;
    } else {
        point3.x = domainAxis.valueToJava2D(dataset.getXValue(series, item + 1), dataArea, xAxisLocation);
        point3.y = rangeAxis.valueToJava2D(dataset.getYValue(series, item + 1), dataArea, yAxisLocation);
    }

    int steps = ((int) ((point2.x - point1.x) / 0.2) < 30) ? (int) ((point2.x - point1.x) / 0.2) : 30;

    Point2D.Double[] points = getBezierCurve(point0, point1, point2, point3, 1, steps);

    for (int i = 1; i < points.length; i++) {
        transX0 = points[i - 1].x;
        transY0 = points[i - 1].y;
        transX1 = points[i].x;
        transY1 = points[i].y;

        PlotOrientation orientation = plot.getOrientation();
        if (orientation == PlotOrientation.HORIZONTAL) {
            state.workingLine.setLine(transY0, transX0, transY1, transX1);
        } else if (orientation == PlotOrientation.VERTICAL) {
            state.workingLine.setLine(transX0, transY0, transX1, transY1);
        }

        if (state.workingLine.intersects(dataArea)) {
            drawFirstPassShape(g2, pass, series, item, state.workingLine);
        }
    }
}

From source file:de.tudarmstadt.ukp.dkpro.wsd.graphconnectivity.iterative.wikipedia.algorithm.LinkInformationSequentialDisambiguation.java

private double computeLinkMeasureSimilarity(String target0, String target1) throws SimilarityException {
    if (target0.equals(target1)) {
        return 1.0;
    }//from w w  w .  j a  v a2 s. co m

    List<String> linksA;
    List<String> linksB;
    try {
        linksA = getIncomingLinks(target0);
        linksB = getIncomingLinks(target1);
    } catch (Exception e) {
        throw new SimilarityException();
    }

    int linksBoth = ListUtils.intersection(linksA, linksB).size();

    double a = Math.log(linksA.size());
    double b = Math.log(linksB.size());
    double ab = Math.log(linksBoth);
    double m = Math.log(linkInformationReader.getNumberOfSenses());

    double sr = (Math.max(a, b) - ab) / (m - Math.min(a, b));

    if (Double.isNaN(sr) || Double.isInfinite(sr) || sr > 1) {
        sr = 1;
    }

    sr = 1 - sr;

    return sr;

}

From source file:org.immutables.gson.stream.JsonGeneratorWriter.java

@Override
public JsonWriter value(Number value) throws IOException {
    if (value == null) {
        return nullValue();
    }/*from   ww w. j  av a  2  s  . c om*/
    double d = value.doubleValue();
    if (!isLenient()) {
        if (Double.isNaN(d) || Double.isInfinite(d)) {
            throw new IllegalArgumentException("JSON forbids NaN and infinities: " + value);
        }
    }
    generator.writeNumber(d);
    return this;
}

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

/**
 * 50th percentile./*from   w  w  w .j ava2 s. c  o m*/
 *
 * @return 50th percentile
 */
@Managed
@SuppressWarnings("unused")
public double getMillisTP50() {
    double percentile = millisStats.getPercentile(50);
    return Double.isNaN(percentile) ? 0.0 : percentile;
}

From source file:edu.harvard.iq.dataverse.util.SumStatCalculator.java

/**
 * Returns the number of Double.NaNs (or nulls) in a double-type array
 *
 *///from w w w .j  ava2  s. c om
private static int countInvalidValues(Number[] x) {
    int counter = 0;
    for (int i = 0; i < x.length; i++) {
        ////if ( x[i] == null || x[i].equals(Double.NaN) ) {
        if (x[i] == null || (Double.isNaN(x[i].doubleValue()))) {
            counter++;
        }
    }
    return counter;
}

From source file:edu.cmu.tetrad.search.TimeSeriesUtils.java

public static DataSet ar2(DataSet timeSeries, int numLags) {
    List<Node> missingVariables = new ArrayList<>();

    for (Node node : timeSeries.getVariables()) {
        int index = timeSeries.getVariables().indexOf(node);
        boolean missing = true;

        for (int i = 0; i < timeSeries.getNumRows(); i++) {
            if (!Double.isNaN(timeSeries.getDouble(i, index))) {
                missing = false;/*from  ww  w  .  j a va  2s .  c o  m*/
                break;
            }
        }

        if (missing) {
            missingVariables.add(node);
        }
    }

    DataSet timeLags = createLagData(timeSeries, numLags);

    Regression regression = new RegressionDataset(timeLags);

    TetradMatrix residuals = new TetradMatrix(timeLags.getNumRows(), timeSeries.getNumColumns());

    for (int i = 0; i < timeSeries.getNumColumns(); i++) {
        Node target = timeLags.getVariable(i);
        int index = timeSeries.getVariables().indexOf(target);

        if (missingVariables.contains(target)) {
            for (int i2 = 0; i2 < residuals.rows(); i2++) {
                residuals.set(i2, index, Double.NaN);
            }

            continue;
        }

        List<Node> regressors = new ArrayList<>();

        for (int i2 = timeSeries.getNumColumns(); i2 < timeLags.getNumColumns(); i2++) {
            int varIndex = i2 % timeSeries.getNumColumns();
            Node var = timeSeries.getVariable(varIndex);

            if (missingVariables.contains(var)) {
                continue;
            }

            regressors.add(timeLags.getVariable(i2));
        }

        RegressionResult result = regression.regress(target, regressors);
        TetradVector residualsColumn = result.getResiduals();
        residuals.assignColumn(i, residualsColumn);
    }

    return ColtDataSet.makeContinuousData(timeSeries.getVariables(), residuals);
}

From source file:mase.spec.HybridStat.java

@Override
public void postPreBreedingExchangeStatistics(EvolutionState state) {
    super.postPreBreedingExchangeStatistics(state);
    AbstractHybridExchanger exc = (AbstractHybridExchanger) state.exchanger;
    // generation, evaluations, and number of metapops
    state.output.print(state.generation + " " + ((MaseProblem) state.evaluator.p_problem).getTotalEvaluations()
            + " " + exc.metaPops.size(), log);

    DescriptiveStatistics ds = new DescriptiveStatistics();
    for (MetaPopulation mp : exc.metaPops) {
        ds.addValue(mp.agents.size());/*from   ww w.j  ava2  s.  c  o  m*/
    }
    // metapop size (min, mean, max)
    state.output.print(" " + ds.getMin() + " " + ds.getMean() + " " + ds.getMax(), log);

    // metapop mean and max age
    ds.clear();
    for (MetaPopulation mp : exc.metaPops) {
        ds.addValue(mp.age);
    }
    state.output.print(" " + ds.getMean() + " " + ds.getMax(), log);

    // number of splits and merges in this generation + total number of splits and merges
    totalMerges += exc.merges;
    totalSplits += exc.splits;
    state.output.print(" " + exc.merges + " " + exc.splits + " " + totalMerges + " " + totalSplits, log);

    if (exc instanceof StochasticHybridExchanger) {
        StochasticHybridExchanger she = (StochasticHybridExchanger) exc;
        // metapop difference to others
        ds.clear();
        for (int i = 0; i < she.distanceMatrix.length; i++) {
            for (int j = i + 1; j < she.distanceMatrix.length; j++) {
                if (!Double.isInfinite(she.distanceMatrix[i][j]) && !Double.isNaN(she.distanceMatrix[i][j])) {
                    ds.addValue(she.distanceMatrix[i][j]);
                }
            }
        }
        if (ds.getN() > 0) {
            state.output.print(" " + ds.getN() + " " + ds.getMin() + " " + ds.getMean() + " " + ds.getMax(),
                    log);
        } else {
            state.output.print(" 0 0 0 0", log);
        }

        //printMatrix(she.distanceMatrix, state);
    }

    state.output.println("", log);

    /*for(MetaPopulation mp : exc.metaPops) {
    StringBuilder sb = new StringBuilder();
    sb.append(String.format("%3d", mp.age)).append(" - ").append(mp.toString());
    if(!mp.foreigns.isEmpty()) {
        sb.append(" - Foreigns:");
    }
    for(Foreign f : mp.foreigns) {
        sb.append(" ").append(f.origin).append("(").append(f.age).append(")");
    }
    state.output.message(sb.toString());
    }*/

    /*for(MetaPopulation mp : exc.metaPops) {
    state.output.message(mp.age + "/" + mp.lockDown);
    }*/
}